1

Suppose I have an image of size 20mb, I need to scale it down to a max of target size 15Mb. How do I achieve this?

I don't find any api other than createScaledBitmap which just takes the image, its height and width , but doesn't have a target size.

How can I achieve this? should I blindly keep trying with different width and height until it scales down to a <= target size?

Please help.

Lilith River
  • 16,204
  • 2
  • 44
  • 76

2 Answers2

0

Did you check this link

As far as i know you scale image size or the file size with Bitmap

Community
  • 1
  • 1
  • I did check this link , but like my comment in the previous advice even this link suggests to have a **DESIRED_WIDTH, DESIRED_HEIGHT** value. But my case is I have a target size but there is no specific limitation on width and height.. – Android_dev_new Oct 08 '16 at 14:09
0

Use this code for resizing the image

// Draw Bitmap on Canvas
public void setBitmap(String imageUrl){

    Bitmap myBitmap = BitmapFactory.decodeFile(imageUrl);

    Bitmap scaleBitmap = null;
    int bWidth = myBitmap.getWidth();
    int bHeight = myBitmap.getHeight();
    int diff = 0;

    Log.d(TAG, "bitmapWidth = " + bitmapWidth + " bitmapHeight = " + bitmapHeight);

    Log.d(TAG, "bWidth = " + bWidth + " bHeight = " + bHeight);

    if(bWidth >= bHeight){

        if(bWidth > bitmapWidth ){

            // landscape
            float ratio = (float) bWidth / bitmapWidth;
            diff = bWidth - bitmapWidth;
            bHeight = (int)(bHeight / ratio);
            scaleBitmap = Bitmap.createScaledBitmap(myBitmap, bWidth - diff, bHeight, false);
        }
        else{

            scaleBitmap = myBitmap;
        }
    }
    else{

        if(bHeight > bitmapHeight){

            float ratio = (float) bHeight / bitmapHeight;
            diff = bHeight - bitmapHeight;
            bWidth = (int)(bWidth / ratio);
            scaleBitmap = Bitmap.createScaledBitmap(myBitmap, bWidth, bHeight - diff, false);
        }
        else{

            scaleBitmap = myBitmap;
        }
    }



    canvasBitmap = scaleBitmap;
    invalidate();

}

Do raise the arrow so that other can also get the link for resizing the image.

gautam90
  • 58
  • 7