Java# Java对图片进行base64编解码
Posted LRcoding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java# Java对图片进行base64编解码相关的知识,希望对你有一定的参考价值。
1. 解码BASE64
protected static String generateImage(String imgStr, String path) throws IOException {
// data:image/jpeg;base64,
int start = imgStr.indexOf("/");
int end = imgStr.indexOf(";");
String ext = "." + imgStr.substring(start + 1, end);
imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
// Base64解码
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
// 存放位置,文件夹按日期区分
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
SimpleDateFormat fileSdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String time = sdf.format(new Date());
String fileName = fileSdf.format(new Date()) + ext;
File file = new File("C:/file_upload/" + path + time);
if(!file.exists()){
file.mkdirs();
}
OutputStream out = new FileOutputStream(file + "/" + fileName);
out.write(b);
out.flush();
out.close();
String photo_address = path + time + "/" + fileName;
return photo_address;
}
2. BASE64加密
protected String getImageStr(String filePath) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(filePath);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
以上是关于Java# Java对图片进行base64编解码的主要内容,如果未能解决你的问题,请参考以下文章
Java 中,对Oracle Clob中的图片Base64进行解码后用System.out.println() 输出为啥成乱码,求高手帮忙。