I have a URI image file and I want to reduce its size in order to upload it. The size of the original image file depends on the mobile phone (maybe 2 MB, or maybe 500 KB), but I want the final size to be about 200 KB so that I can download it.
From what I read, I have (at least) 2 options:
- Using BitmapFactory.Options.inSampleSize to select the source image and get a smaller image;
- Using Bitmap.compress to compress an image that determines the quality of compression.
What is the best choice?
I thought at first changing the size / height of the image until the width or height exceeds 1000 pixels (something like 1024x768 or others), and then compress the image with a decrease in quality until the file size is above 200 KB. Here is an example:
int MAX_IMAGE_SIZE = 200 * 1024; // max final file size Bitmap bmpPic = BitmapFactory.decodeFile(fileUri.getPath()); if ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) { BitmapFactory.Options bmpOptions = new BitmapFactory.Options(); bmpOptions.inSampleSize = 1; while ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) { bmpOptions.inSampleSize++; bmpPic = BitmapFactory.decodeFile(fileUri.getPath(), bmpOptions); } Log.d(TAG, "Resize: " + bmpOptions.inSampleSize); } int compressQuality = 104; // quality decreasing by 5 every loop. (start from 99) int streamLength = MAX_IMAGE_SIZE; while (streamLength >= MAX_IMAGE_SIZE) { ByteArrayOutputStream bmpStream = new ByteArrayOutputStream(); compressQuality -= 5; Log.d(TAG, "Quality: " + compressQuality); bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream); byte[] bmpPicByteArray = bmpStream.toByteArray(); streamLength = bmpPicByteArray.length; Log.d(TAG, "Size: " + streamLength); } try { FileOutputStream bmpFile = new FileOutputStream(finalPath); bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpFile); bmpFile.flush(); bmpFile.close(); } catch (Exception e) { Log.e(TAG, "Error on saving file"); }
Is there a better way to do this? Should I try to use all 2 methods or only one? Thanks
android bitmap image-uploading image-resizing
KitKat Jun 16 '12 at 6:11 2012-06-16 06:11
source share