親測3個請求都可用,沒有測試性能問題。僅供參考
BASE64Decoder Eclipsse 類可能引用不了
解決方案鏈接:http://blog.csdn.net/JBxiaozi/article/details/7351768
3 import java.awt.image.BufferedImage;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import javax.imageio.ImageIO;
9 import javax.servlet.http.HttpServletResponse;
10 import org.springframework.stereotype.Controller;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import sun.misc.BASE64Decoder;
13 import sun.misc.BASE64Encoder;
14
15 @Controller
16 @RequestMapping("/imgs/")
17 public class test {
18
19 @RequestMapping("test")
20 public void test(HttpServletResponse response) throws IOException {
21 //寫給瀏覽器
22 response.setContentType("image/jpeg");
23 //瀏覽器不要緩存
24 response.setDateHeader("expries", -1);
25 response.setHeader("Cache-Control", "no-cache");
26 response.setHeader("Pragma", "no-cache");
27 BufferedImage buffImg = ImageIO.read(new FileInputStream("g://timg.jpg"));
28 ImageIO.write(buffImg, "jpg", response.getOutputStream());
29 }
30 @RequestMapping("test1")
31 public void test1(HttpServletResponse response) throws IOException {
32 try {
33 response.setContentType("image/jpeg");
34 OutputStream toClient = response.getOutputStream();
35 String xmlImg = GetImageStr("g://timg.jpg");
36 GenerateImage(xmlImg, toClient);
37 } catch (Exception ex) {
38 System.out.println(ex.toString());
39 }
40 }
41
42 @RequestMapping("test2")
43 public void test2(HttpServletResponse response) throws IOException {
44 try {
45 response.setContentType("text/html");
46 String xmlImg = GetImageStr("g://timg.jpg");
47 System.out.println(xmlImg);
48 response.getWriter().write("<html><body><img src='data:image/jpeg;base64,"+xmlImg+"'/></body></html>");
49 } catch (Exception ex) {
50 System.out.println(ex.toString());
51 }
52 }
53
54 public static boolean GenerateImage(String imgStr, OutputStream out) {
55 if (imgStr == null) // 圖像數據為空
56 return false;
57 BASE64Decoder decoder = new BASE64Decoder();
58 try {
59 // Base64解碼
60 byte[] b = decoder.decodeBuffer(imgStr);
61 for (int i = 0; i < b.length; ++i) {
62 if (b[i] < 0) {
63 b[i] += 256;
64 }
65 }
66
67 out.write(b);
68 out.flush();
69 out.close();
70 return true;
71 } catch (Exception e) {
72 return false;
73 }
74 }
75
76 public static String GetImageStr(String imgFilePath) {
77 // 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理
78 byte[] data = null;
79
80 // 讀取圖片字節數組
81 try {
82 InputStream in = new FileInputStream(imgFilePath);
83 data = new byte[in.available()];
84 in.read(data);
85 in.close();
86 } catch (IOException e) {
87 e.printStackTrace();
88 }
89
90 // 對字節數組Base64編碼
91 BASE64Encoder encoder = new BASE64Encoder();
92 return encoder.encode(data);//返回字符串
93 }
94 }