java 图片处理 base64编码和图片二进制编码相互转换

时间:2023-03-09 02:59:50
java 图片处理 base64编码和图片二进制编码相互转换

  今天在弄小程序项目时,涉及上传图片的更改。

  以下是代码:

 /**
* -> base64
* @param imgFile
* @return
* @throws IOException
*/
public static String getImageStr(String imgFile) throws IOException {
InputStream inputStream = null;
byte[] data = null; inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close(); // 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
 /**
* base64 ->
* @param imgStr
* @param path
* @return
* @throws IOException
*/
public static boolean generateImage(String imgStr, String path) throws IOException {
if (imgStr == null){
return false;
}
BASE64Decoder decoder = new BASE64Decoder(); //解密
byte[] b = decoder.decodeBuffer(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
}
 public static void main(String[] args) throws IOException {
//图片 -》 base64
String imgFile = "F:/Desktop/tupain/kaoshiwancheng.jpg";
getImageStr(imgFile); //base64 -> 图片
String imgStr = "imgStr";
String path = "F:/Desktop/tupain/kaoshiwancheng.jpg";
generateImage(imgStr, path); }

  不过需要注意的是,一般插件返回的base64编码的字符串都是有一个前缀的。"data:image/jpeg;base64," 解码之前这个得去掉。

  引用:https://www.cnblogs.com/libra0920/p/5754356.html