2017-05-26 111 views
0

我有一個2550x3300大小的JPEG文件(此文件是用質量級別90創建的)。該文件的物理大小爲2.5 MB。我想將這個圖像縮小到1288x1864(原始尺寸的50%)並保存爲相同的質量90.但是,我希望事先知道下采樣圖像的物理尺寸,即使在實際縮小尺寸之前。縮小圖像的大小預測

任何幫助表示讚賞!

這裏是我使用的代碼,

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

回答

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()將非常接近字節的圖像的大小。