Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

A script to create IMG tags from a folder of pictures Internet
If, like me, you do most of your HTML coding in a text editor, then perhaps you've found one of the most tiresome chores is loading every little image you've made for a button or background into Preview or similar package to find out its dimensions for correct handling in HTML (i.e. <img src=filename height=y width=x>).

To alleviate this a little, I've written a small Python script. When run from the Terminal, the script will search for all JPEG, GIF or PNG images in the current directory, and output a user-named HTML file. The file will include each image's name plus its dimensions in HTML format, ready for you to copy and paste into your working document. I've found it's saved me a lot of time on the site I'm currently building, and I hope it might help you, too.

My imgDetails.py script [view source] uses the extremely-useful Mac OS 10.3 command line utility sips, which allows you to query (and modify if you wish) images from the Terminal. This utility was only added in 10.3, hence my script will not work on prior versions of Mac OS X.

[robg adds: I tested this one, and it worked as described -- you get a nice HTML file that contains the IMG tags with the proper 'width' and 'height' tags already included.]
    •    
  • Currently 3.20 / 5
  You rated: 5 / 5 (5 votes cast)
 
[10,647 views]  

A script to create IMG tags from a folder of pictures | 13 comments | Create New Account
Click here to return to the 'A script to create IMG tags from a folder of pictures' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
A script to create IMG tags from a folder of pictures
Authored by: josh3io on Dec 22, '04 10:45:17AM
I use php to do this so I can add images to the dir without making changes to anything:

<?
# index.php
# $dir is the dir that holds your images
$dir = '.';
$ary = array();
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
                if (!is_dir($file) && !strstr($file,'index')) {
                        echo "<img src=\"$file\"/><br>";
                }
       }
       closedir($dh);
   }
?>


[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: tforrest on Dec 22, '04 01:28:32PM

Am I missing something? The PHP script is very cool but it appears to me that it does not give you the width and height values (which was kinda the focus of this hint...)



[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: Telluride on Dec 23, '04 10:28:43AM
try this. php's image manipulation functions are pretty good. You can even create thumbnails, resize-images, etc on the fly.

<?
# index.php
# $dir is the dir that holds your images
$dir = '.';
$ary = array();
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
                if (!is_dir($file) && !strstr($file,'index')) {
                        echo "<img src=\"$file\"/><br>";
                }
       }
       closedir($dh);
   }
?>


[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: Telluride on Dec 23, '04 10:30:30AM
OOPS! Wrong paste of code! Corrected version:

<?
# index.php
# $dir is the dir that holds your images
$dir = '.';
$ary = array();
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
                if (!is_dir($file) && !strstr($file,'index')) {
                        list($h,$w,$type,$dimensions) = getimagesize($file);
                        echo "<img src=\"$file\" $dimensions>\n<br>\n";
                }
       }
       closedir($dh);
   }
?>


