部分內容摘自互連網,選擇精華部分摘入,並加入自己實踐內容,記錄下,方便後人,方便自己!
1. 產生JPG圖片
response.setContentType("image/jpeg");
int width = 32, height = 18;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0, width, height);
g.setColor(Color.red);
g.drawOval(0, 0, width, height);
ServletOutputStream out = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close()
類似這種效果:
白色底,顯的品質也不咋的!
2. 產生透明的PNG圖片
response.setContentType("image/png");
int width = 32;
int height = 18;
// 建立BufferedImage對象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 擷取Graphics2D
Graphics2D g2d = image.createGraphics();
// ---------- 增加下面的代碼使得背景透明 -----------------
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
// ---------- 背景透明代碼結束 -----------------
// 畫圖
g2d.setColor(new Color(255,0,0));
g2d.setStroke(new BasicStroke(2));
g2d.drawLine(1, height-3, width-1, height-3);
g2d.drawString(strReqNum, width/2-4, height/2);
//釋放對象
g2d.dispose();
// 儲存檔案
ImageIO.write(image, "png", response.getOutputStream());
這個效果還不錯,比較滿意!
3 浮水印效果
浮水印效果用的也比較多, 隨便寫個例子。
response.setContentType("image/png");
// 擷取浮水印原圖
String temp = request.getSession().getServletContext().getRealPath("");
String filePath = temp + "/image/S.gif";
// 浮水印檔案
BufferedImage theImg = ImageIO.read(new File(filePath));
int width = theImg.getWidth(null);
int height = theImg.getHeight(null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
// ---------- 增加下面的代碼使得背景透明 -----------------
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
g2d.setColor(new Color(255,0,0));
g2d.setStroke(new BasicStroke(1));
g2d.setColor(Color.white);
g2d.drawImage(theImg, 0, 0, null);
g2d.setFont(new Font("宋體", Font.BOLD, 48)); // 第二個參數更改粗斜體...粗體和斜體(Font.BOLD|Font.ITALIC)
g2d.drawString("syx", width / 8, height / 2); // 添加浮水印的文字和設定浮水印文字出現的內容
g2d.dispose();
ImageIO.write(image, "png", response.getOutputStream());
還有一種就是圖片上貼圖片,如果想貼透明的必須源圖片也是透明最好PNG的,在再添加浮水印的代碼中部分修改下,加上類似
g2d.drawImage(img, x, y, width, height, null)
這種代碼應該就可以了,沒試過不知道透明效果給力不!
因文章字數限制,就不貼片貼圖片代碼了!