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

这是您的代码当前正在执行的操作:

//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字符串,并将解码的数据写入文件:

//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) {}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值