Servlet(JSP)中动态生成JPG PNG透明 水印图像

部分内容摘自互联网,选择精华部分摘入,并加入自己实践内容,记录下,方便后人,方便自己!

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()

类似这种效果:

image
白色底,显的质量也不咋的!

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());

这个效果还不错,比较满意!

image

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());

image

还有一种就是图片上贴图片,如果想贴透明的必须源图片也是透明最好PNG的,在再添加水印的代码中部分修改下,加上类似

g2d.drawImage(img, x, y, width, height, null)

这种代码应该就可以了,没试过不知道透明效果给力不!

因文章字数限制,就不贴上图片贴图片代码了!


原文地址:https://www.cnblogs.com/syxchina/p/2197207.html