Skip to content

Instantly share code, notes, and snippets.

@xinlc
Last active July 31, 2019 05:22
Show Gist options
  • Save xinlc/51dcabafde15b004a618ddc6ef153e36 to your computer and use it in GitHub Desktop.
Save xinlc/51dcabafde15b004a618ddc6ef153e36 to your computer and use it in GitHub Desktop.
java 处理图片 Base64
package test;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
public class Base64ImageUtil {
/**
* 图片转BASE64
*
* @param imagePath 路径
* @return
*/
public static String imageChangeBase64(String imagePath) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imagePath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
/**
* BASE转图片
*
* @param baseStr base64字符串
* @param imagePath 生成的图片
* @return
*/
public static boolean base64ChangeImage(String baseStr, String imagePath) {
if (baseStr == null) {
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// 解密
byte[] b = decoder.decodeBuffer(baseStr);
// 处理数据
// 因为byte是有符号的,它表示的范围是-127~127,如果要映射到无符号0~255,那么0~127不用改变,而-128~-1对应128~255。
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imagePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 如果上面不好用,就用这个
* @param baseStr
* @param imagePath
*/
public static void base64ChangeImage2(String baseStr, String imagePath) {
BufferedImage image = null;
byte[] imageByte = null;
try {
imageByte = DatatypeConverter.parseBase64Binary(baseStr);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(new ByteArrayInputStream(imageByte));
bis.close();
File outputfile = new File("e:\\sealImg.bmp");
ImageIO.write(image, "bmp", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//加密
// String basestr = imageChangeBase64("D://1.png");
// System.out.println(basestr);
//
String str = "data:image/png;base64,xxxxxxx=="; // 替换成真实的BASE64
String[] sr = str.split(",");
String a = sr[0];
String data = sr[1];
String imgType = a.substring(a.indexOf('/') + 1, a.indexOf(';'));
String imgName = UUID.randomUUID().toString().replaceAll("-","");
String imgPath = "D://" + imgName + "." + imgType;
//解密
base64ChangeImage(data,imgPath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment