缩小图像的尺寸预测

时间:2017-05-26 03:25:42

标签: java android image imaging

我有一个2550x3300大小的JPEG文件(此文件的质量级别为90)。文件的物理大小为2.5 MB。我想将此图像缩小到1288x1864(原始尺寸的50%)并保存相同的质量90.但我想提前知道下采样图像的物理尺寸,甚至在实际缩小之前。< / p>

任何帮助表示赞赏!

这是我正在使用的代码,

`
//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();
`

1 个答案:

答案 0 :(得分:0)

压缩后很难预测图像的大小,因为压缩取决于图像的实际内容,有些图像压缩到比其他图像更小的尺寸,即使它们具有相同的尺寸。我建议的方法是尝试压缩内存中的图像,如字节数组,然后获取此数组的大小,这将是文件的大小给予或采取几个字节。此代码取自另一个答案,并根据您的需要进行了一些修改: 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()

现在jpegData.size()将非常接近图像的大小(以字节为单位)。