How to crop margin in imagemagick?

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?".
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

How to crop margin in imagemagick?

Post by VanGog »

Hello,
am new to IM and trying to solve this.

I have many images (*.pdf) that originally do not have margin. The files are in various sizes but usually from 8000x4000 to 20000x14000 px.

I use this command to convert them to jpeg:

for /r %x in (*.pdf) do convert -density 400 -quality 100% "%x" "%x.jpg"

But it produces big margins. Margins take 30% of the image size. So I need to prevent them or to crop them. I tried to look in IM manual to find how to obtain width and height and to substract some value and to add it to -crop. But this his too hard to me, I am tring to solve it about 1,5 hours without result. And I am new to IM. Can somebody tell me how to solve this and remove the margin?

Also I would like to repair name of file from e.g. map.pdf to map.jpg Now it result in map.pdf.jpg
User avatar
anthony
Posts: 8883
Joined: 2004-05-31T19:27:03-07:00
Authentication code: 8675308
Location: Brisbane, Australia

Re: How to crop margin in imagemagick?

Post by anthony »

Their are many ways.

Th primary operator as you have figured out is -crop WxH+X+Y +repage (though the +repage is not necessary from JPG images). But that works by knowning what part of the image you want to keep, not what you want to remove.

If you don't mind different sized images, you and -trim +repage
If you know how big the margins are you can use -shave
If the margins are unequal on left-right and top-bottom you can -chop each margin individually

ALL these methods (and more) are exampled and demonstrated in IM Examples, Cutting and Borders
http://www.imagemagick.org/Usage/crop/
Anthony Thyssen -- Webmaster for ImageMagick Example Pages
https://imagemagick.org/Usage/
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by VanGog »

Could you please tell me how can I calculate the size from percentage of with and percentage of height?

When I use for first image -shave 1600x1600 so it is too much for other images. So I would need to calculate 15% of the width and 15% of the height to get it to -shave
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: How to crop margin in imagemagick?

Post by fmw42 »

I believe that this works:

convert image -shave 15%x15% output


But if not, then

newwidth=`convert image -format "%[fx:0.15*w]" info:

newheight=`convert image -format "%[fx:0.15*h]" info:

convert image -shave ${newwidth}x${newheight} output

see string formats and fx escapes at
http://www.imagemagick.org/script/escape.php
http://www.imagemagick.org/Usage/transform/#fx_escapes
http://www.imagemagick.org/script/fx.php
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by VanGog »

newwidth and newheight are variables? I cannot use them because DOS/cmd.exe does not recognized them as command. Are you sure your syntax near ` is correct? Should not be closed ``?

In the first try -shave 15%x15% results in program's thinking that %x is variable but -shave 15% x 15% results in thinking that x should be file
User avatar
anthony
Posts: 8883
Joined: 2004-05-31T19:27:03-07:00
Authentication code: 8675308
Location: Brisbane, Australia

Re: How to crop margin in imagemagick?

Post by anthony »

VanGog wrote:newwidth and newheight are variables? I cannot use them because DOS/cmd.exe does not recognized them as command. Are you sure your syntax near ` is correct? Should not be closed ``?

In the first try -shave 15%x15% results in program's thinking that %x is variable but -shave 15% x 15% results in thinking that x should be file
DOS requires you to escape the percent characters that you want ImageMagick to see, but have DOS ignore.
Basically some characters are special to UNIX shell, orthers are special to DOS. The following lists the changes needed to handle these meta-characters.
IM examples, Windows, Converting Scripts: UNIX Shell to Window DOS
http://www.imagemagick.org/Usage/windows/#dos
Anthony Thyssen -- Webmaster for ImageMagick Example Pages
https://imagemagick.org/Usage/
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by VanGog »

I tried several commands for batch file so simplify my work, but still not success. Now just the simple shave command:

Code: Select all

for /r %%x in (*.pdf) do ^
convert -density 400 -shave "30%x30%" -quality 34%% "%%x" "%%x.jpg"
Tells me that the geometry is not contained in image.

In this way with backslashes:

Code: Select all

