importjava.awt.image.BufferedImage;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjavax.imageio.ImageIO;importjavax.servlet.http.HttpServletResponse;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;
@Controller
@RequestMapping("/imgs/")public classtest {
@RequestMapping("test")public void test(HttpServletResponse response) throwsIOException {//写给浏览器
response.setContentType("image/jpeg");//浏览器不要缓存
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
BufferedImage buffImg= ImageIO.read(new FileInputStream("g://timg.jpg"));
ImageIO.write(buffImg,"jpg", response.getOutputStream());
}
@RequestMapping("test1")public void test1(HttpServletResponse response) throwsIOException {try{
response.setContentType("image/jpeg");
OutputStream toClient=response.getOutputStream();
String xmlImg= GetImageStr("g://timg.jpg");
GenerateImage(xmlImg, toClient);
}catch(Exception ex) {
System.out.println(ex.toString());
}
}
@RequestMapping("test2")public void test2(HttpServletResponse response) throwsIOException {try{
response.setContentType("text/html");
String xmlImg= GetImageStr("g://timg.jpg");
System.out.println(xmlImg);
response.getWriter().write("
}catch(Exception ex) {
System.out.println(ex.toString());
}
}public static booleanGenerateImage(String imgStr, OutputStream out) {if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder= newBASE64Decoder();try{//Base64解码
byte[] b =decoder.decodeBuffer(imgStr);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {
b[i]+= 256;
}
}
out.write(b);
out.flush();
out.close();return true;
}catch(Exception e) {return false;
}
}public staticString GetImageStr(String imgFilePath) {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;//读取图片字节数组
try{
InputStream in= newFileInputStream(imgFilePath);
data= new byte[in.available()];
in.read(data);
in.close();
}catch(IOException e) {
e.printStackTrace();
}//对字节数组Base64编码
BASE64Encoder encoder = newBASE64Encoder();return encoder.encode(data);//返回字符串
}
}