gpt4 book ai didi

java - 如何使用 gzip-android 将图像转换为 base64 字符串

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:29 29 4
gpt4 key购买 nike

我正在尝试转换和压缩从 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) {}
}

关于java - 如何使用 gzip-android 将图像转换为 base64 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379904/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com