java编写之jpg图⽚与base64编码之间的转换
/**
* @author zyq
* 将⽹络图⽚进⾏Base64位编码
* @param imgUrl
*
*/
public static String encodeWebImageToBase64(URL imgUrl){ //传⼊图⽚url,将⽹络图⽚编码为base64编码
String webArray;
ByteArrayOutputStream outputStream = null; //字节数组流,可以捕获内存缓冲区的数据,转换成字节数组(拓展:ByteArrayInputStream:可以将字节数组转化为输⼊流)
try {
BufferedImage bufferedImage = ad(imgUrl); //Image是⼀个抽象列,BufferedImage是Image的实现,Image和BufferedImage的主要作⽤就是将⼀副图⽚加载到内存中
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpg",outputStream);//将BufferedImage对象直接写出指定输出流outputStream,图⽚格式为jpg
}catch (MalformedURLException e){ //URL协议、格式或者路径错误异常
e.printStackTrace();
}catch (IOException e1){ //输⼊输出异常
e1.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder(); //BASE64Encoder,字符串加密算法
webArray = ByteArray()); //编码为base64编码(⽅法参数为字节数组),其中ByteArray()⽤于获取内存缓冲中的数据,并转换为字节数组
return webArray;
}
/**
* @author zyq
* 将本地图⽚进⾏Base64位编码
* @param imageFile
*/
java中字符串转数组public static String encodeLocImageToBase64(File imageFile){
String locArray;
ByteArrayOutputStream outputStream = null;
try {
BufferedImage bufferedImage = ad(imageFile);
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpg",outputStream);
}catch (MalformedURLException e1){
e1.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
locArray = ByteArray());
return locArray;
}
/**
* @author zyq
* 将base64编码的图⽚进⾏解码显⽰,并保存在指定路径
* @param base64code
* @param imagePath
* @param imageName
*/
public static void decodeBase64ToImage(String base64code,String imagePath,String imageName){
BASE64Decoder decoder = new BASE64Decoder(); //BASE64Decoder,base64编码解码算法,解码为字节数组
try {
FileOutputStream write = new FileOutputStream(new File(imagePath + imageName)); //⽂件输出流,是⽤于将数据写⼊File或FileDescriptor的输出流,其中
File(imagePath + imageName)创建⽂件,参数为⽂件名(⽂件路径)
byte[] decoderBytes = decoder.decodeBuffer(base64code); //解码,⽅法参数为base64加密编码
write.write(decoderBytes); //decoderBytes数组写⼊⽂件
write.close(); //关闭此⽂件输出流并释放与此流有关的所有系统资源}catch (IOException e){
e.printStackTrace();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。