The Important Bit!

Adding watermarks to image in Perl

December 16th, 2012

I was writing a little script to watermark some images on my site, and thought I would share it for anyone who can make use of it :)

All the main options are found at the top – so should be pretty simple to customize. The idea behind this system is that you upload it to your /cgi-bin (either password protected, or just somewhere safe), and then access it from your browser. You then upload your image, and it will scale the image and add your watermark to it. Simple as that!


use warnings;
use strict;
use CGI;

my $write_folder = "/var/home/user/www/watermarked";
my $write_url    = "/watermarked"; # you can use the URL, or relative is just fine...
my $watermark_img = "/var/home/user/cgi-bin/cgi-bin/watermark/watermark.png";
my $transparency = "15"; # percentage of watermark image opacity
my $resize       = "400x400";

my $IN = new CGI;

print "Content-Type: text/html \n\n";

if (!$IN->param('doit')) {

	print qq|
	<form action="watermark.cgi" method="post" enctype="multipart/form-data">
		<input type="file" name="image" />
		<br /><br />
		<input type="submit" value="Watermark" >
		<input type="hidden" name="doit" value="1" />

} else {
	my $file = $IN->param('image');
	my $ext = lc((reverse split /\./, $file)[0]);
	my $upload = $IN->upload('image');
	#print "GOT: $file , and $ext";
	my $write_file = CORE::time() . ".$ext";
	#print "Writing to $write_folder/$write_file <br />";
	open (UPLOADFILE, ">$write_folder/$write_file") || die $!;
		binmode UPLOADFILE;
		 while ( <$upload> ) {
			print UPLOADFILE;
	my $command = qq|convert $write_folder/$write_file -resize $resize $write_folder/$write_file|;
	my $command2 = qq|composite -dissolve $transparency -tile $watermark_img $write_folder/$write_file $write_folder/$write_file|;

	if ($ext !~ /jpg/i) {
		my $new_filename = $write_file;
		   $new_filename =~ s/\.$ext/jpg/g;
		`convert $write_folder/$write_file $write_folder/$new_filename`;
		$write_file = $new_filename;
	print qq|<img src="$write_url/$write_file" />|


Categories: Perl Coding


Related Posts: