All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.day.cq.dam.commons.watermark.WatermarkUtil Maven / Gradle / Ivy

package com.day.cq.dam.commons.watermark;

import com.day.cq.commons.ImageHelper;
import com.day.image.Layer;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 *  A utility class with static method for performing water marking operations on a {@link WatermarkContext}
 */
public class WatermarkUtil {

    /**
     * Logger instance for this class.
     */
    private static final Logger LOG = LoggerFactory.getLogger(WatermarkUtil.class);

    /**
     * Debug marker flag
     */
    private static final boolean _debug = false;

    /**
     * Applies the watermark on top of the underlying image.
* Before applying, it also styles the watermark considering the following:
*
    *
  • position - relative to the underlying source image
  • *
  • orientation - angle of rotation as measured from the x-axis in clockwise direction
  • *
  • opacity - transparency of the watermark
  • *
* * @throws WatermarkingException */ public static void applyWatermark(WatermarkContext ctx) throws WatermarkingException { Layer layer = ctx.getImage(); ImageWatermark watermark = (ImageWatermark) ctx.getWatermark(); //prepare watermark Layer wmLayer = new Layer(watermark.getImage()); wmLayer.rotate(watermark.getOrientation()); BufferedImage wmImage = wmLayer.getImage(); //position the watermark relative to the underlying image watermark.setCoords(layer.getWidth(), layer.getHeight(), wmImage.getWidth(), wmImage.getHeight()); LOG.info("Applying watermark to image with the following settings {}", watermark.toString()); BufferedImage image = layer.getImage(); Graphics2D graphics2D = image.createGraphics(); AlphaComposite ac = java.awt.AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, watermark.getOpacity()); graphics2D.setComposite(ac); graphics2D.drawImage(wmImage, watermark.getLeft(), watermark.getTop(), null); graphics2D.dispose(); if(_debug) { try { saveLayer(new Layer(wmImage)); } catch (IOException e) { throw new WatermarkingException(e); } } } private static void saveLayer(Layer layer) throws IOException { OutputStream out = null; try { out = new FileOutputStream(System.getProperty("java.io.tmpdir")+File.separatorChar+"wm.png"); layer.write("image/png", 1.0, out); out.close(); out = null; } finally { IOUtils.closeQuietly(out); } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy