数字图像处理——用Java对数字图像写水印

来源:互联网 发布:linux域名绑定公网ip 编辑:程序博客网 时间:2024/06/09 15:01

写水印这个是数字图像处理中十分常见的操作,比如我们在CSDN上传个图片啥的,它还要在图片的右下方写点“http://blog.csdn.net/sinat_36246371”,那么我们用Java代码也在图片上写点啥,直接看代码吧。

import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class ImageWaterMark {    public static void main(String[] args) {        BufferedImage image = null;        File file = null;        try {            file = new File("E:\\in.jpg");            image = ImageIO.read(file);            BufferedImage temp = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);            Graphics graphics = temp.getGraphics();            graphics.drawImage(image, 0, 0, null);            graphics.setFont(new Font("Arial", Font.PLAIN, 40));            graphics.setColor(new Color(0, 0, 255, 255));            String text = "K.Sun's CSDN";            graphics.drawString(text, image.getWidth() / 2, image.getHeight() / 2);            graphics.dispose();            file = new File("E:\\out.jpg");            ImageIO.write(temp, "jpg", file);        } catch (IOException e) {            e.printStackTrace();        }    }}

代码对图像的读写与前面的一样,不需要再啰嗦了。BufferedImage在前面也讲过了,就是指明图像的表现形式。

不一样的地方来了:

首先我们用getGraphics()方法获得了一个Graphics对象,这个对象是要存储我们将要画在图像上的文字的,实际上也是一个二维图形对象。

drawImage(Image img, int x, int y, ImageObserver observer)指定了图像左上角的位置,而参数ImageObserver只的是图像异步加载机制,一般也不用,所以设为null就行了。

然后通过setFont(Font f)setColor(Color c)方法设置颜色和字体,最后用drawString(String str, int x, int y)方法,就是说要画在图像的什么位置。

输出结果是:


这里写图片描述