Skip to content

Instantly share code, notes, and snippets.

@gautamk
Created November 17, 2011 12:58
Show Gist options
  • Save gautamk/1373080 to your computer and use it in GitHub Desktop.
Save gautamk/1373080 to your computer and use it in GitHub Desktop.
JavaWatermarkingScript
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
public class wartermarker {
/**
*
* A rule from {@link java.awt.AlphaComposite}
* preferably {@link java.awt.AlphaComposite#SRC_OVER}
*/
private int alphaCompositeRule;
/**
* The opacity of the watermark
* @see java.awt.AlphaComposite#getInstance(int, float)
*/
private float alpha;
private AlphaComposite alc ;
/**
*
* This method converts a multiline string into an ArrayList of Strings
* Each item on the array list is a line of the string.
* @param str A multiline string
* @return An ArrayList of strings , a string per line of text
* @see java.util.ArrayList
*/
private static ArrayList<String> convertStringToLineString(String str){
ArrayList<String> string = new ArrayList<String>();
String s = new String ();
char [] ca = str.toCharArray();
for(int i=0;i<ca.length;i++){
if(ca[i] == '\n'){
string.add(s);
s = new String();
}
s += ca[i];
}
return string;
}
public static void main(String []args) throws IOException, ArrayIndexOutOfBoundsException{
final String src_img_name = args[0];
File image = new File(src_img_name);
if(! image.exists())
throw new FileNotFoundException("The Specified File was not found");
ImageIcon img = new ImageIcon(args[0]);
BufferedImage bufferedImage = new BufferedImage(
img.getIconWidth(),img.getIconHeight(),BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
g2d.drawImage(img.getImage(), 0, 0, null);
AlphaComposite alc = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.5f);
g2d.setColor(Color.white);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setFont(new Font("Arial",Font.BOLD,15));
String watermark = jCal.getMonthlyCalender(11,2011);
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);
int x =(img.getIconWidth() - (int) rect.getWidth()) / 2,
y =(img.getIconHeight() - (int) rect.getHeight()) / 2;
ArrayList<String> watermarks = convertStringToLineString(watermark);
for (String w : watermarks){
g2d.drawString(w,x,y);
y+=20;
}
//Free graphic resources
g2d.dispose();
BufferedOutputStream bo = new BufferedOutputStream(
new FileOutputStream("watermarked_"+image.getName() ) );
ImageIO.write(bufferedImage,"jpg",bo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment