有關Bitmap的轉圖片,壓縮,以及Base64加密。

1.轉圖片:app

public void saveBitmap(Bitmap bitmap) {
首先保存圖片 File appDir = new File(Environment.getExternalStorageDirectory(),"zxing_image");
if (!appDir.exists())
{ appDir.mkdir(); }
String fileName = "zxing_image" + ".png";
file = new File(appDir, fileName);
try { FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush(); fos.close(); }
catch (Exception e) { e.printStackTrace(); }}
}


2.Bitmap壓縮:
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中  
int options = 90;
while (baos.toByteArray().length / 1024 > 50) {//循環判斷若是壓縮後圖片是否大於100kb,大於繼續壓縮
baos.reset();//重置baos即清空baos 
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//這裏壓縮options%,把壓縮後的數據存放到baos中 
options -= 10;//每次都減小10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把壓縮後的數據baos存放到ByteArrayInputStream中 
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream數據生成圖片
return bitmap;
}

3.Bitmap轉Base64:
public static String bitmapToBase64(Bitmap bitmap) {

String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

baos.flush();
baos.close();

byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;}
相關文章
相關標籤/搜索