Skip to content

Instantly share code, notes, and snippets.

@shunn shunn/nametag.pl
Created Jun 19, 2019

Embed
What would you like to do?
Name Tag Generator
#!/usr/bin/perl
use strict;
use Image::Magick;
# Input and output files
my $sourcefile = 'image-magick-step-1.jpg'; # blank name tag image (input filename)
my $texturefile = 'image-magick-step-2.jpg'; # pebbled texture image (input filename)
my $targetfile = 'image-magick-step-6.jpg'; # final composite image (output filename)
# Text values
my $name = 'ELDER HEISENBERG'; # text to print on name tag
my $font = 'AltGoth2.ttf'; # font face (TrueType font file)
my $size = 59; # font size
# Starting values for text positioning on blank name tag
my $startx = 252; # horizontal text position (centered)
my $starty = 94; # vertical text position (top edge)
# Shadow offset values
my $offsetx = 0; # horizontal shadow offset
my $offsety = 2; # vertical shadow offset
# Image processing values
my $radius = 0; # blur radius
my $sigma = 1.5; # blur sigma
my $opacity = '70%'; # shadow opacity
# Load image files for compositing
my $nametag = Image::Magick->new;
my $texture = Image::Magick->new;
$nametag->Read($sourcefile);
$texture->Read($texturefile);
# Get dimensions of rendered text
my ($x_ppem, $y_ppem, $ascender, $descender, $width, $height, $max_advance) =
$nametag->QueryFontMetrics(
font => $font,
pointsize => $size,
text => $name,
);
# Position text so it's centered on the name tag
my $x = $startx - int($width / 2);
my $y = $starty;
# Create a mask (or stencil) image using the desired text
my $mask = Image::Magick->new; # Create a new image object
$mask->Set( size => '503x339' ); # Same size as blank name tag image
$mask->ReadImage( 'canvas:black' ); # Fill the image with black
$mask->Annotate( # Render the text on the image in white
font => $font,
pointsize => $size,
fill => 'white',
text => $name,
x => $x,
y => $y,
antialias => true,
);
# Create our shadow image
my $shadow = Image::Magick->new;
$shadow->Set( size => '503x339' );
$shadow->ReadImage( 'canvas:black' );
$shadow->Annotate(
font => $font,
pointsize => $size,
fill => 'white',
text => $name,
x => $x + $offsetx,
y => $y + $offsety,
antialias => true,
);
$shadow->Blur(
radius => $radius,
sigma => $sigma,
);
# Layer our blurred shadow onto our texture image
$texture->Composite(
image => $shadow,
compose => 'Dissolve',
opacity => $opacity,
);
# Layer our textured shadow onto the blank name tag, using our mask layer as a stencil
$nametag->Composite(
image => $texture,
mask => $mask,
);
# Write the resulting image to a file
$nametag->Write($targetfile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.