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:

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.

+3


source to share


3 answers


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.

+7


source


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.

+5


source


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;
}

      

0


source







All Articles