for /r %%x in (*.pdf) do ^
convert -density 400 -shave "30\%x30\%" -quality 34%% "%%x" "%%x.jpg"
There is syntax problem probably. same like here

Code: Select all

for /r %%x in (*.pdf) do ^
convert -density 400 -shave "30%%x30%%" -quality 34%% "%%x" "%%x.jpg"
What I tried to pass the percent sign to IM as normal percent sign, not a special meaning character.
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by VanGog »

I've finished the code to Win/DOS batch but I got many errors, and only 8 files successfully converted. Any idea where could be problem?

Code: Select all

for /r %%F in (*.pdf) do ^
"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%%x30%% -quality 34%% %%F %%F.jpg
**** Warning: File has insufficient data for an image.
libpng error: Write Error
Error: /VMerror in --showpage--
VM status: 3 935695 2253216
Current allocation mode is local
Last OS error: 28
GPL Ghostscript 9.04: Unrecoverable error, exit code 1
convert.exe: `%s': %s "C:/program files/GhostScript9.04/bin/gswin32c.exe" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dEPS
Crop -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r400x400" -g67533x50656 "-sOutputFile=C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/magick-zVIp4tf7-12275968" "-fC:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/magick-njK22eLq" "-fC:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/magick-XXK6mIPn" @ error/pdf.c/InvokePDFDelegate/199.convert.exe: Postscript delegate failed `D:\Europe\Cyprus\enroute.pdf':

No such file or directory @ error/pdf.c/ReadPDFImage/667. convert.exe: unable to open image `D:\Europe\Cyprus\enroute.pdf.jpg': No such file or directory @ error/blob.c/OpenBlob/2614.

D:\Europe>"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%x30% -quality 34% D:\Europe\Czech_republic\lower.pdf D:\Europe\Czech_republic\lower.pdf.jpg -density 400 -shave 30%x30% -quality 34% D:\Europe\Austria\upper.pdf D:\Europe\Austria\upper.pdf.jpg
convert.exe: unable to open image `D:\Europe\Czech_republic\lower.pdf.jpg':
No such file or directory @ error/blob.c/OpenBlob/2614.

D:\Europe>"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%x30% -quality 34% D:\Europe\Czech_republic\upper.pdf D:\Europe\Czech_republic\upper.pdf.jpg -density 400 -shave 30%x30% -quality 34% D:\Europe\Austria\upper.pdf D:\Europe\Austria\upper.pdf.jpg
**** Warning: xref subsection header has extra characters.
**** Warning: An error occurred while reading an XREF table.
**** The file has been damaged. This may have been caused
**** by a problem while converting or transfering the file.
**** Ghostscript will attempt to recover the data.
**** Warning: There are objects with matching object and generation
**** numbers. The accuracy of the resulting image is unknown.

**** This file had errors that were repaired or ignored.
**** The file was produced by:
**** >>>> Acrobat Distiller 6.0 (Windows) <<<<
**** Please notify the author of the software that produced this
**** file that it does not conform to Adobe's published PDF
**** specification.

convert.exe: unable to open image `D:\Europe\Czech_republic\upper.pdf.jpg': No such file or directory @ error/blob.c/OpenBlob/2614.

D:\Europe>"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%x30% -quality 34% D:\Europe\Denmark\lower.pdf D:\Europe\Denmark\lower.pdf.jpg -density 400 -shave 30%x30% -quality 34% D:\Europe\Austria\upper.pdf D:\Europe\Austria\upper.pdf.jpg
convert.exe: unable to open image `D:\Europe\Denmark\lower.pdf.jpg': No such file or directory @ error/blob.c/OpenBlob/2614.

D:\Europe>"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%x30% -quality 34% D:\Europe\Denmark\upper.pdf D:\Europe\Denmark\upper.pdf.jpg -density 400 -shave 30%x30% -quality 34% D:\Europe\Austria\upper.pdf D:\Europe\Austria\upper.pdf.jpg
convert.exe: unable to open image `D:\Europe\Denmark\upper.pdf.jpg': No such file or directory @ error/blob.c/OpenBlob/2614.

D:\Europe>"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%x30% -quality 34% D:\Europe\Estonia\enroute.pdf D:\Estonia\enroute.pdf.jpg -density 400 -shave 30%x30% -quality 34% D:\Austria\upper.pdf D:\Europe\Austria\upper.pdf.jpg
**** Warning: File has unbalanced q/Q operators (too many q's)

**** This file had errors that were repaired or ignored.
**** Please notify the author of the software that produced this
**** file that it does not conform to Adobe's published PDF
**** specification.

convert.exe: unable to open image `D:\Europe\Estonia\enroute.pdf.jpg': No such file or directory @ error/blob.c/OpenBlob/2614.

D:\Europe>"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%x30% -quality 34% D:\Europe\Finland\lower.pdf D:\Europe\Finland\lower.pdf.jpg -density 400 -shave 30%x30% -quality 34% D:\Europe\Austria\upper.pdf D:\Europe\Austria\upper.pdf.jpg
Error: /ioerror in --showpage--
Operand stack:
1 true
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-
- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- fa
lse 1 %stopped_push 1926 1 3 %oparray_pop 1925 1 3 %oparray_
pop 1909 1 3 %oparray_pop --nostringval-- --nostringval-- 2 1
1 --nostringval-- %for_pos_int_continue --nostringval-- --nostringval--
1809 0 9 %oparray_pop --nostringval-- --nostringval--
Dictionary stack:
--dict:1170/1684(ro)(G)-- --dict:1/20(G)-- --dict:82/200(L)-- --dict:82
/200(L)-- --dict:108/127(ro)(G)-- --dict:291/300(ro)(G)-- --dict:24/30(L)-
- --dict:6/8(L)-- --dict:21/40(L)--
Current allocation mode is local
Last OS error: No space left on device
GPL Ghostscript 9.04: Unrecoverable error, exit code 1
convert.exe: `%s': %s "C:/program files/GhostScript9.04/bin/gswin32c.exe" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dEPS
Crop -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pamcmyk32" -dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r400x400" -g10394x14506 -dUseCIEColor "-sOutputFile=C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/magick-zyXkMOEq-12275968" "-fC:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/magick-ZpF7Sh2b" "-fC:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/magick-0DSQLmkI" @ error/pdf.c/InvokePDFDelegate/199.convert.exe: Postscript delegate failed `D:\Europe\Finland\lower.pdf': No such file or directory @ error/pdf.c/ReadPDFImage/667.convert.exe: unable to open image `D:\Europe\Finland\lower.pdf.jpg': No such file or directory @ error/blob.c/OpenBlob/2614.

