Levon Petrosyan Levon Petrosyan - 27 days ago 8
Android Question

How to compress Bitmap using PNG format?

I have a custom View(WorldMapView) and a map drawable(3209x1287,PNG,64-bit color,1.33M) and I am getting


java.lang.RuntimeException: Canvas: trying to draw too large(148679388bytes) bitmap.


I tried to compress like this.

WorldMapView worldMapView = (WorldMapView) itemView.findViewById(R.id.map_of_world);
Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(context, R.drawable.map)).getBitmap();
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
worldMapView.setImageBitmap(decoded);


But if you are using PNG format then it will not compress your image because PNG is a lossless format,so can anyone please suggest a solution?

Thank You in Advance.

Answer Source

I tried to compress like this

You cannot "compress" a Bitmap to another Bitmap. Images are compressed on disk in some file formats (e.g., PNG, JPEG, WebP). A Bitmap is always uncompressed.

if you are using PNG format then it will not compress your image because PNG is a lossless format

This is unrelated to your problem. PNG is an on-disk format. Bitmap is not. Going from a Bitmap to a Bitmap will not "compress" the bitmap, no matter what image format you use.

so can anyone please suggest a solution?

Reduce the resolution of the image by 90% or so.

Or, use a view that handles large images, such as this one.