java水印透明_java给透明图片加水印

这段Java代码展示了如何在一张具有透明背景的图片上添加图片水印。通过读取源图片和水印图片,利用Graphics2D进行旋转、设置透明度,并在指定位置绘制水印,最终保存为PNG格式。
摘要由CSDN通过智能技术生成

java实现一张透明背景的图片,添加图片水印

public static void createWaterMarkByIcon(File srcImageFile, File logoImageFile,

File outputImageFile, double degree) {

OutputStream os = null;

try {

Image srcImg = ImageIO.read(srcImageFile);

BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),

srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

Graphics2D graphics = buffImg.createGraphics();

buffImg = graphics.getDeviceConfiguration().createCompatibleImage(srcImg.getWidth(null), srcImg.getWidth(null), Transparency.TRANSLUCENT);

graphics = buffImg.createGraphics();

// graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

int imgWidth = srcImg.getWidth(null);

int imgHeight = srcImg.getHeight(null);

graphics.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),

srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(logoImageFile));

Image logoImg = logoImgIcon.getImage();

//旋转

if (degree>0) {

graphics.rotate(Math.toRadians(degree),

(double) buffImg.getWidth() / 2,

(double) buffImg.getWidth() / 2);

}

float alpha = 0.7f; // 透明度

graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

//水印 的位置

int logoWidth = imgWidth/4;

int logoHeight = logoWidth*17/20;

graphics.drawImage(logoImg, buffImg.getWidth()-logoWidth, buffImg.getHeight()-logoHeight,logoWidth,logoHeight, null);

// graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

graphics.dispose();

os = new FileOutputStream(outputImageFile);

// 生成图片

ImageIO.write(buffImg, "PNG", os);

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (null != os)

os.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值