简体   繁体   中英

Android: Quality loss when downscaling Bitmap

I'm getting an image (.png) from SQLiteDatabase and using this code to decode the bytearray into a bitmap:

Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inDither = true;
options.inScaled = true;
options.inDensity = 240;
options.inTargetDensity = metrics.densityDpi;
Bitmap bmp = BitmapFactory.decodeStream(new ByteArrayInputStream(imageAsBytes), null, options);

As you can see, image (3) should be like (2), but it doesn't.

1) 原版的 = Image with no scale (metrics.densityDpi = 240);

2) 来自可绘制资源 = same .png above, but compiled in res/drawable;

3) 从低档 = Image with down scale (with metrics.densityDpi = 120);

I also tried options.inDither = false; , but I see no difference.

So what's wrong with my code?

There a few other things I would try:

  1. Load the png with no scale, when you come to draw the Image (either from within an ImageView or directly onto the canvas) set a Matrix to scale the image

  2. Alternatively, load the image in the required density and try drawing the Bitmap directly to the canvas with a Paint object. After instantiating your Paint, enable Bitmap filtering (this will increase the image quality)

     setFilterBitmap(true) 
  3. Finally, you could always load the Bitmap (density independent) and resize the Bitmap manually using Bitmap.createScaledBitmap , make sure you set the third paramenter to true (this enabled bitmap filtering for increased quality). Below is an example of scaling a bitmap where 100 is the desired size:

     Bitmap.createScaledBitmap ( original_bitmap, 100, 100, true); 

Briefly, the best quality downscaling algorithm consists of 2 steps:

  1. downscale using BitmapFactory.Options::inSampleSize->BitmapFactory.decodeResource() as close as possible to the resolution that you need but not less than it
  2. get to the exact resolution by downscaling a little bit using Canvas::drawBitmap()

Here is detailed explanation how SonyMobile resolved this task: http://developer.sonymobile.com/2011/06/27/how-to-scale-images-for-your-android-application/

Here is the source code of SonyMobile scale utils: http://developer.sonymobile.com/downloads/code-example-module/image-scaling-code-example-for-android/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM