convert2 - Convert image file from/to - bmp png jpg gif pdf - format

Here is another script I found on the internet, made some modifications and am positing here for your use and enjoyment. Originally written by Dawid Michalczyk, it consisted of three separate script files for three graphic conversions. I have modified it to support five types and really it could support a lot more, you need only try it to see.

To use convert2 copy and past the following text into a file in your home area bin folder as the file convert2 (~/bin/convert2).

#!/bin/bash

#: Title       : Convert2 
#: Date Created: Fri Oct 8 21:29:50 CDT 2010
#: Last Edit   : Sat Oct 21 17:37:00 CDT 2010
#: Author      : Dawid Michalczyk & J. McDaniel
#: Version     : 1.00
#: Description : Convert image file from/to - bmp png jpg gif pdf - format
#: Options     : Convert2 [type] -vhlr] <file> [file...]

# Created for the openSUSE Forums on Thursday October 21th, 2010

# Copy and paste this text into a file called convert2 in your home ~/bin folder
# To Make this script executable run the terminal command chmod +x ~/bin/convert2

# #############################################################################

       NAME_="Convert2"
    PURPOSE_="Convert image file from/to - bmp png jpg jpg pdf - format"
   SYNOPSIS_="$NAME_ [type] -vhlr] <file> [file...]"
   REQUIRES_="standard GNU commands, ImageMagick"
    VERSION_="1.00"
     IMAGES_="bmp png jpg gif pdf"

# #############################################################################
# This program is distributed under the terms of the GNU General Public License

#
# Display Help If requested
#

usage () {

echo
echo >&2 "$NAME_ $VERSION_ - $PURPOSE_
Usage: $SYNOPSIS_
Requires: $REQUIRES_
Type: bmp, png, jpg, gif or pdf: default Type is jpg
Options:
     -r, remove the input file after conversion
     -v, verbose
     -h, usage and options (this help)
     -l, see this script,, use Q to quit"
echo
    exit 1
}

#
# args check - Did we get any commands
#

echo

 $# -eq 0 ] && { echo >&2 missing argument, type $NAME_ -h for help; exit 1; }

#
# Check for Image Type for conversion - Default will be jpg if not specified
#

TYPE=$1

if  "$IMAGES_" == *$TYPE* ]] ; then
  shift
else
  TYPE=jpg 
fi

#
# varible setup
#

rm_input=
verbose=

#
# option and argument handling
#

while getopts vhlr options; do

    case "$options" in
        r) rm_input=on ;;
        v) verbose=on ;;
        h) usage ;;
        l) less $0; exit 1 ;;
       \?) echo invalid argument, type $NAME_ -h for help; exit 1 ;;
    esac

done
shift $(( $OPTIND - 1 ))

#
# check if required command is in $PATH variable
#

which mogrify &> /dev/null
 $? != 0 ]] && { echo >&2 the required ImageMagick \"mogrify\" command \
is not in your PATH variable; exit 1; }

#
# main progrm execution starts here
#

for a in "$@"; do

    newf=$(echo "${a%.*}".$TYPE)
    if  -f "$newf" ]; then
        echo "${NAME_}: skipping converting $a - $newf already exist" && continue
    else
         -f "$a" ] && mogrify -format $TYPE $a || continue
         $verbose ]] && echo "${NAME_}: $a -> $newf"
         $rm_input ]] && rm -f -- "$a"
    fi

done

echo

exit 0

# end of script file

To make the script usable, open up a terminal session and type the following command:

 chmod +x ~/bin/convert2

To use convert2, open another terminal session and enter convert2 with the following syntax:

Convert2 [type] -vhlr] <file> [file...]

If you request the help command (convert2 -h), here is what you get:

Convert2 1.00 - Convert image file from/to - bmp png jpg jpg pdf - format
Usage: Convert2 [type] -vhlr] <file> [file...]
Requires: standard GNU commands, ImageMagick
Type: bmp, png, jpg, gif or pdf: default Type is jpg
Options:
     -r, remove the input file after conversion
     -v, verbose
     -h, usage and options (this help)
     -l, see this script - Enter Q to Quit

convert2 presently supports the image types IMAGES_=“bmp png jpg gif pdf” as set by the value IMAGES_. You may add new ones to see if it is also supported. Don’t forget to modify the help information if you add something new. Don’t forget to let use know about it here.

Thank You,

I don’t know why you’re using mogrify. Maybe it has some advantages over convert. Otherwise convert is another member of the ImageMagick suite of tools and the syntax is just as simple as:

convert file.png file.xpm 

(that will convert a .png into .xpm for example). I use it quite often to create pixmap icons for older wms.

I don’t know why you’re using mogrify. Maybe it has some advantages over convert. Otherwise convert is another member of the ImageMagick suite of tools and the syntax is just as simple
Hello please_try_again. The script file I found was built around **mogrify **and seemed simple, producing good quality converted files and it seems fast as well. It can be used to convert multiple files at the same time if you wish. Since the script was six years old, is **convert **newer or produce better quality conversions? The two programs (mogrify & convert) don’t use the same syntax, so some modifications to the script would be required to make convert work.

Again scripts presented here are designed to show different ways to perform tasks and I thought that the person that wrote this one originally seemed plenty cleaver as so I decided to use it here. I also was able to understand what was being done which helps. I will mess around with the convert program as you suggest and thanks for the suggestion.

Thank You,

I cannot find the list of supported formats but ImageMagick knows quite a lot. You don’t have to limit the script to those five formats.
Such a single command will convert all files in .xpm

for pic in * ; do convert $pic ${pic%.*}.xpm ; done

So, in a script, where the first argument would be the destination format, that would be:


#! /bin/bash

type=$1
shift
for pic in $* ; do
       convert $pic ${pic%.*}.$type
done 

Notice that the source format doesn’t matter.
I don’t know if mogrify does a better job. The syntax is a little bit easier for multiple files conversion but not much.

So this is a quick and simple script file to convert between graphics formats I agree:

#! /bin/bash

type=$1
shift
for pic in $* ; do
       convert $pic ${pic%.*}.$type
done

Your script does not include anything to qualify the input format is correct or present help on what that format might be. All that means is that you can boil down any script to the line or couple of lines that does the real work. Adding in all of that other stuff is what can take a lot of work. That does not mean that quick and simple is not good, but it is something you do for your self as opposed to passing out to others. Of course if you have a memory as short as mine, I need the help as well so I can remember just what I was thinking in the first place. I was also trying to limit the format to things known to work with the ability to keep adding in more as they are tested. This is something the new scripting writing person might do with it on their own.

Thank You,

I wouldn’t call it a script. It was just an example. But you don’t check the input format either, so the following produces an error from mogrify:

./convert2 jpg test
mogrify: Not a JPEG file: starts with 0x23 0x21 `test' @ error/jpeg.c/EmitMessage/233.

Or did I miss something in the syntax of this script?

So, what kind of file is test since it has no file extension?

./convert2 jpg test
mogrify: Not a JPEG file: starts with 0x23 0x21 `test' @ error/jpeg.c/EmitMessage/233.

I am not suggesting that all errors are found by the script, but it does some more checking than none. Of course, what are we arguing over anyway? You are obviously a master bash script file writer while I am on the other end, trying to learn bash scripting while coming up with something that might be useful.

What caught my eye on this script was the ability to check for different command line options using the case command and the usage of the shift command. When I saw that it also converted image types, something I do all of the time, I thought it was a perfect script to work on and expand on.

Now I am trying to keep the pressure up here in the scripting department. I need for you to start rowing in the same direction as I am. I tried to do my part here master script writer. Its your turn to come up with another script as useful as findgrub was.

Thank You,

$ convert -list format
   Format  Module    Mode  Description
-------------------------------------------------------------------------------
      3FR  DNG       r--   Hasselblad CFV/H3D39II
        A* RAW       rw+   Raw alpha samples
       AI  PDF       rw-   Adobe Illustrator CS2
      ART* ART       rw-   PFS: 1st Publisher Clip Art
      ARW  DNG       r--   Sony Alpha Raw Image Format
      AVI* AVI       r--   Microsoft Audio/Visual Interleaved
      AVS* AVS       rw+   AVS X image
        B* RAW       rw+   Raw blue samples
      BGR* RGB       rw+   Raw blue, green, and red samples
     BGRA* RGB       rw+   Raw blue, green, red and alpha samples
      BMP* BMP       rw-   Microsoft Windows bitmap image (V5)
     BMP2* BMP       -w-   Microsoft Windows bitmap image (V2)
     BMP3* BMP       -w-   Microsoft Windows bitmap image (V3)
      BRF* BRAILLE   -w-   BRF ASCII Braille format
      BRG* RGB       rw+   Raw blue, red, and green samples
        C* RAW       rw+   Raw cyan samples
      CAL* CALS      rw-   Continuous Acquisition and Life-cycle Support Type 1
           Specified in MIL-R-28002 and MIL-PRF-28002
     CALS* CALS      rw-   Continuous Acquisition and Life-cycle Support Type 1
           Specified in MIL-R-28002 and MIL-PRF-28002
  CAPTION* CAPTION   r--   Image caption
      CIN* CIN       rw+   Cineon Image File
      CIP* CIP       -w-   Cisco IP phone image format
     CLIP* CLIP      -w+   Image Clip Mask
     CMYK* CMYK      rw+   Raw cyan, magenta, yellow, and black samples
    CMYKA* CMYK      rw+   Raw cyan, magenta, yellow, black, and alpha samples
      CR2  DNG       r--   Canon Digital Camera Raw Image Format
      CRW  DNG       r--   Canon Digital Camera Raw Image Format
      CUR* CUR       rw-   Microsoft icon
      CUT* CUT       r--   DR Halo
      DCM* DCM       r--   Digital Imaging and Communications in Medicine image
           DICOM is used by the medical community for images like X-rays.  The
           specification, "Digital Imaging and Communications in Medicine
           (DICOM)", is available at http://medical.nema.org/.  In particular,
           see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),
           and supplement 61 which adds JPEG-2000 encoding.
      DCR  DNG       r--   Kodak Digital Camera Raw Image File
      DCX* PCX       rw+   ZSoft IBM PC multi-page Paintbrush
      DDS* DDS       r--   Microsoft DirectDraw Surface
    DFONT* TTF       r--   Multi-face font package (Freetype 2.3.12)
      DNG  DNG       r--   Digital Negative
      DOT  DOT       ---   Graphviz
      DPX* DPX       rw-   SMPTE 268M-2003 (DPX 2.0)
           Digital Moving Picture Exchange Bitmap, Version 2.0.
           See SMPTE 268M-2003 specification at http://www.smtpe.org
           
     EPDF  PDF       rw-   Encapsulated Portable Document Format
      EPI  PS        rw-   Encapsulated PostScript Interchange format
      EPS  PS        rw-   Encapsulated PostScript
     EPS2* PS2       -w-   Level II Encapsulated PostScript
     EPS3* PS3       -w+   Level III Encapsulated PostScript
     EPSF  PS        rw-   Encapsulated PostScript
     EPSI  PS        rw-   Encapsulated PostScript Interchange format
      EPT  EPT       rw-   Encapsulated PostScript with TIFF preview
     EPT2  EPT       rw-   Encapsulated PostScript Level II with TIFF preview
     EPT3  EPT       rw+   Encapsulated PostScript Level III with TIFF preview
      ERF  DNG       r--   Epson RAW Format
      FAX* FAX       rw+   Group 3 FAX
           FAX machines use non-square pixels which are 1.5 times wider than
           they are tall but computer displays use square pixels, therefore
           FAX images may appear to be narrow unless they are explicitly
           resized using a geometry of "150x100%".
           
     FITS* FITS      rw-   Flexible Image Transport System
  FRACTAL* PLASMA    r--   Plasma fractal image
      FTS* FTS       rw-   Flexible Image Transport System
        G* RAW       rw+   Raw green samples
       G3* FAX       rw-   Group 3 FAX
      GBR* RGB       rw+   Raw green, blue, and red samples
      GIF* GIF       rw+   CompuServe graphics interchange format
    GIF87* GIF       rw-   CompuServe graphics interchange format (version 87a)
 GRADIENT* GRADIENT  r--   Gradual linear passing from one shade to another
     GRAY* GRAY      rw+   Raw gray samples
      GRB* RGB       rw+   Raw green, red, and blue samples
   GROUP4* TIFF      rw-   Raw CCITT Group4
     HALD*           r--   Identity Hald color lookup table image
HISTOGRAM* HISTOGRAM -w-   Histogram of the image
      HRZ* HRZ       rw-   Slow Scan TeleVision
      HTM* HTML      -w-   Hypertext Markup Language and a client-side image map
     HTML* HTML      -w-   Hypertext Markup Language and a client-side image map
      ICB* TGA       rw+   Truevision Targa image
      ICO* ICON      rw+   Microsoft icon
     ICON* ICON      rw-   Microsoft icon
     INFO  INFO      -w+   The image format and characteristics
   INLINE* INLINE    r--   Base64-encoded inline images
      IPL* IPL       rw+   IPL Image Sequence
   ISOBRL* BRAILLE   -w-   ISO/TR 11548-1 format
      JNG* PNG       rw-   JPEG Network Graphics
           See http://www.libpng.org/pub/mng/ for details about the JNG
           format.
     JPEG* JPEG      rw-   Joint Photographic Experts Group JFIF format (80)
      JPG* JPEG      rw-   Joint Photographic Experts Group JFIF format (80)
        K* RAW       rw+   Raw black samples
      K25  DNG       r--   Kodak Digital Camera Raw Image Format
      KDC  DNG       r--   Kodak Digital Camera Raw Image Format
    LABEL* LABEL     r--   Image label
        M* RAW       rw+   Raw magenta samples
      M2V  MPEG      rw+   MPEG Video Stream
      M4V  MPEG      rw+   Raw MPEG-4 Video
      MAP* MAP       rw-   Colormap intensities and indices
      MAT  MAT       rw+   MATLAB image format
    MATTE* MATTE     -w+   MATTE format
     MIFF* MIFF      rw+   Magick Image File Format
      MNG* PNG       rw+   Multiple-image Network Graphics (libpng 1.4.3)
           See http://www.libpng.org/pub/mng/ for details about the MNG
           format.
     MONO* MONO      rw-   Raw bi-level bitmap
      MOV  MPEG      rw+   MPEG Video Stream
      MP4  MPEG      rw+   MPEG-4 Video Stream
      MPC* MPC       rw+   Magick Persistent Cache image format
     MPEG  MPEG      rw+   MPEG Video Stream
      MPG  MPEG      rw+   MPEG Video Stream
      MRW  DNG       r--   Sony (Minolta) Raw Image File
      MSL* MSL       rw+   Magick Scripting Language
     MSVG  SVG       rw+   ImageMagick's own SVG internal renderer
      MTV* MTV       rw+   MTV Raytracing image format
      MVG* MVG       rw-   Magick Vector Graphics
      NEF  DNG       r--   Nikon Digital SLR Camera Raw Image File
     NULL* NULL      rw-   Constant image of uniform color
        O* RAW       rw+   Raw opacity samples
      ORF  DNG       r--   Olympus Digital Camera Raw Image File
      OTB* OTB       rw-   On-the-air bitmap
      OTF* TTF       r--   Open Type font (Freetype 2.3.12)
      PAL* UYVY      rw-   16bit/pixel interleaved YUV
     PALM* PALM      rw+   Palm pixmap
      PAM* PNM       rw+   Common 2-dimensional bitmap format
  PATTERN* PATTERN   r--   Predefined pattern
      PBM* PNM       rw+   Portable bitmap format (black and white)
      PCD* PCD       rw-   Photo CD
     PCDS* PCD       rw-   Photo CD
      PCL  PCL       rw+   Printer Control Language
      PCT* PICT      rw-   Apple Macintosh QuickDraw/PICT
      PCX* PCX       rw-   ZSoft IBM PC Paintbrush
      PDB* PDB       rw+   Palm Database ImageViewer Format
      PDF  PDF       rw+   Portable Document Format
     PDFA  PDF       rw+   Portable Document Archive Format
      PEF  DNG       r--   Pentax Electronic File
      PES* PES       r--   Embrid Embroidery Format
      PFA* TTF       r--   Postscript Type 1 font (ASCII) (Freetype 2.3.12)
      PFB* TTF       r--   Postscript Type 1 font (binary) (Freetype 2.3.12)
      PFM* PFM       rw+   Portable float format
      PGM* PNM       rw+   Portable graymap format (gray scale)
    PICON* XPM       rw-   Personal Icon
     PICT* PICT      rw-   Apple Macintosh QuickDraw/PICT
      PIX* PIX       r--   Alias/Wavefront RLE image format
    PJPEG* JPEG      rw-   Joint Photographic Experts Group JFIF format (80)
   PLASMA* PLASMA    r--   Plasma fractal image
      PNG* PNG       rw-   Portable Network Graphics (libpng 1.4.3)
           See http://www.libpng.org/ for details about the PNG format.
    PNG24* PNG       rw-   opaque 24-bit RGB (zlib 1.2.3)
    PNG32* PNG       rw-   opaque or transparent 32-bit RGBA
     PNG8* PNG       rw-   8-bit indexed with optional binary transparency
      PNM* PNM       rw+   Portable anymap
      PPM* PNM       rw+   Portable pixmap format (color)
  PREVIEW* PREVIEW   -w-   Show a preview an image enhancement, effect, or f/x
       PS  PS        rw+   PostScript
      PS2* PS2       -w+   Level II PostScript
      PS3* PS3       -w+   Level III PostScript
      PSB* PSD       rw+   Adobe Large Document Format
      PSD* PSD       rw+   Adobe Photoshop bitmap
     PTIF* TIFF      rw+   Pyramid encoded TIFF
      PWP* PWP       r--   Seattle Film Works
        R* RAW       rw+   Raw red samples
RADIAL-GRADIENT* GRADIENT  r--   Gradual radial passing from one shade to another
      RAF  DNG       r--   Fuji CCD-RAW Graphic File
      RAS* SUN       rw+   SUN Rasterfile
      RBG* RGB       rw+   Raw red, blue, and green samples
      RGB* RGB       rw+   Raw red, green, and blue samples
     RGBA* RGB       rw+   Raw red, green, blue, and alpha samples
     RGBO* RGB       rw+   Raw red, green, blue, and opacity samples
      RLA* RLA       r--   Alias/Wavefront image
      RLE* RLE       r--   Utah Run length encoded image
      SCR* SCR       r--   ZX-Spectrum SCREEN$
      SCT* SCT       r--   Scitex HandShake
      SFW* SFW       r--   Seattle Film Works
      SGI* SGI       rw+   Irix RGB image
    SHTML* HTML      -w-   Hypertext Markup Language and a client-side image map
      SR2  DNG       r--   Sony Raw Format 2
      SRF  DNG       r--   Sony Raw Format
  STEGANO* STEGANO   r--   Steganographic image
      SUN* SUN       rw+   SUN Rasterfile
      SVG  SVG       rw+   Scalable Vector Graphics (XML 2.7.7)
     SVGZ  SVG       rw+   Compressed Scalable Vector Graphics (XML 2.7.7)
     TEXT* TXT       rw-   Text
      TGA* TGA       rw+   Truevision Targa image
THUMBNAIL* THUMBNAIL -w+   EXIF Profile Thumbnail
     TIFF* TIFF      rw+   Tagged Image File Format (LIBTIFF, Version 3.9.2)
   TIFF64* TIFF      ---   Tagged Image File Format (64-bit) (LIBTIFF, Version 3.9.2)
     TILE* TILE      r--   Tile image with a texture
      TIM* TIM       r--   PSX TIM
      TTC* TTF       r--   TrueType font collection (Freetype 2.3.12)
      TTF* TTF       r--   TrueType font (Freetype 2.3.12)
      TXT* TXT       rw-   Text
     UBRL* BRAILLE   -w-   Unicode Text format
      UIL* UIL       -w-   X-Motif UIL table
     UYVY* UYVY      rw-   16bit/pixel interleaved YUV
      VDA* TGA       rw+   Truevision Targa image
    VICAR* VICAR     rw-   VICAR rasterfile format
      VID* VID       rw+   Visual Image Directory
     VIFF* VIFF      rw+   Khoros Visualization image
      VST* TGA       rw+   Truevision Targa image
     WBMP* WBMP      rw-   Wireless Bitmap (level 0) image
      WMV  MPEG      rw+   Windows Media Video
      WPG* WPG       r--   Word Perfect Graphics
        X* X         rw+   X Image
      X3F  DNG       r--   Sigma Camera RAW Picture File
      XBM* XBM       rw-   X Windows system bitmap (black and white)
       XC* XC        r--   Constant image uniform color
      XCF* XCF       r--   GIMP image
      XPM* XPM       rw-   X Windows system pixmap (color)
      XPS  XPS       r--   Microsoft XML Paper Specification
       XV* VIFF      rw+   Khoros Visualization image
      XWD* XWD       rw-   X Windows system window dump (color)
        Y* RAW       rw+   Raw yellow samples
    YCbCr* YCbCr     rw+   Raw Y, Cb, and Cr samples
   YCbCrA* YCbCr     rw+   Raw Y, Cb, Cr, and alpha samples
      YUV* YUV       rw-   CCIR 601 4:1:1 or 4:2:2

* native blob support
r read support
w write support
+ support for multiple images

Wow RedDwarf, it will take forever to code in everything it supports it would seem. Thanks very much for the information. By the way, did you look at the mmcheck script I put together using your 10-steps guide? It really helped me out and automating it seemed like the right thing to do. I can’t thank you enough for putting together that 10-steps thread to help us all out.

Thank You,

Hi James
Might be time for to look at something like perl, I’m sure there is a
cpan module to do a lot of the work for you…

There is also a script (trying to remember where) that will download a
module from cpan and build a spec file and make an rpm (then could
upload to OBS) for installing into openSUSE.

You should also consider making your scripts into and rpm, then you
could update and push out to users.


Cheers Malcolm °¿° (Linux Counter #276890)
SUSE Linux Enterprise Desktop 11 (x86_64) Kernel 2.6.32.23-0.3-default
up 1 day 4:37, 4 users, load average: 0.00, 0.06, 0.07
GPU GeForce 8600 GTS Silent - Driver Version: 260.19.12

Ahh here it is;
http://en.opensuse.org/openSUSE:Packaging_Perl


Cheers Malcolm °¿° (Linux Counter #276890)
SUSE Linux Enterprise Desktop 11 (x86_64) Kernel 2.6.32.23-0.3-default
up 1 day 5:08, 4 users, load average: 0.18, 0.08, 0.03
GPU GeForce 8600 GTS Silent - Driver Version: 260.19.12

Hi James,
File extension is a Windows kind of thing. convert and mogrify - as other ImageMagick tools - read the magic number to determine the format of the input file. test was a text file intended to demonstrate that this script doesn’t check the input format (neither did my example). If you wanted to check the input format in order for your script to handle only supported graphic formats and ignore the others (avoiding errors), I would suggest replacing this line

 -f "$a" ] && echo mogrify -format $TYPE $a || continue

with those lines

if  -f "$a" ] ; then
    file "$a" | grep -q -i -e JPG -e JPEG -e PNG -e pixmap -e PDF -e GIF || continue
    mogrify -format $TYPE $a || continue
fi

Notice that JPG, JPEG, PNG, etc don’t refer to file extensions. These strings are just part of the output of the command file applied to each argument. You can complete this list with other strings when you know the ouptut of file for other graphics formats (like Windows bitmaps or tiff for example).

if  -f "$a" ] ; then
    file "$a" | grep -q -i -e JPG -e JPEG -e PNG -e pixmap -e PDF -e GIF || continue
    mogrify -format $TYPE $a || continue
fi

This is great stuff as usual. I must say that I like file extensions as a quick way to know a file’s type. I understand that files don’t need this in Linux, I just like to use them, that is all. I know that the extension could be wrong, but for what reason? The script did not check the files internals to see if it was the proper image type for conversion. I am not sure how I would use your example. I was only checking for a supported file type command, to make sure it was supported, but in light of RedDwarf’s list, I am coming up short. I do have the ones I normally use included.

So if you were going to write a script that made the task of conversion easier, could provide help later after you forgot what you did and provided value added support, what would you write? Consider that there is no penalty for putting extra text or commands in the script, only that is does the job with reasonable error checking for proper user input. What would you write? Also throw in the thought that your example code could be an insprirtation to others to write more scripts and where at least you could go and borrow a section for a new script that you are writing.

When I decide to write a script, I remember that I had to perform certian tasks before and just copy them for reuse in the new script, trying to not recreate the wheel again. Now when making examples for others, all of the wheels we are showing have been done before, but that does not matter when trying to show others how to write scripts. I know one thing and that is every scriptlet you write please_try_again goes into my collection, should I figure out how to use it again.

Thank You,

Thank You,

Saw it. Seems ok, but I’m not really familiar enough with the scripting functions you used to be able to judge.

In fact in Linux we also mostly use the extensions to identify files. Check the “Recommended checking order” section of Shared MIME-info Database

Yes and no. You can use extensions like file.cfg or file.txt because they are both text files which don’t serve the same purpose, but trying to convert or even open a graphic file based on its extension … is a Windows kind of thing. IMHO freedesktop is not Unix, freedesktop is also a Windows kind of thing (and I’m programming a lot wit freedesktop unfortunately). :sarcastic: Ok … it’s not too bad. In fact it got a lot better over the years, the time it took for the wms (specially KDE) to adapt.

Because people are wrong, eat wrong, think wrong, use wrong operating systems in the wrongest manner … That’s usually how things are (unless I’m wrong) :wink:

Hmmm … If you’re asking me … but, you know, my scripting style can become very quickly a write only kind of thing … OK, I quickly added some stuff but don’t have the time to test everything.

I added all the supported formats in 2 arrays: one for the format, one for the description. So the script will display the description (I guess you wanted more infos). If the format is unsupported the script will tell you and skip this file (so not try to convert or mogrify at all). The user has the possibility to add more formats in the array addFormats, following the syntax already used:
“format : description”
This array will be parsed and its content added to the frmt(formats) and desc(description) arrays. You won’t add formats because of new formats but because of different strings existing formats may output in their magic info.

@RedDwarf, I know what you might be tending to say … but I don’t have time.

I had to move some stuff : checking if mogrify is available (because I needed it to list the formats) before checking the arguments. It makes more sense anyway. Why would you check the arguments if the program you want to use is missing?

I also kept ‘mogrify’ but gave you the choice to use ‘convert’ instead. You should use the one or the other based of what those programs really do, not because you prefer one syntax or the other. You can see that both commands have exactly the same length (ok, I admit the second one look more fancy).

#!/bin/bash

#: Title       : Convert2 
#: Date Created: Fri Oct 8 21:29:50 CDT 2010
#: Last Edit   : Fri Oct 22 23:31:11 PDT 2010
#: Author      : Dawid Michalczyk & J. McDaniel
#: modified by : Please_try_again (added format check) 
#: Version     : 1.00
#: Description : Convert image file from/to - bmp png jpg gif pdf - format
#: Options     : Convert2 [type] [-vhlr] <file> [file...]

# Created for the openSUSE Forums on Thursday October 21th, 2010

# Copy and paste this text into a file called convert2 in your home ~/bin folder
# To Make this script executable run the terminal command chmod +x ~/bin/convert2

# #############################################################################

       NAME_="Convert2"
    PURPOSE_="Convert image file from/to - bmp png jpg jpg pdf - format"
   SYNOPSIS_="$NAME_ [type] [-vhlr] <file> [file...]"
   REQUIRES_="standard GNU commands, ImageMagick"
    VERSION_="1.00"
#    IMAGES_="bmp png jpg gif pdf"
# #############################################################################
# This program is distributed under the terms of the GNU General Public License

#
# Display Help If requested
#

usage () {

echo
echo >&2 "$NAME_ $VERSION_ - $PURPOSE_
Usage: $SYNOPSIS_
Requires: $REQUIRES_
Type: bmp, png, jpg, gif or pdf: default Type is jpg
Options:
     -r, remove the input file after conversion
     -v, verbose
     -h, usage and options (this help)
     -l, see this script,, use Q to quit"
echo
    exit 1
}

#
# check if required command is in $PATH variable
#

which mogrify &> /dev/null
[[ $? != 0 ]] && { echo >&2 the required ImageMagick \"mogrify\" command \
is not in your PATH variable; exit 1; }



# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# get the list supported formats and create two arrays : frmt (format strings) and desc (descriptions). 
eval `mogrify -list format | sed 's|HALD\*|& HALD|;/X Image/d' | awk 'BEGIN { I = -1 } ; /r.[+-]/ { I++ ; TYPE=$2 ; $1=""; $2=""; $3="" ; DESC=$0 ; sub (/^ */, "", DESC) ;  printf "frmt[%i]=\"%s\"; desc[%i]=\"%s\";", I, TYPE, I, DESC }'`

# add user defined types (based of the output of the file command)
addFormats=(\
"X pixmap : X pixmap image text" \
"ASCII C : X Windows system bitmap (black and white)" \
"GIMP brush data : X Windows system bitmap (black and white)" \
)

i=${#frmt[li]}
[/li]
for f in "${addFormats[@]}" ; do
	frmt[$i]="${f%:*}"
	desc[$i]="${f#*:}"
	let i++
done

# exit if count of formats and count of descriptions don't match (should not happen)
[ ${#frmt[li]} -eq ${#desc[*]} ] || exec echo "error: formats and descriptions don't match"
[/li]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


#
# args check - Did we get any commands
#

echo

[ $# -eq 0 ] && { echo >&2 missing argument, type $NAME_ -h for help; exit 1; }

#
# Check for Image Type for conversion - Default will be jpg if not specified
#

TYPE=$1

#if [[ "$IMAGES_" == *$TYPE* ]] ; then
#  shift
#else
#  TYPE=jpg 
#fi

#
# varible setup
#

rm_input=
verbose=

#
# option and argument handling
#

while getopts vhlr options; do

    case "$options" in
        r) rm_input=on ;;
        v) verbose=on ;;
        h) usage ;;
        l) less $0; exit 1 ;;
       \?) echo invalid argument, type $NAME_ -h for help; exit 1 ;;
    esac

done
shift $(( $OPTIND - 1 ))

 

# get format of input file according to its magic number
#
function getformat() {

i=0
Desc=$(file -b $1)

while [ $i -lt ${#frmt[li]} ] ; do
[/li]	echo $Desc | grep -q "${frmt[$i]}" && echo $Desc && return
	let i++
done

echo "Unsupported format"

}

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#
# main progrm execution starts here
#

for a in "$@"; do

    newf=$(echo "${a%.*}".$TYPE)
    if [ -f "$newf" ]; then
        echo "${NAME_}: skipping converting $a - $newf already exist" && continue
    else
        #[ -f "$a" ] && echo mogrify -format $TYPE $a || continue
        if [ -f "$a" ] ; then
			af=$(getformat $a)
			[ "$af" == "Unsupported format" ] && echo "skipping converting $a - unsupported format" && continue 
			echo "converting $a ( $af ) to $TYPE"
			mogrify -format $TYPE $a || continue
			#convert $a ${a%.*}.$TYPE || continue

		fi
        [[ $verbose ]] && echo "${NAME_}: $a -> $newf"
        [[ $rm_input ]] && rm -f -- "$a"
    fi

done

echo

exit 0

# end of script file

[ul]
[li]Red: removed/commented out
[/li][li]Blue: moved
[/li][li]Green: added
[/li][/ul]

Thy might be bugs but they would be easy to fix …

wow thats an epic script!
im gonna be using this for a while
used to use online converters but they suck so i really appreciate this :slight_smile:
regards

There are many online converters avialble these days that can do this conversion for you and you don;t have to go through all this coding and they also provide samples codes so that you can use them in your APIs also. The converter which i use is Aspose.PDF for java](http://www.aspose.com/java/pdf-component.aspx) for converting pdf file to/from images and to many other formats using many other programming languages.