<span style="color: rgb(51, 51, 51); font-family: 'Microsoft YaHei'; font-size: 14px; line-height: 26px;">將圖片保存到本地時進行壓縮, 即將圖片從Bitmap形式變爲File形式時進行壓縮</span>
public static void compressBmpToFile(Bitmap bmp,File file){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 80;//個人喜歡從80開始,
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
看了很多網上關於圖片壓縮的總結,總覺得缺點效率,所以基於以上方法,做了優化處理。
以上的方法,會去一次一次減少10的形式去壓縮,我認爲:既然都知道圖片的大小了baos.toByteArray().length,
就可以根據你圖片的固定大小來算出來壓縮率,沒有必要一遍一遍的去試着壓縮,下面貼出部分代碼,僅作參考
</pre><pre name="code" class="html">private String handleDetailImage(Bitmap bitmap) {
String result = null;
FileOutputStream fos = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
result = System.currentTimeMillis() + ".jpg";
File file = new File(getDetailImageDir(), result);
fos = new FileOutputStream(file);
// FIXME
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int option = (int) (6144000D / baos.toByteArray().length);
baos.flush();
baos.close();
bitmap.compress(Bitmap.CompressFormat.JPEG, option>100?100:option, fos);
fos.flush();
} catch (Exception e) {
result = null;
} finally {
if (baos != null)
try {
baos.close();
} catch (IOException e) {
}
if (fos != null)
try {
fos.close();
} catch (IOException e) {
}
}
return result;
}
}