Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Tuesday May 04, 2004
09:09 AM

Putting a black border around an image

[ #18611 ]

While riding the train from Chicago to Detroit last night, I finally wrote a little program I have needed for a while. Up to know I have put black borders around images by firing up Photoshop, and as tiresome and annoying as that is, I was too lazy to do anything about it.

So, while I was uploading pics from my phone to my computer, I banged out this dirty little script to make the transformation. I want to go from the full size (640x480) images my phone provides to half size (320x240) images with a one pixel black border around them.

I wrote this in about the time it takes for me to start Photoshop and open an image, minus a few clean-ups to make it more presentable.

#!/usr/bin/perl
use strict;
use warnings;
 
use GD;
 
my( $file, $new_file ) = @ARGV;
 
my $source = GD::Image->newFromJpeg( $file );
die "Could not open [$file]\n" unless ref $source;
 
my( $width, $height ) = $source->getBounds();
 
my( $new_width, $new_height ) =
    map { int($_ / 2) } ( $width, $height );
 
my $thumb = GD::Image->new( $new_width, $new_height );
 
$thumb->copyResized( $source, 0,0 => 0,0 =>
    $new_width,$new_height => $width,$height );
 
black_border( $thumb );
 
open my( $fh ), "> $new_file"
    or die "Could not write [$new_file]: $!\n";
 
print $fh $thumb->jpeg;
 
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
sub black_border
    {
    my $image = shift;
    my $black = $image->colorAllocate( 0, 0, 0 );
 
    my( $w, $h ) = map { $_ - 1 } $image->getBounds();
 
    foreach my $points (
        [0,0   =>  0,$h],
        [0,$h  => $w,$h],
        [$w,$h => $w, 0],
        [$w, 0 =>  0, 0] )
        {
        $image->line( @$points, $black );
        }
    }

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • You can also do this at the command line with:

    convert -resize 50% -border 1x1 -bordercolor black orig.img new.img

    assuming you have Imagemagick installed. Substitute mogrify for convert if you don't want to keep the originals.
    • Yeah, I was working on installing ImageMagick, but I had some trouble with the freetype headers (which I have noew fixed).

      Eventually this thing is going to end up in another program, but it's good to have the command line option too. Thanks :)
      • Imager is a neat alternative to Image::Magick. I've been playing with it recently and so far it's proving pretty gosh-darned nifty. It's also several orders of magnitude easier to install.