需求,给图片添加水印,
使用 Graphics2D 给图片添加了水印,之后使用ImageIO.write() 将图片添加到磁盘,结果190K的图片添加水印后变成了80K,图片质量产生损耗,造成原因是 ImageIO.write() 方法进行了质量压缩
水印
Graphics2D g = imgBuff.createGraphics();//imgBuff 原图
float alpha_biao = new Float(50).floatValue() / 100.0F;//透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha_biao));
g.drawImage(src_biao, x, y,sy_width, sy_height, null);
g.dispose();
解决方法 ://原方法ImageIO.write(imgBuff)
FileOutputStream out = new FileOutputStream(destFile);//目标路径
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param=encoder.getDefaultJPEGEncodeParam(imgBuff);//imgBuff 添加水印后的图片
param.setQuality(1, true);//设置质量
encoder.encode(imgBuff, param);
out.close();