个性化阅读
专注于IT技术分析

Java中的图像处理S10(为图像加水印)

点击下载

我们强烈建议你在下面的帖子中提及此内容。

  • Java中的图像处理S1(读和写)
  • Java中的图像处理S2(获取并设置像素)

在这个集合中, 我们将生成水印并将其应用到输入图像上。

为了生成文本并将其应用到图像中,我们将使用java.awt.Graphics包。文本的字体和颜色是通过使用java.awt.Color和java.awt.Font类来应用的。

代码中使用的一些方法:

  • getGraphics()–在BufferedImage类中找到此方法, 该方法从图像文件中返回2DGraphics对象。
  • drawImage(Image img, int x, int y, ImageObserver observer)– x, y位置指定图像左上角的位置。该观察器参数通知应用程序对异步加载的映像的更新。观察者参数并不经常直接使用, 并且对于BufferedImage类而言并不需要, 因此通常为null。
  • setFont(Font f)–该方法位于awt包的Font类中, 构造函数将(FONT_TYPE, FONT_STYLE, FONT_SIZE)作为参数。
  • setColor(Color c)–该方法位于awt包的Color类中, 构造函数将(R, G, B, A)作为参数。
  • drawString(String str, int x, int y)– Graphics类中的Fond将字符串文本和位置坐标分别作为x和y作为参数。
//Java code for watermarking an image
  
//For setting color of the watermark text
import java.awt.Color;
  
//For setting font of the watermark text
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 WaterMark
{
     public static void main(String[] args)
     {
         BufferedImage img = null ;
         File f = null ;
  
         //Read image
         try
         {
             f = new File( "input.png" );
             img = ImageIO.read(f);
         }
         catch (IOException e)
         {
             System.out.println(e);
         }
  
         //create BufferedImage object of same width and
         //height as of input image
         BufferedImage temp = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
  
         //Create graphics object and add original
         //image to it
         Graphics graphics = temp.getGraphics();
         graphics.drawImage(img, 0 , 0 , null );
  
         //Set font for the watermark text
         graphics.setFont( new Font( "Arial" , Font.PLAIN, 80 ));
         graphics.setColor( new Color( 255 , 0 , 0 , 40 ));
  
         //Setting watermark text
         String watermark = "WaterMark generated" ;
  
         //Add the watermark text at (width/5, height/3)
         //location
         graphics.drawString(watermark, img.getWidth()/5 , img.getHeight()/3 );
  
         //releases any system resources that it is using
         graphics.dispose();
  
         f = new File( "output.png" );
         try
         {
             ImageIO.write(temp, "png" , f);
         }
         catch (IOException e)
         {
             System.out.println(e);
         }
     }
}

注意:代码将无法在在线IDE上运行, 因为它需要驱动器中的映像。

输出如下:

input.jpg



output.jpg

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

赞(0)
未经允许不得转载:srcmini » Java中的图像处理S10(为图像加水印)

评论 抢沙发

评论前必须登录!