JAVA实现网络/本地图片转BASE64存储代码示例
作者:小码农~LR
这篇文章主要给大家介绍了关于JAVA实现网络/本地图片转BASE64存储的相关资料,Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法,需要的朋友可以参考下
网络图片转BASE64
String encoder = "data:image/jpg;base64,"; //定义图片类型,方便前端直接使用
ByteArrayOutputStream data = new ByteArrayOutputStream();
URL url = new URL(picUrl);//picUrl为图片地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1){
data.write(bytes,0,len);
}
is.close();
BASE64Encoder base64Encoder = new BASE64Encoder();
encoder = encoder + base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();//这里去掉结果里面的"\r\n",也可以不去,但是不去的话需要使用的时候还是要去掉,所以为了方便就先去掉再存储如果是本地图片的话,其实和网络图片相差不多的,主要就是读取图片流的形式变一下
String encoder = "data:image/jpg;base64,"; //定义图片类型,方便前端直接使用
ByteArrayOutputStream data = new ByteArrayOutputStream();
String filePath = "filePath";//这里的filePath为本地存放图片的地址
FileInputStream is = new FileInputStream(filePath);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1){
data.write(bytes,0,len);
}
is.close();
BASE64Encoder base64Encoder = new BASE64Encoder();
encoder = encoder + base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();//这里去掉结果里面的"\r\n",也可以不去,但是不去的话需要使用的时候还是要去掉,所以为了方便就先去掉再存储附:Java实现图片和base64之间的互转
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
public class ImageUtil {
/**
* 图片转Base64码
* @param src
* @return
*/
public static String convertImageToBase64Str(String src) {
ByteArrayOutputStream baos = null;
try {
String suffix = src.substring(src.lastIndexOf(".") + 1);
File imageFile = new File(src);
BufferedImage bufferedImage = ImageIO.read(imageFile);
baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, suffix, baos);
byte[] bytes = baos.toByteArray();
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Base64码转图片
* @param base64String
* @param newSrc
*/
public static void convertBase64StrToImage(String base64String, String newSrc) {
ByteArrayInputStream bais = null;
try {
String suffix = newSrc.substring(newSrc.lastIndexOf(".") + 1);
byte[] bytes = Base64.getDecoder().decode(base64String);
bais = new ByteArrayInputStream(bytes);
BufferedImage bufferedImage = ImageIO.read(bais);
File imageFile = new File(newSrc);
ImageIO.write(bufferedImage, suffix, imageFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bais != null) {
bais.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}总结
到此这篇关于JAVA实现网络/本地图片转BASE64存储的文章就介绍到这了,更多相关JAVA图片转BASE64存储内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
