Java基于Base64实现编码解码图片文件
BASE64编码是一种常用的字符编码,在很多地方都会用到。但base64不是安全领域下的加密解密算法。能起到安全作用的效果很差,而且很容易破解,他核心作用应该是传输数据的正确性,有些网关或系统只能使用ASCII字符。Base64就是用来将非ASCII字符的数据转换成ASCII字符的一种方法,而且base64特别适合在http,mime协议下快速传输数据。
1、编码与解码代码如下所示:
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.net.MalformedURLException;
importjava.net.URL;
importjavax.imageio.ImageIO;
importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;
/**
*@authorzxn
*@version创建时间:2014-7-2上午11:40:40
*
*/
publicclassImageUtils{
/**
*将网络图片进行Base64位编码
*
*@paramimgUrl
*图片的url路径,如http://.....xx.jpg
*@return
*/
publicstaticStringencodeImgageToBase64(URLimageUrl){//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
ByteArrayOutputStreamoutputStream=null;
try{
BufferedImagebufferedImage=ImageIO.read(imageUrl);
outputStream=newByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpg",outputStream);
}catch(MalformedURLExceptione1){
e1.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoderencoder=newBASE64Encoder();
returnencoder.encode(outputStream.toByteArray());//返回Base64编码过的字节数组字符串
}
/**
*将本地图片进行Base64位编码
*
*@paramimgUrl
*图片的url路径,如http://.....xx.jpg
*@return
*/
publicstaticStringencodeImgageToBase64(FileimageFile){//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
ByteArrayOutputStreamoutputStream=null;
try{
BufferedImagebufferedImage=ImageIO.read(imageFile);
outputStream=newByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpg",outputStream);
}catch(MalformedURLExceptione1){
e1.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoderencoder=newBASE64Encoder();
returnencoder.encode(outputStream.toByteArray());//返回Base64编码过的字节数组字符串
}
/**
*将Base64位编码的图片进行解码,并保存到指定目录
*
*@parambase64
*base64编码的图片信息
*@return
*/
publicstaticvoiddecodeBase64ToImage(Stringbase64,Stringpath,
StringimgName){
BASE64Decoderdecoder=newBASE64Decoder();
try{
FileOutputStreamwrite=newFileOutputStream(newFile(path
+imgName));
byte[]decoderBytes=decoder.decodeBuffer(base64);
write.write(decoderBytes);
write.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
2、直接在页面上显示base64编码的图片
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。