[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: kmue on Dec 22, '04 11:22:23AM

Unfortunately the script can't handle spaces in filenames. Also filenames with UTF characters are not handled properly.

Does anybody know how to fix it?



[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: foilpan on Dec 22, '04 11:27:23AM
the free QuickImageCM from hide itoh does this in batch mode. it copies the image tag information, and you can paste it into a file for later use. it works with files containing spaces in their names, too.

pixture.com

[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: carstenjs on Dec 22, '04 12:11:59PM
Not exactly the same, but maybe it does exactly what you want - I'm using this script for many years for web developement. The perl-script wwwis from Alex K. updates the images in your html code with the necessary size information.

[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: koncept on Dec 22, '04 02:27:28PM
I wrote this as a shell script for anybody who is interested. It will open the results in TextEdit

#!/bin/bash
###########################################################
# Usage: imgDetails.sh
#
# Script will save to /private/tmp/imgDetails_(PID).html 
# with the details of images it came across in the current 
# directory which the script was run. When complete, 
# the script will open the tmp file in textEdit.
############################################################
declare -r OUT=/private/tmp/imgDetails_$(echo $$).html
declare -r CMD="sips -g pixelWidth -g pixelHeight"
declare -a PROPS=()
declare -ar ALLOWED=(
*.jpg *.JPG *.jpeg
*.GIF *.gif
*.png *.PNG
)

let COUNT=0

for ITEM in ${ALLOWED[@]}; do
  if [ -f $ITEM ]; then
    pos=0
    for PROP in $($CMD "$ITEM"|tail -2|sed 's/ //g'|awk -F':' '{print $2}')
    do
      echo $PROP | egrep '[0-9]+'>/dev/null 2>&1
      if [ $? == 0 ]; then
        PROPS[$pos]=$PROP
        pos=$((pos+1))
      fi
    done
    if [ -n ${PROPS[0]} -a -n ${PROPS[1]} ]; then
      echo "<img src=\"${ITEM}\" width=\"${PROPS[0]}\" " \
        "height=\"${PROPS[1]}\" alt=\"${ITEM}\" />" | tee -a $OUT
      COUNT=$((COUNT+1))
    fi      
  fi
done

echo -e "\nAttempted to process (${COUNT}) files."

[ -f $OUT ] && open -e $OUT

exit 0


[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: koncept on Dec 22, '04 02:44:40PM
Made a slight change. I didn't see the ability to repost, so here it is again.

#!/bin/bash
#
###########################################################
# Usage: imgDetails.sh
#
# Script will save to /private/tmp/imgDetails_(PID).html 
# with the details of images it came across in the current 
# directory which the script was run. When complete, 
# the script will open the tmp file in textEdit.
############################################################
#
declare -i COUNT=0
declare -i SUCCESS=0
declare -r OUT=/private/tmp/imgDetails_$(echo $$).html
declare -r CMD="sips -g pixelWidth -g pixelHeight"
declare -ar ALLOWED=(*.jpg *.JPG *.jpeg *.GIF *.gif *.png *.PNG)

for ITEM in ${ALLOWED[@]}; do
  if [ -f $ITEM ]; then
    declare -i POS=0
    declare -a PROPS=()
    for PROP in $($CMD "$ITEM"|tail -2|sed 's/ //g'|awk -F':' '{print $2}')
    do
      echo $PROP | egrep '[0-9]+'>/dev/null 2>&1
      if [ $? == 0 ]; then
        PROPS[$POS]=$PROP
        POS=POS+1
      fi
    done
    if [ -n ${PROPS[0]} -a -n ${PROPS[1]} ]; then
      echo "<img src=\"${ITEM}\" width=\"${PROPS[0]}\" " \
        "height=\"${PROPS[1]}\" alt=\"${ITEM}\" />" | tee -a $OUT
      [ $? == 0 ] && SUCCESS=SUCCESS+1
    fi
    COUNT=COUNT+1
  fi
done

echo -e "\nAttempted to process (${COUNT}) files."
echo -e "Successfully processed (${SUCCESS}) files."

[ -f $OUT ] && open -e $OUT

exit 0


[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: guybrush on Dec 22, '04 05:18:32PM
the python script uses an external command "sips" to get the width/height of the image, but OS X supports Quartz commands in python. Taken from /Developer/Examples/Quartz/Python/image.py:
from CoreGraphics import *

i = CGImageImport (CGDataProviderCreateWithFilename (inputFile))
print "Image '%s' size is (%d,%d)" % (inputFile, i.getWidth(), i.getHeight())
works great, has other nice features as well, just check the /Developer/Examples/Quartz/Python dir :)

[ Reply to This | # ]
A script to create IMG tags from a folder of pictures
Authored by: gshenaut on Dec 23, '04 03:12:09PM
If your text editor lets you insert the output of a shell command into the file, then a small script such as
#!/bin/ksh

i=$*
if [[ "$i" = "" ]] ; then
	read i
fi

w=$(sips -g pixelWidth "$i" | tail -1 | rev | cut -d' ' -f1 | rev)
h=$(sips -g pixelHeight "$i" | tail -1 | rev | cut -d' ' -f1 | rev)

print "<img src=\"$i\" height=$h width=$w>"
may be convenient (I'm sorry for the way too complicated rev|cut|rev stuff, but I can't get my brain to kick in to find something easier).

For example, in vi, you could put in an empty line, then type

!!putimg file.jpg<RETURN>
and the html code will be inserted into your file. (I named the script "putimg".)

The stuff at the top where it reads the name of the image file from standard input is so that if you put the name of the image file by itself on the current line in your text file, then type

!!putimg<RETURN>
the line will be replaced with the html code.

Cheers,

Greg Shenaut

[ Reply to This | # ]

A script to create IMG tags from a folder of pictures
Authored by: gregraven on Dec 25, '04 11:40:08AM

If you use BBEdit, you can create a new .html document, select the image files in the Finder, and then drag-n-drop them between the <BODY> tags in the document. There will be a dialog box where you get to set characteristics for the dropped images as a group.

---
--
Greg Raven
Apple Valley, CA



[ Reply to This | # ]
simpler img script
Authored by: Florian Bösch on Dec 27, '04 11:45:36AM
I would propose a much simpler, cleaner, portable and more powerfull script. something like:

#!/usr/bin/python
try: import sys, os, Image
except: print >> sys.stderr, 'Please install Python Imaging Library to run this script.'
else:
    if __name__=='__main__':
        if len(sys.argv) == 1: outstream = sys.stdout
        elif len(sys.argv) == 3 and sys.argv[1] == '-f': outstream = open( sys.argv[2], 'w' )
        else:
            print '\nUSAGE : "%s" <output filename>'%sys.argv[0]
            sys.exit( -1 )
        
        extensions = ['JPG', 'jpg', 'JPEG', 'jpeg', 'GIF', 'gif', 'PNG', 'png']
        file_list = [name for name in os.listdir('.') if name.split('.')[-1] in extensions]

        for image_name in file_list:
            try:
                width, height = Image.open( image_name ).size
                print >> outstream, '<img src="%s" width="%s" height="%s">'%(image_name,width,height)
            except:
                print >> sys.stderr, 'Unexpected error for file %s.'%image_name


[ Reply to This | # ]