Saving bitmap with getDrawingCache gives black image
Everything I tried with setDrawingCacheEnabled
and getDrawingCache
didnt work. The system was creating an image, but it just looked black.
Other people on SO seemed to have a similar problem, but the answers seemed to be either too complicated or irrelevant to my situation. Here are some of the ones I've looked at:
- Save view as bitmap, I only get black screen
- Screenshot shows black
- getDrawingCache always returns the same bitmap
- Convert view to bitmap on Android
- bitmap doesn't save only black image
- Custom view-to-bitmap conversion that returns a black image
And here is my code:
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
try {
FileOutputStream stream = new FileOutputStream(getApplicationContext().getCacheDir() + "/image.jpg");
bitmap.compress(CompressFormat.JPEG, 80, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
view.setDrawingCacheEnabled(false);
I have shared my answer below in case someone else makes the same mistake as me.
source to share
My problem was that mine view
was TextView
. The text TextView
was not black (naturally), and in the application the background looked white. However, I later remembered that the background view is transparent by default, so any color below is shown.
So I added android:background="@color/white"
xml to the layout for the view and it worked. When I scanned the image before I scanned the black text on a black background.
See @ BraisGabin's answer for an alternative way that doesn't require reimplementing the UI.
source to share
I just find the best option:
final boolean cachePreviousState = view.isDrawingCacheEnabled();
final int backgroundPreviousColor = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheEnabled(true);
view.setDrawingCacheBackgroundColor(0xfffafafa);
final Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheBackgroundColor(backgroundPreviousColor);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
view.setDrawingCacheEnabled(cachePreviousState);
Where 0xfffafafa
is the desired background color.
source to share
The code used below to get the image bitmap
to view it works fine.
public Bitmap loadBitmapFromView(View v) {
DisplayMetrics dm = getResources().getDisplayMetrics();
v.measure(View.MeasureSpec.makeMeasureSpec(dm.widthPixels,
View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(dm.heightPixels,
View.MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap =
Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
source to share