Add margins to pbm

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
ghostmansd
Posts: 24
Joined: 2011-03-21T09:27:47-07:00
Authentication code: 8675308

Add margins to pbm

Post by ghostmansd »

Hello everybody! Could you help me to add white margins to image in pbm format? For example, 2 cm for top and bottom, 1,5 for left and rigt.
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Add margins to pbm

Post by fmw42 »

You will have to convert from cm or inches to pixels using the image's density (nominally 72 dpi, but it may be different). Then you can simply use -bordercolor white -border X, where X is in pixels (see http://www.imagemagick.org/Usage/crop/#border), if you want it uniform all around. If you want different borders, then use -splice (see http://www.imagemagick.org/Usage/crop/#splice)

You can find the density or resolution and units for an image from string formats %x and %y from http://www.imagemagick.org/script/escape.php

convert -units pixelsperinch zelda3.png -density 72 zelda3.pnm
convert zelda3.pnm -format "%x x %y" info:
72 Undefined x 72 Undefined

Does PNM format support units?

You would then convert 72 dpi (presumably) to centimeters and then figure out how many pixels that means for a 2 cm border.

Here is an example:

# create test image:
convert zelda3.jpg -density 72 -units pixelsperinch zelda3_72dpi.jpg

# process it to add a 2 cm border
borderwidth=2 #assume centimeters
res=`convert zelda3_72dpi.jpg -format "%x" info:`
density=`echo "$res" | cut -d\ -f1`
units=`echo "$res" | cut -d\ -f2`
echo "density=$density; units=$units"
if [ "$units" = "PixelsPerCentimeter" ]; then
borderpix=`convert xc: -format "%[fx:2*$density]" info:`
elif [ "$units" = "PixelsPerInch" -o "$units" = "Undefined" ]; then
borderpix=`convert xc: -format "%[fx:round(2*$density/2.54)]" info:`
fi
echo "borderpix=$borderpix"
convert zelda3_72dpi.jpg -bordercolor white -border $borderpix zelda3_72dpi_border.jpg
ghostmansd
Posts: 24
Joined: 2011-03-21T09:27:47-07:00
Authentication code: 8675308

Re: Add margins to pbm

Post by ghostmansd »

Thank you! And is it possible to delete a part of borders? For example, I need to delete 2 cm from top and 3 from bottom.
Image
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Add margins to pbm

Post by fmw42 »

see -shave at http://www.imagemagick.org/Usage/crop/#shave

but you again need to convert from cm to pixels using the density and units.
Post Reply