利用BufferedImage处理图片时,例如生成海报往添加图片加文字,由于背景图颜色差异不统一,需要加入纯色半透明遮罩层后,再往上面添加文字。
以下代码演示:在图片底部加入一条高度20的半透明遮罩层packagecom;
importjavax.imageio.ImageIO;
importjava.awt.*;
importjava.awt.image.BufferedImage;
importjava.io.File;
publicclassImageUtil{
publicstaticvoidmain(String[]arg)throwsException{
//底图
BufferedImagebackground=ImageIO.read(newFile("C:\\1.png"));
Graphics2DbgG2=(Graphics2D)background.getGraphics();
//遮罩层大小
intcoverWidth=background.getWidth();
intcoverHeight=20;
//遮罩层位置
intcoverX=0;
intcoverY=background.getHeight()-coverHeight;
//创建黑色遮罩层
BufferedImagecover=newBufferedImage(coverWidth,coverHeight,BufferedImage.TYPE_INT_RGB);
Graphics2DcoverG2=(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();
//图片保存到本地
Filefile=newFile("C:\\2.png");
ImageIO.write(background,"png",file);
}
}
处理图片前:
处理图片后:
原创文章,转载请注明出处:/article/92.html