0

So I'm using this code

Bitmap myBitmap = BitmapFactory.decodeFile(fname);

to load an image file. But sometimes the image loaded can be large like 512x512, and I don't want to now load all the 262144 pixels of the image, but load it scaled down. How can I do it?

Droemmelbert
  • 155
  • 1
  • 13
Flafy
  • 176
  • 1
  • 3
  • 15
  • Never mind a duplicate... [https://stackoverflow.com/questions/3331527/resize-a-large-bitmap-file-to-scaled-output-file-on-android](https://stackoverflow.com/questions/3331527/resize-a-large-bitmap-file-to-scaled-output-file-on-android) – Flafy Oct 28 '19 at 15:07
  • Possible duplicate of [Resize a large bitmap file to scaled output file on Android](https://stackoverflow.com/questions/3331527/resize-a-large-bitmap-file-to-scaled-output-file-on-android) – TofferJ Oct 28 '19 at 15:49

2 Answers2

0

Use Bitmap.Compress() like this:

Uri uri = Uri.fromFile(file);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); 
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, stream);

the QUALITY argument:

int: Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting

porya74
  • 102
  • 1
  • 9
0

You get original image with Bitmap myBitmap = BitmapFactory.decodeFile(fname).

Integer scaleValue;

Integer scaleHeight = desiredMaxPixelHeight/myBitmap.getHeight();
Integer scaleWidth = desiredMaxPixelWidth/myBitmap.getWidth();

if (scaleHeight < 1 && scaleWidth < 1) scaleValue = 1;
else if (scaleHeight > scaleWidth) scaleValue = scaleHeight;
else scaleValue = scaleWidth;

Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, myBitmap.getHeight()/scaleValue, myBitmap.getWidth()/scaleValue, false);

Scaling logic can be done better, but point is that you can check info about original bitmap and then create new scaled one with Bitmap.createScaledBitmap(oldBitmap,sizeX,sizeY,false)

Milan Kundacina
  • 309
  • 1
  • 8