Обработка изображений в Java | Установите 10 (водяные знаки на изображении)

Опубликовано: 15 Февраля, 2022

Мы настоятельно рекомендуем ссылаться на нижеследующий пост как на предварительное условие для этого.

  • Обработка изображений в Java | Установите 1 (чтение и запись)
  • Обработка изображений в Java | Установите 2 (получение и установка пикселей)

В этом наборе мы будем генерировать водяной знак и применять его к входному изображению.
Для создания текста и применения его к изображению мы будем использовать пакет java.awt.Graphics. Шрифт и цвет текста применяются с использованием классов java.awt.Color и java.awt.Font.

Some of the methods used in the code:

  • getGraphics() – This method is found in BufferedImage class, and it returns a 2DGraphics object out of image file.
  • drawImage(Image img, int x, int y, ImageObserver observer) – The x,y location specifies the position for the top-left of the image. The observer parameter notifies the application of updates to an image that is loaded asynchronously. The observer parameter is not frequently used directly and is not needed for the BufferedImage class, so it usually is null.
  • setFont(Font f) – This method is found in Font class of awt package and the constructor takes (FONT_TYPE, FONT_STYLE, FONT_SIZE) as arguments.
  • setColor(Color c) – This method is found in Color class of awt package and the constructor takes (R, G, B, A) as arguments.
  • drawString(String str, int x, int y) – Fond in Graphics class takes the string text and the location cordinates as x and y as arguments.
// 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


Эта статья предоставлена Pratik Agarwal . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью с помощью provide.geeksforgeeks.org или отправить ее по электронной почте на deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .