这两天写一个base64转图片的功能,却发现转出的图片怎么出是损坏点,搞不清怎么回事,后面才发现原因。在此记录一下。

最开始的代码是调用的之前写好的代码,如下,转换后的图片都打不开。

/**

* Base64图片 转 图片

* @param path 要上传到的图片位置

* @param imgStr base64图片

* @param imgName 图片名称

* @return 返回图片名字

* @throws IOException

*/

public static String base64ToImg(String path, String imgStr, String imgName) throws IOException {

BASE64Decoder decoder = new BASE64Decoder();

byte[] b = decoder.decodeBuffer(imgStr);

for (int i = 0; i < b.length; ++i) {

if (b[i] < 0) {// 调整异常数据

b[i] += 256;

}

}

File file = new File(path);

if (!file.exists()) {

file.mkdirs();

}

String imgPath = path + imgName + ".png";

OutputStream out = new FileOutputStream(imgPath);

//写入数据

out.write(b);

out.flush();

out.close();

return imgName + ".png";

}

后面才发现,原来问题是转换的时候必须将 前面的data:image/jpeg;base64,这一段给去掉 ,如果不去掉转换就有问题,我去掉之后,还是发现不行,这个时候大家要注意一下,是不是去掉错误了,这一段 data:image/jpeg;base64, 标记的格式还可能是png jpg等格式,去除的时候,要根据你们的业务约定去除相应格式的 这个标记。

/**

* base64 这个转换base64图片为图片的时候需要做一些转换

* @param img base64

* @param path 存储路径

* @param imgName 图片名

* @throws IOException

* @return 返回图片名字

*/

public static String base64ToImgTransformation(String path, String img, String imgName) throws IOException {

if (CheckUtil.checkNull(img)){

return null;

}

BASE64Decoder decoder = new BASE64Decoder();

//前台在用Ajax传base64值的时候会把base64中的+换成空格,所以需要替换回来。

String baseValue = img.replaceAll(" ", "+");

//去除base64中无用的部分

byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/png;base64,", ""));

for (int i = 0; i < b.length; ++i) {

// 调整异常数据

if (b[i] < 0) {

b[i] += 256;

}

}

File file = new File(path);

if (!file.exists()) {

file.mkdirs();

}

String imgPath = path + imgName + ".png";

OutputStream out = new FileOutputStream(imgPath);

//写入数据

out.write(b);

out.flush();

out.close();

return imgName + ".png";

}

最终的代码如上, 将

baseValue.replace("data:image/png;base64,"

写为我的格式就成功了。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