生成JPEG所需的具體步驟
1.創建一個BufferedImage
int width = ...;
int height = ....;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
2.在BufferedImage上繪制內容
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setXXX(...);
g2d.fill(...);
g2d.draw(...);
3. 設置Content-Type響應報頭
reponse.setContentType("image/jpeg");
4. 獲取輸出流
OutputStream out = response.getOutputStream();
5.以JPEG格式將BufferedImage發送到輸出流
try{
ImageIO.writer(image, "jpg", out);
}catch(IOException ioe){
System.err.println("Error writing jpeg file: " + ioe);
}