打水印 Imagename_biao是水印文件 ImgName是原图

时间:2022-07-20 04:49:07
/**
* 打水印 Imagename_biao是水印文件 ImgName是原图
* @param Imagename_biao
* @param ImgName
*/
public static void imgYin(String Imagename_biao, String ImgName) {
//System.out.println("11111111111111111111111111111111 inin");
FileImageOutputStream out=null;
File _file=null;
BufferedImage image=null;
File _filebiao=null;
try {
_file = new File(ImgName);
Image src = ImageIO.read(_file);
int wideth = src.getWidth(null);
int height = src.getHeight(null); //宽大于300才打水印
if (wideth > 300) {
image = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, wideth, height, null);
// g.drawImage(src.getScaledInstance(wideth,
// height,Image.SCALE_SMOOTH), 0, 0,wideth, height, null); // 水印文件
_filebiao = new File(Imagename_biao);
Image src_biao = ImageIO.read(_filebiao);
int wideth_biao = src_biao.getWidth(null);
int height_biao = src_biao.getHeight(null);
// 水印文件显示在*
g.drawImage(src_biao, (int) (0.5 * (wideth - wideth_biao)),
(int) (0.5 * (height - height_biao)), wideth_biao,
height_biao, null);
// g.drawImage(src_biao.getScaledInstance(wideth_biao,
// height_biao,Image.SCALE_SMOOTH), (int)(0.5*(wideth
// -wideth_biao)) , (int)(0.5*(height -height_biao)),
// wideth_biao,
// height_biao, null);
// 水印文件在原图片文件的位置,原图片文件的右下角为wideth-0,height-0
g.dispose();
// FileOutputStream out = new FileOutputStream(ImgName);
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// JPEGEncodeParam param =
// encoder.getDefaultJPEGEncodeParam(image);
// param.setQuality(0.9f, false); //不压缩图像fals
// encoder.setJPEGEncodeParam(param);
// encoder.encode(image);
// out.flush();
// out.close(); // ImageIO.write(image, "jpg", new File(ImgName)); Iterator<ImageWriter> iter = ImageIO
.getImageWritersByFormatName("jpg");
if (iter.hasNext()) {
ImageWriter writer = iter.next();
ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); //MODE_COPY_FROM_METADATA ,MODE_EXPLICIT
param.setCompressionQuality(0.9f);
//System.out.println("Quality:"+1.0);
out = new FileImageOutputStream(
new File(ImgName));
writer.setOutput(out);
// writer.write(bi);
writer.write(null, new IIOImage(image, null, null), param);
out.close();
writer.dispose(); } } } catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}finally{ if(out!=null){
try
{
out.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}

宝贝网址:打水印  Imagename_biao是水印文件  ImgName是原图