Java 中使用 Base64 编码处理图片
很多初学者可能不知道什么是 urlencode、urldecode 以及图片的 Base64 编码。今天我就给大家写一篇 Java 处理 Base64 编码图片的教程。
编码与解码代码非常的简单,我直接贴出来,如下所示:
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class ImageUtils {
/**
* 将网络图片进行Base64位编码
* @param imgUrl 图片的url路径,如http://.....xx.jpg
* @return
*/
public static String encodeImgageToBase64(URL imageUrl) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(imageUrl);
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(outputStream.toByteArray());
}
/**
* 将本地图片进行Base64位编码
* @param imgUrl 图片的url路径,如http://.....xx.jpg
* @return
*/
public static String encodeImgageToBase64(File imageFile) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ImageIO.read(imageFile);
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", outputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(outputStream.toByteArray());
}
/**
* @param base64编码的图片信息
* @return
*/
public static void decodeBase64ToImage(String base64, String path,
String imgName) {
BASE64Decoder decoder = new BASE64Decoder();
try {
FileOutputStream write = new FileOutputStream(new File(path + imgName));
byte[] decoderBytes = decoder.decodeBuffer(base64);
write.write(decoderBytes);
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Base64 编码后的图片,都是以 data:image/jpeg;base64 开头的。
编码后的图片,我们就可以在 html 中直接使用。
<html>
<body>
<img src='data:image/jpg;base64,/9j/......'/>
</body>
</html>
如果是第三方的接口调用,转化成 Base64 后的图片,就不需要再经过上传操作了。第三方直接拿到 Base64 后的图片数据,进行分析,处理。
以百度的人脸识别接口,就是这样的。https://ai.baidu.com/docs#/Face-Detect-V3/top。百度给的案例介绍的已经非常的清楚了。如果到这里你还不懂这个接口怎么调用,那我也没办法了。
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2021/04/19 09:25