我正在開發一款安卓應用,該應用具有相機捕獲和照片上傳功能。如果設備具有高分辨率照相機,拍攝的圖像尺寸將非常大(1〜3MB或更多)。
由於應用程序需要將此圖像上傳到服務器,因此我需要在上傳前壓縮圖像。例如,如果相機捕獲1920x1080全分辨率照片,理想的輸出是保持圖像的16:9比例,將其壓縮爲640x360圖像,以降低某些圖像質量並使其以較小的字節數進行縮小。Android - 縮放並壓縮位圖
這是我的代碼(來自谷歌引用):
/**
* this class provide methods that can help compress the image size.
*
*/
public class ImageCompressHelper {
/**
* Calcuate how much to compress the image
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height/2;
final int halfWidth = width/2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight/inSampleSize) > reqHeight
&& (halfWidth/inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
/**
* resize image to 480x800
* @param filePath
* @return
*/
public static Bitmap getSmallBitmap(String filePath) {
File file = new File(filePath);
long originalSize = file.length();
MyLogger.Verbose("Original image size is: " + originalSize + " bytes.");
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize based on a preset ratio
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap compressedImage = BitmapFactory.decodeFile(filePath, options);
MyLogger.Verbose("Compressed image size is " + sizeOf(compressedImage) + " bytes");
return compressedImage;
}
與上述代碼的問題是:
- 它不能保持率,代碼迫使圖像大小調整爲爲480x800。如果用戶以另一個比例捕捉圖像,壓縮後圖像看起來不太好。
它運行不正常。無論原始文件大小如何,代碼將始終將圖像大小更改爲7990272byte。如果原始圖像尺寸是非常小的已經,它將使大(我的測試結果把我的牆,這是非常單色的圖片):
Original image size is: 990092 bytes.
Compressed image size is 7990272 bytes
我在問是否有更好的方式來壓縮照片,以便它可以順利上傳的建議?
的大小代替使用硬編碼的480×800大小 - 你應該計算出維持所需的縱橫比i動態輸出位圖的大小。e改變風景和人像。對於圖像大小 - 請記住,您正在比較原始*壓縮*文件大小與縮放*未壓縮*位圖大小。 – harism