在51cto写博文上传图片的时候,觉得图片上加上水印很有意思,与是有了自己动手写一个加水印的小程序,自己动手丰衣足食。来看看我写的代码吧,哈哈
package com.sucre.blog; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import javax.swing.ImageIcon; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * 给图片加水印 * @author sucre * */ public class ProductWaterMark { public boolean createMark(String filePath, String markContent, Color markContentColor, float qualNum, String watermark) { ImageIcon imgIcon = new ImageIcon(filePath); Image theImg = imgIcon.getImage(); int width = theImg.getWidth(null); int height = theImg.getHeight(null); BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Font font = new Font("新宋体", Font.PLAIN, 50);//这里控制图片上文字的大小 Graphics2D g = bimage.createGraphics(); g.setColor(markContentColor); g.setFont(font); g.setBackground(Color.white); g.drawImage(theImg, 0, 0, null); //添加水印的文字和设置水印文字出现的内容 g.drawString(markContent, width - 800, height - 80); g.dispose(); try { FileOutputStream out = new FileOutputStream(filePath); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage); param.setQuality(qualNum, true); encoder.encode(bimage, param); out.close(); } catch (Exception e) { return false; } return true; } public static void main(String arg[]) { ProductWaterMark wk = new ProductWaterMark(); boolean successOrNot = wk.createMark("F:\\我的图片\\1.jpg","http://sucre.blog.51cto.com", Color.BLACK, 23f, ""); System.out.println(successOrNot?"You are Success!":"You are Failure"); } }
无水印的图
加水印后的图片
看到了吧,图片的最小方有一行大黑字,虽然没有博客系统加的好看,但是我觉得还行。
本文出自 “” 博客,请务必保留此出处