[Android演算法] bitmap 將圖片壓縮到指定的大小

來源:互聯網
上載者:User

標籤:

Bitmap壓縮到指定大小:

private void imageZoom() {
//圖片允許最大空間 單位:KB
double maxSize =400.00;
//將bitmap放至數組中,意在bitmap的大小(與實際讀取的原檔案要大)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
//將位元組換成KB
double mid = b.length/1024;
//判斷bitmap佔用空間是否大於允許最大空間 如果大於則壓縮 小於則不壓縮
if (mid > maxSize) {
//擷取bitmap大小 是允許最大大小的多少倍
double i = mid / maxSize;
//開始壓縮 此處用到平方根 將寬頻和高度壓縮掉對應的平方根倍 (1.保持刻度和高度和原bitmap比率一致,壓縮後也達到了最大大小佔用空間的大小)
bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
bitMap.getHeight() / Math.sqrt(i));
}
}



public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
double newHeight) {
// 擷取這個圖片的寬和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();
// 建立操作圖片用的matrix對象
Matrix matrix = new Matrix();
// 計算寬高縮放率
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 縮放圖片動作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}

壓縮後的圖片比預期要大10% 原因可能是bitmap圖的寬高不一致,導致壓縮誤差!

[Android演算法] bitmap 將圖片壓縮到指定的大小

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.