BufferedImage在图片添加半透明遮罩层
阅读(2031)
2019-05-22
利用BufferedImage处理图片时,例如生成海报往添加图片加文字,由于背景图颜色差异不统一,需要加入纯色半透明遮罩层后,再往上面添加文字。
以下代码演示:在图片底部加入一条高度20的半透明遮罩层
package com; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; public class ImageUtil { public static void main(String[] arg) throws Exception{ //底图 BufferedImage background = ImageIO.read(new File("C:\\1.png")); Graphics2D bgG2 = (Graphics2D)background.getGraphics(); //遮罩层大小 int coverWidth = background.getWidth(); int coverHeight = 20; //遮罩层位置 int coverX = 0; int coverY = background.getHeight() - coverHeight; //创建黑色遮罩层 BufferedImage cover = new BufferedImage(coverWidth, coverHeight, BufferedImage.TYPE_INT_RGB); Graphics2D coverG2 = (Graphics2D)cover.getGraphics(); coverG2.setColor(Color.BLACK); coverG2.fillRect(0,0, coverWidth, coverHeight); coverG2.dispose(); //开启透明度 bgG2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f)); //描绘 bgG2.drawImage(cover, coverX, coverY, coverWidth, coverHeight, null); //结束透明度 bgG2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); bgG2.dispose(); //图片保存到本地 File file =new File("C:\\2.png"); ImageIO.write(background, "png", file); } }
处理图片前:
处理图片后:
原创文章,转载请注明出处:https://www.weizhixi.com/article/92.html