ホームページ  >  記事  >  Java  >  Javaでテキスト透かしと画像透かし機能を追加する方法

Javaでテキスト透かしと画像透かし機能を追加する方法

王林
王林転載
2023-05-23 08:56:121644ブラウズ

    ウォーターマークの追加

    画像にウォーターマークを追加する主な目的は、画像の著作権を保護して、権限のない人による使用や拡散を防ぐことです。この画像。画像に透かしを追加することは、一般的な画像処理手法です。 Java JDK に付属の Graphics2D クラスを使用して透かしを描画できます。画像の透かしまたはテキストの透かしを追加できます。

    Java プラットフォームは、2D 画像描画を実装するための Java 2D API クラス ライブラリを提供します。このソフトウェアは、複数の画像、フォント、カラー管理形式のサポートを提供し、アルファ ブレンディング、深度バッファなどの多くの高度な機能を備えています。

    Java 2D API の概要

    1. グラフィックスを描画するためのオブジェクトを作成する

    Graphics2D クラスを使用して、グラフィックスを描画するためのオブジェクトを作成します。 Graphics クラスのサブクラスである Graphics2D オブジェクトを拡張することで、より多くの描画機能を実現できます。

    // 创建一个大小为 800x600 像素的空白图像
    BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
    // 递给 Graphics2D 对象以进行绘制操作
    Graphics2D g2d = image.createGraphics();

    2. 基本的なグラフィックスの描画

    Java 2D API は、線分、長方形、楕円、円弧などのさまざまな基本的な 2D グラフィックスの描画をサポートします。

    // 绘制一条线段
    g2d.drawLine(100, 100, 200, 200);
    // 绘制一个矩形
    g2d.drawRect(300, 100, 100, 50);
    // 绘制一个椭圆
    g2d.drawOval(500, 100, 100, 150);
    // 绘制一个弧形
    g2d.drawArc(100, 300, 100, 100, 0, 90);
    3. テキストの描画

    Graphics2D オブジェクトのdrawString() メソッドを使用して、画像上に文字列テキストを描画できます

    // 将字符串 "Hello, Java 2D!" 绘制在坐标 (200, 400) 处
    g2d.drawString("Hello, Java 2D!", 200, 400);
    4 . 画像の描画

    JPEG、PNG、GIF など、さまざまな形式の画像の読み込みと描画をサポートします。 ImageIO クラスを使用して画像ファイルをロードし、Graphics2D オブジェクトのdrawImage() メソッドを使用してそれを画像上に描画することもできます。

    // 从指定的文件路径加载一张图片,并将其绘制在图像的左上角
    BufferedImage image = ImageIO.read(new File("image.jpg"));
    g2d.drawImage(image, 0, 0, null);
    5. 描画プロパティの設定

    Graphics2D オブジェクトの set メソッドを使用して、色、フォント、線幅などのさまざまな描画プロパティを設定できます。 。

    // 设置绘制颜色为红色
    g2d.setColor(Color.RED);
    // 设置字体为 Arial,大小为 24
    g2d.setFont(new Font("Arial", Font.PLAIN, 24));
    // 设置线宽为 3 像素
    g2d.setStroke(new BasicStroke(3));
    テキスト透かしの描画

    画像にテキスト透かしを追加する手順は次のとおりです。

    • ImageIO クラスを使用します。追加する必要がある透かしをロードするには Image

    • BufferedImage のカスタム画像オブジェクトを作成し、Graphics2D オブジェクトを使用して元の画像をオブジェクト上に描画します

    • ##フォント オブジェクトを作成し、フォント、色、透明度、その他の属性を設定します。

    • Graphics2D オブジェクトのdrawString() メソッドを使用して、次の位置に文字列を描画します。ウォーターマークを追加する必要があります

    • ImageIO クラスを使用して、変更した画像を指定したディレクトリに保存します

    •     public static void addWatermark(File input, File out, String text, int fontSize) {
              // 读取原图片
              BufferedImage image = null;
              try {
                  image = ImageIO.read(input);
              } catch (IOException e) {
                  e.printStackTrace();
              }
              // 获取图片的宽度和高度
              int width = image.getWidth();
              int height = image.getHeight();
              // 创建一个图片缓存对象
              BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
              // 获取图片的画笔
              Graphics2D g = newImage.createGraphics();
              // 将原图片绘制到缓存图片上
              g.drawImage(image, 0, 0, width, height, null);
              // 创建字体对象
              Font font = new Font("微软雅黑", Font.BOLD, fontSize);
              // 创建字体渲染上下文
              FontRenderContext frc = new FontRenderContext(null, true, true);
              // 计算字符串的宽度和高度
              Rectangle2D bounds = font.getStringBounds(text, frc);
              // 字符宽度
              int strWidth = (int) bounds.getWidth();
              // 字符高度
              int strHeight = (int) bounds.getHeight();
              // 设置水印的字体样式
              g.setFont(font);
              // 设置水印的颜色
              g.setColor(Color.red);
              // 设置水印的位置 根据需要再自行调整宽度、高度
              g.drawString(text, width - strWidth - 10, height - strHeight + 15);
              // 释放图形上下文使用的系统资源
              g.dispose();
              // 保存带水印的图片
              try {
                  ImageIO.write(newImage, "png", out);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          public static void main(String[] args) {
              File input = new File("D://test.png");
              File out = new File("D://watermark.png");
              // 水印文本内容,中文转Unicode
              String text = "\u6dfb\u52a0\u6c34\u5370";
              addWatermark(input, out, text, 20);
          }
    画像のウォーターマークを描画します

    画像に画像の透かしを追加する手順は次のとおりです。

    • ImageIO クラスを使用して、透かしを入れる必要がある画像を読み込みます

    • #BufferedImage のカスタム画像オブジェクトを作成し、Graphics2D オブジェクトを使用して元の画像をオブジェクトに描画します
    • #ImageIO クラスを使用してウォーターマーク画像をロードし、透明度およびその他のプロパティ
    • 透かし画像を描画し、関連リソースを解放します
    • ImageIO クラスを使用して、変更した画像を指定したディレクトリに保存します
    •     public static void addWatermark(File input, File out, File watermarkImage) {
              // 读取添加水印的图片
              BufferedImage image = null;
              try {
                  image = ImageIO.read(input);
              } catch (IOException e) {
                  e.printStackTrace();
              }
              // 获取图片的宽度和高度
              int width = image.getWidth();
              int height = image.getHeight();
              // 创建一个图片缓存对象
              BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
              // 获取图片的画笔
              Graphics2D g = newImage.createGraphics();
              // 将原图片绘制到缓存图片上
              g.drawImage(image, 0, 0, width, height, null);
              // 读取水印图片
              BufferedImage watermark = null;
              try {
                  watermark = ImageIO.read(watermarkImage);
              } catch (IOException e) {
                  e.printStackTrace();
              }
              // 获取水印图片的宽度和高度
              int wmWidth = watermark.getWidth();
              int wmHeight = watermark.getHeight();
              // 设置水印图片的透明度
              g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
              // 绘制水印图片
              g.drawImage(watermark, width - wmWidth - 10, height - wmHeight - 10, wmWidth, wmHeight, null);
              // 释放图形上下文使用的系统资源
              g.dispose();
              // 保存带水印的图片
              try {
                  ImageIO.write(newImage, "png", out);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          public static void main(String[] args) {
              File input = new File("D://test.png");
              File out = new File("D://watermark.png");
              File watermarkImage = new File("D://watermarkImage .png");
              addWatermark(input, out, watermarkImage);
          }

      ループ内にテキスト透かしを追加
    • public class AddWatermarkUtils {
          // 水印字体
          private static final Font FONT = new Font("微软雅黑", Font.PLAIN, 24);
          // 透明度
          private static final AlphaComposite COMPOSITE = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
          // 水印之间的间隔
          private static final int X_MOVE = 150;
          // 水印之间的间隔
          private static final int Y_MOVE = 200;
          public static void markWithContent(String inputImgPath, Font font, Color markContentColor,
                                             String waterMarkContent,
                                             String outImgPath) throws IOException {
              // 读取原图片信息
              File srcFile = new File(inputImgPath);
              File outFile = new File(outImgPath);
              BufferedImage srcImg = ImageIO.read(srcFile);
              // 图片宽、高
              int imgWidth = srcImg.getWidth();
              int imgHeight = srcImg.getHeight();
              // 图片缓存
              BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
              // 创建绘图工具
              Graphics2D graphics = bufImg.createGraphics();
              // 画入原始图像
              graphics.drawImage(srcImg, 0, 0, imgWidth, imgHeight, null);
              // 设置水印颜色
              graphics.setColor(markContentColor);
              // 设置水印透明度
              graphics.setComposite(COMPOSITE);
              // 设置倾斜角度
              graphics.rotate(Math.toRadians(-35), (double) bufImg.getWidth() / 2,
                      (double) bufImg.getHeight() / 2);
              // 设置水印字体
              graphics.setFont(font);
              // 消除java.awt.Font字体的锯齿
              graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              int xCoordinate = -imgWidth / 2, yCoordinate;
              // 字体长度
              int markWidth = FONT.getSize() * getTextLength(waterMarkContent);
              // 字体高度
              int markHeight = FONT.getSize();
              // 循环添加水印
              while (xCoordinate < imgWidth * 1.5) {
                  yCoordinate = -imgHeight / 2;
                  while (yCoordinate < imgHeight * 1.5) {
                      graphics.drawString(waterMarkContent, xCoordinate, yCoordinate);
                      yCoordinate += markHeight + Y_MOVE;
                  }
                  xCoordinate += markWidth + X_MOVE;
              }
              // 释放画图工具
              graphics.dispose();
              try (FileOutputStream fos = new FileOutputStream(outFile)) {
                  // 输出图片
                  ImageIO.write(bufImg, "jpg", fos);
                  fos.flush();
              }
          }
          /**
           * 计算水印文本长度
           * 中文长度即文本长度
           * 英文长度为文本长度二分之一
           */
          public static int getTextLength(String text) {
              //水印文字长度
              int length = text.length();
              for (int i = 0; i < text.length(); i++) {
                  String s = String.valueOf(text.charAt(i));
                  if (s.getBytes().length > 1) {
                      length++;
                  }
              }
              length = length % 2 == 0 ? length / 2 : length / 2 + 1;
              return length;
          }
      }
          public static void main(String[] args) throws IOException {
              // 输入图片路径
              String inputFile = "D://test.png";
              // 输出图片路径
              String outputFile = "D://watermark.png";
              // 水印文本内容,中文转Unicode
              String watermarkText = "\u6dfb\u52a0\u6c34\u5370";
              AddWatermarkUtils.markWithContent(inputFile, FONT, Color.darkGray, watermarkText, outputFile);
          }

    以上がJavaでテキスト透かしと画像透かし機能を追加する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

    声明:
    この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。