D:\Europe>"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -shave 30%x30% -quality 34% D:\Europe\Finland\upper.pdf D:\Europe\Finland\upper.pdf.jpg -density 400 -shave 30%x30% -quality 34% D:\Europe\Austria\upper.pdf D:\Europe\Austria\upper.pdf.jpg
convert.exe: unable to open image `D:\Europe\Finland\upper.pdf.jpg': No such file or directory @ error/blob.c/OpenBlob/2614.

****************************************************************************

Did you noticed that folder with Austria has been converted successfully and then Cyprus, Czech_republic and Denmark folders commands added part with -density -shave and with Austria folders/files?

How to solve this bug? Please help.
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: How to crop margin in imagemagick?

Post by fmw42 »

D:\Europe\Cyprus\enroute.pdf.jpg
Check your code and filenames.

Looks like you are trying to reading and/or writing files with double suffixes.
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by VanGog »

Well, there are *.pdf and *.jpg. After convert saves them as *.pdf.jpg and I don't know how to change save it with different extension. Probably when the *.pdf.jpg is created it is then next input to the program. But how to change the command to save the file with different ext.?
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: How to crop margin in imagemagick?

Post by fmw42 »

Sorry I am not a windows user/programmer so cannot help with Batch file scripts or windows syntax.

see
http://www.imagemagick.org/Usage/windows/
Drarakel
Posts: 547
Joined: 2010-04-07T12:36:59-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by Drarakel »

Perhaps try that:

Code: Select all

for /r %%F in (*.pdf) do (
"c:\program files\ImageMagick-6.7.5-Q8\convert.exe" -density 400 -colorspace RGB "%%F" -background white -alpha remove -shave 30%%x30%% "%%~dF%%~pF%%~nF.jpg"
)
With some 'safety measures'. Even if there was no such error in your case - you should always quote the filenames within FOR loops. And "-colorspace RGB" and "-alpha remove" (or "-flatten", if you have an older IM version) can sometimes avoid problems with 'PDF to JPG' conversions.
And, as you noticed, one FOR loop can also try to process the files that get only created in that loop. So, you have to write to a directory that isn't included in the FOR loop - or you have to stay away from the input file extensions for the output.
Oh, and I omitted the quality option. You can readd that of course - but in my opinion, with quality settings under.. 60 or 50%, one can save usually only a few KBs more, but very quickly almost 'destroys' the picture.

For the 'enroute.pdf' file, you perhaps will have to lower your density value. (I guess, 67533x50656 is too big here. :))

But I didn't understand your statement from the beginning:
VanGog wrote:I have many images (*.pdf) that originally do not have margin.
If you get different margins with different PDF tools, then you either have some strange files, or you don't have the right command. If, for example, some of your files use a smaller 'cropbox' (and some PDF tools only show the cropbox), then maybe you should add "-define pdf:use-cropbox=true" before the input. (But, in my experience, ImageMagick also can create problems here with the page sizes by adding an additional "-g" geometry option with sometimes wrong values. Not easy to completely avoid that from within IM.)
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by VanGog »

Hello and thank you much for good answer.
I will try your command but now will answer your question.

"I have many images (*.pdf) that originally do not have margin."
I use maps that have no margin or the margin is very little. I read it in Acrobat Reader. But when I run the IM convertion so there are big margins in the output file. So I call the shave command to remove this margin, that would take a lot of space.

"Oh, and I omitted the quality option. You can readd that of course - but in my opinion, with quality settings under.. 60 or 50%, one can save usually only a few KBs more, but very quickly almost 'destroys' the picture."
I use resolution 400 and with 34% of quality I have very very high quality of image. I see no damage in the picture, even when I look the smallest letters on the image. This saves me really much of space. I used to use quality 75-80% but the files have 14Mb or more. Now, with quality 34%, they have from 1.6Mb to 4.6Mb depends on size of map. The quality as for a human reader is still the same.
Drarakel
Posts: 547
Joined: 2010-04-07T12:36:59-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by Drarakel »

Photoshop for example wouldn't let you specify such a low quality at all (not even with 'save for Web'). There's a reason for that. But well, maybe it works with your type of files.
VanGog wrote:I use maps that have no margin or the margin is very little. I read it in Acrobat Reader. But when I run the IM convertion so there are big margins in the output file. So I call the shave command to remove this margin, that would take a lot of space.
Instead of using a workaround, I would try to eliminate the cause of that error. The Acrobat Reader displays the 'CropBox'. So, you should use the 'CropBox' here instead of the Ghostscript default 'MediaBox'. But some errors can also happen due to ImageMagick options. Perhaps you want to try that:

Code: Select all

for /r %%F in (*.pdf) do (
"C:/program files/GhostScript9.04/bin/gswin32c.exe" -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dEPSCrop -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r400 -dUseCropBox -dJPEGQ=50 -sOutputFile="%%~dF%%~pF%%~nF.jpg" "%%F"
)
You can change the density with "-r" and the JPG quality with "-dJPEG" :wink:. You could also change the "-sDEVICE" to a lossless format, e.g. "bmp16m", if you want to do automatic postprocessing with ImageMagick. In either case, the loop should be quicker by reading the PDF directly with Ghostscript. And the 'margins' should be correct now.

Ask again if there's still some error or if there's an issue with the Ghostscript syntax.
VanGog
Posts: 308
Joined: 2012-02-05T02:46:58-07:00
Authentication code: 8675308

Re: How to crop margin in imagemagick?

Post by VanGog »

Well, I am testing your script but it takes some time. First I forgot to add the quality option to your IM script so I'm running it again.

I don't understand what you mean by that Photoshop has not such low quality. Photoshop saves in 12 levels of quality for JPEG and I can use 4/12 to save in so called "low quality". But those 4/12 quality = 34%.
Post Reply