Scaling EPS images

A while back I wanted to scale some EPS images. They were actually bitmap images that came out of convert, but I wanted to scale them down after they were turned in to EPS so as not to lose quality. This way the pixels get smaller, rather than less numerous.

I couldn't find any nice way of doing this. No doubt some sort of complex incantation involving gs would do the job, but I was in a hurry, so I knocked up the crufty bit of Perl below. Note that this is known to only work on some EPS images. I think there's a bug which will fix it for many more, but even so it relies on the textual structure of the EPS being what I'd expect.

I'm posting this here because I couldn't find anything on Google, so it might be useful to someone similarly in a hurry. Also, it's an amusing hack to edit vector graphics files with regexes :-)

#!/usr/bin/perl -w
use strict;
use File::Slurp;

# A crufty little program which will, for at least some EPS images,
# scale them by a given factor (e.g., 0.5 for half size).
# Note that it doesn't give up if it can't understand the EPS.  It
# just carries on regardless and hopes for the best.
#
# I think there is a bug in the scaling.  I'll fix it sometime.
#
# This program is public domain.  Do what you want with it.  Don't sue me.
#
# --Qef, 2004-03-04.

die "Usage: $0 scale-factor input-filename output-filename\n"
  unless @ARGV == 3;

my ($scale, $input_filename, $output_filename) = @ARGV;
$input_filename = \*STDIN if $input_filename eq '-';
$output_filename = \*STDOUT if $output_filename eq '-';

local $_ = read_file($input_filename);

# Adjust bounding boxes.
s[^(%%(?:Page)?BoundingBox:)\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)]
 [join ' ', $1, map { int($_ * $scale) } $2, $3, $4, $5 ]meg;

# Insert scaling command.
s[^(%%Page:.*\n(?:%%.*\n)*)][$1\ngsave $scale $scale scale\n]m
or
s[^(%!.*\n(?:%%.*\n)*)][$1\ngsave $scale $scale scale\n]
or
s[^][gsave $scale $scale scale\n];

# Restore from the scaling.
s[^(%%PageTrailer)][grestore\n$1]m
or
s[$][\ngrestore\n];

write_file($output_filename, $_);

# vi:ts=4 sw=4 expandtab

< Folk in the Grove, 5th March (I think) | Adding an archive to my blog >

Miniblog

(nuggets of inanity)

Tuesday Apr 24th 2007, 16:54 »
Just took the annual web design survey that AListApart do. I don't realy consider myself to be a web designer, but I have been doing a lot of HTML and CSS lately.
Monday Apr 23rd 2007, 18:23 »
Strange, there appears to be a bare-knuckle boxing match going on in the field outside my flat. Wish they wouldn't make so much noise about it.
Thursday Mar 1st 2007, 18:47 »
“In its written form, Hebrew has no vowels, making it the ideal language for texting.”
—Said in jest on some Radio 4 programme just now.

Archive: 2007 · 2006 · 2005 · 2004
Feed