Watermarking Response Images - skremp/pictura-io GitHub Wiki
To dynamically adding a watermark to an image (response) you can implement your own io.pictura.servlet.ImageInterceptor
.
Seeting up the custom PicturaServlet
@WebServlet(...)
@PicturaImageInterceptor(WatermarkImageInterceptor.class)
public final class WatermarkPicturaServlet extends PicturaServlet {
}
Implement the watermark interceptor
public final class WatermarkImageInterceptor implements ImageInterceptor {
private static BufferedImage watermark;
static {
try {
watermark = ImageIO.read(WatermarkImageInterceptor.class.getResourceAsStream("/watermark.png"));
} catch (IOException e) {
// ignore
}
}
@Override
public BufferedImage intercept(BufferedImage img, HttpServletRequest req) {
if (watermark != null && img.getWidth() >= 10 && img.getWidth() >= 10) {
int w = watermark.getWidth() > watermark.getHeight()
? watermark.getWidth() : watermark.getHeight();
float i = Math.max(8, (img.getWidth() / 10f));
BufferedImage wm = watermark;
if (w > i) {
wm = Pictura.resize(watermark, Pictura.Method.AUTOMATIC,
Pictura.Mode.FIT_EXACT, Math.round(i), Math.round(i));
}
// Bottom-Right
int x = img.getWidth() - Math.round(1.2f * wm.getWidth());
int y = img.getHeight() - Math.round(1.2f * wm.getHeight());
Graphics2D g = (Graphics2D) img.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int rule = AlphaComposite.SRC_OVER;
Composite comp = AlphaComposite.getInstance(rule, 0.65f);
g.setComposite(comp);
g.drawImage(wm, x, y, null);
g.dispose();
}
return img;
}
@Override
public String getVaryCacheKey(String trueCacheKey, HttpServletRequest req) {
return trueCacheKey;
}
}
Note: the watermark image
watermark.png
in the example above is located in the root classpath.
That's all!