0

I have a JPEG file of 2550x3300 size (this file was created with quality level 90). The physical size of the file is 2.5 MB. I would like to scale down this image to 1288x1864 (50% of the original dimension) and save with same quality 90. But I want to know the physical size of the down sampled image in advance, even before doing the actual scale down.

Any help is appreciated!

Here is the code I am using,

`
//Decodes the existing file to bitmap
Bitmap srcBP = BitmapFactory.decodeFile(filePath, options);
//Calculates required width and height
int reqWidth = options.outWidth * .50;
int reqHeight = options.outHeight * .50;
//Creates scaled image
Bitmap outBP = Bitmap.createScaledBitmap(srcBP, reqWidth, reqHeight, false);
//Save modified as JPEG
File tempFile = new File(imageOutPath);
FileOutputStream out = new FileOutputStream(tempFile);
outBP.compress(Bitmap.CompressFormat.JPEG, compression, out);
out.close();
`
coder
  • 312
  • 3
  • 12

1 Answers1

0

Is hard to predict the size of the image after compression because compression depends on the actual content of the image, some images compress to smaller size than others even they have the same dimensions. The approach I would suggest is to try and compress the image in memory like a byte array, then get the size of this array and that would be the size of the file give or take a few bytes. This code taken from another answer and modified a little bit to your needs: Java BufferedImage JPG compression without writing to file

ByteArrayOutputStream compressed = new ByteArrayOutputStream();
ImageOutputStream outputStream = 
ImageIO.createImageOutputStream(compressed);
ImageWriter jpgWriter = 
ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(0.9f);
jpgWriter.setOutput(outputStream);
int reqWidth = options.outWidth * .50;
int reqHeight = options.outHeight * .50;
BufferedImage img = new BufferedImage(reqWidth , reqHeight, BufferedImage.TYPE_INT_ARGB);;
try {
    img = ImageIO.read(new File(filepath));
} catch (IOException e) {
}

jpgWriter.write(null, new IIOImage(img, null, null), jpgWriteParam);
jpgWriter.dispose();
byte[] jpegData = compressed.toByteArray()

Now jpegData.size() will be very close to the size of your image in bytes.

AbelSurace
  • 2,263
  • 1
  • 12
  • 16