*本事例主要讲了如下几点:
* 1:将图片转换为BASE64加密字符串. * 2:将图片流转换为BASE64加密字符串. * 3:将BASE64加密字符串转换为图片.
* 4:在jsp文件中以引用的方式和BASE64加密字符串方式展示图片.
首先看工具类:
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* @author IluckySi
* @since 20150122
*/
public class ImageUtil {
private static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
private static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
/**
* 将图片转换为BASE64加密字符串.
* @param imagePath 图片路径.
* @param format 图片格式.
* @return
*/
public String convertImageToByte(String imagePath, String format) {
File file = new File(imagePath);
BufferedImage bi = null;
ByteArrayOutputStream baos = null;
String result = null;
try {
bi = ImageIO.read(file);
baos = new ByteArrayOutputStream();
ImageIO.write(bi, format == null ? \: format, baos);
byte[] bytes = baos.toByteArray();
result = encoder.encodeBuffer(bytes).trim();
System.out.println(\将图片转换为BASE64加密字符串成功!\
} catch (IOException e) {
System.out.println(\将图片转换为 BASE64加密字符串失败: \+ e);
} finally {
try {
if(baos != null) {
baos.close();
baos = null;
}
} catch (Exception e) {
System.out.println(\关闭文件流发生异常: \+ e);