在android中的很多應用中都需要拍照上傳圖片,隨着手機的像素越來越高,拍攝的圖片也越來越大。在拍攝後顯示的時候,使用universalimageloader.這個開源項目可以避免內存溢出。但是在上傳的時候,一般需要壓縮,但是壓縮的時候很容易導致內存溢出。解決的辦法就是,壓縮後的二進制流,不用導出Bitmap,而是直接存儲爲本地文件,上傳的時候直接通過本地文件上傳。代碼如下:
1.圖片壓縮獲取輸入流
/**
* 壓縮圖片獲取輸入流
* @param image
* @return
*/
public static InputStream compressImage3(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { // 循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
baos.reset();// 重置baos即清空baos
options -= 10;// 每次都減少10
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這裏壓縮options%,把壓縮後的數據存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮後的數據baos存放到ByteArrayInputStream中
//Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數據生成圖片
//return bitmap;
return isBm;
}
2.將輸入流寫入文件,代碼如下:
InputStream in=ImageLoadUtil.compressImage3(bitmap);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(file);
byte[] buf=new byte[64];
int len;
while((len=in.read(buf))>-1){
out.write(buf, 0, len);
}
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}