[英]How to convert an image to a base64 string with gzip- android
我試圖轉換和壓縮從android上的文件路徑獲取的圖像 ,用base64的gzip轉換(我正在使用這個,因為我的桌面版本,用java編寫,也是這樣做的)。 這是我目前用於壓縮的內容:
Bitmap bm = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
String base64Str = null;
ByteArrayOutputStream out_bytes = new ByteArrayOutputStream();
OutputStream out = new Base64.OutputStream(out_bytes);
try {
out.write(data);
out.close();
byte[] encoded = out_bytes.toByteArray();
base64Str = Base64.encodeBytes(encoded, Base64.GZIP);
baos.close();
} catch (Exception e) {}
這是您的代碼目前所做的:
//1. Decode data from image file
Bitmap bm = BitmapFactory.decodeFile(imagePath);
...
//2. Compress decoded image data to JPEG format with max quality
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
...
//3. Encode compressed image data to base64
out.write(data);
...
//4. Compress to gzip format, before encoding gzipped data to base64
base64Str = Base64.encodeBytes(encoded, Base64.GZIP);
我不知道您的桌面版本是如何做到的,但是步驟3是不必要的,因為您正在執行與步驟4相同的操作。
(刪除部分答案)
編輯:以下代碼將從文件中讀取字節,gzip字節並將它們編碼為base64。 它適用於小於2 GB的所有可讀文件。 傳入Base64.encodeBytes
的字節將與文件中的字節相同,因此不會丟失任何信息(與上面的代碼相反,首先將數據轉換為JPEG格式)。
/*
* imagePath has changed name to path, as the file doesn't have to be an image.
*/
File file = new File(path);
long length = file.length();
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
if(length > Integer.MAX_VALUE) {
throw new IOException("File must be smaller than 2 GB.");
}
byte[] data = new byte[(int)length];
//Read bytes from file
bis.read(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis != null)
try { bis.close(); }
catch(IOException e) {}
}
//Gzip and encode to base64
String base64Str = Base64.encodeBytes(data, Base64.GZIP);
EDIT2:這應解碼base64 String
並將解碼后的數據寫入文件:
//outputPath is the path to the destination file.
//Decode base64 String (automatically detects and decompresses gzip)
byte[] data = Base64.decode(base64str);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputPath);
//Write data to file
fos.write(data);
} catch(IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
try { fos.close(); }
catch(IOException e) {}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.