472,805 Members | 1,124 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,805 software developers and data experts.

Generating Thumbnail Images of a Photo Gallery

The following is a program to generate thumbnail images for a website.
Useful, if you want to do that.

It is used to generate the thumbnails for my “Banners, Damsels, and
Mores” project gallery. (
http://xahlee.org/Periodic_dosage_dir/lanci/lanci.html )

Comments and versions in other lang welcome.

# -*- coding: utf-8 -*-
# Python

# © 2006-04 by Xah Lee, ∑ http://xahlee.org/, 2006-04

# Given a webite gallery of photos with hundreds of photos, i want to
generate a thumbnail page so that viewers can get a bird's eye's view

# Technically:
# Given a dir: e.g. /Users/xah/web/Periodic_dosage_dir/lanci/
# This dir has many html files inside it, maybe in sub dir.
# Any html file is a photo gallery, with inline images of photos.
# all the image files are in under the given dir, or in subdir.

# • The goal is to create thumbnail images of all the inline images
in all html files under that dir.
# • These thumbnail images destination can be specified, unrelated to
the given dir.
# • Thumbnail images must preserve the dir structure they are in. For
example, if a inline image's full path is /a/b/c/d/1.img, and the a
root is given as /a/b, then the thumbnail image's path must retain the
c/d, as sud bir under the specified thumbnail destination.
# • if the inline image's size is smaller than a certain given size
(specified as area), then skip it.

# Note: online inline images in a html file will be considered for
thumbnail. Any other images in the given dir or as linked images should
be ignored.
import re, subprocess, os.path

# path where html files and images are at. e.g. /a/b/c/d
inPath= '/Users/xah/3D-XplorMath/Curves' # no trailing slash

# a substring of inPath. The thumbnails will preserve dir structures.
If a image is at /a/b/c/d/e/f/1.png, and rootDir is /a/b/c, then the
thumbnail will be at /x/y/d/e/f/1.png
rootDir= '/Users/xah/3D-XplorMath/Curves' # no trailing slash

# the destination path of thumbanil images. It will be created.
Existing things will be over-written. e.g. /x/y
thumbnailDir= '/Users/xah/3D-XplorMath/Curves/tn' # no trailing slash

# thumbnail size
thumbnailSizeArea = 150 * 150

# if a image is smaller than this area, don't gen thumbnail for it.
minArea = 200*200

# imageMagic 'identify' program path
identify = r'/sw/bin/identify'
convert = r'/sw/bin/convert'

# depth of nested dir to dive into.
minLevel=1; # files and dirs of mydir are level 1.
maxLevel=9; # inclusive

## functions

def scaleFactor(A,(w,h)):
'''getInlineImg(A,(w,h)) returns a number s such that w*s*h*s==A.
This is used for generating the scaling factor of a image with a given
desired thumbnail area A. The w and h are width and height of rectangle
(image). The A is given size of thumbnail of the photo (as area). When
the image is scaled by s in both dimensions, it will have desired size
specified by area A as thumbnail.'''
return (float(A)/float(w*h))**0.5

def getInlineImg(file_full_path):
'''getInlineImg(html_file_full_path) returns a array that is a list
of inline images. For example, it may return
FF = open(file_full_path,'rb')
txt_segs = re.split( r'src', unicode(FF.read(),'utf-8'))
for linkBlock in txt_segs:
matchResult = re.search(ur'\s*=\s*\"([^\"]+)\"',
if matchResult: linx.append(
matchResult.group(1).encode('utf-8') )
return linx

def linkFullPath(dir,locallink):
'''linkFullPath(dir, locallink) returns a string that is the full
path to the local link. For example,
linkFullPath('/Users/t/public_html/a/b', '../image/t.png') returns
'Users/t/public_html/a/image/t.png'. The returned result will not
contain double slash or '../' string.'''
result = dir + '/' + locallink
result = re.sub(r'//+', r'/', result)
while re.search(r'/[^\/]+\/\.\.', result): result =
re.sub(r'/[^\/]+\/\.\.', '', result)
return result
def buildThumbnails(dPath, fName, tbPath, rPath, areaA):
u'''Generate thumbnail images. dPath is directory full path, and
fName is a html file name that exists under it. The tbPath is the
thumbnail images destination dir. The areaA is the thumbnail image size
in terms of its area. This function will create thumbnail images in the
tbPath. rPath is a root dir subset of dPath, used to build the dir
structure for tbPath for each thumbnail.

For Example, if
dPath = '/Users/mary/Public/pictures'
fName = 'trip.html' (this exits under dPath)
tbPath = '/Users/mary/Public/thumbs'
rPath = '/Users/mary/Public' (must be a substring of dPath or equal to
and trip.html contains <img ="Beijin/day1/img1.jpg">
then a thumbnail will be generated at

This func uses the imagemagick's shell command “convert” and
“identify”, and assumes that both's path on the disk are set in the
global vars “convert” and “identify”.'''
# outline:
# • Read in the file.
# • Get the img paths from inline images tags, accumulate them
into a list.
# • For each image, find its dimension w and h.
# • Generate the thumbnail image on disk.

# Generate a list of image paths.
for im in filter(lambda x : (not x.startswith('http')) and (not
x.endswith('icon_sum.gif')), getInlineImg(dPath + '/' + fName)):
imgPaths.append (linkFullPath(dPath, im))

# Change the image path to the full sized image, if it exists.
# That is, if image ends in -s.jpg, find one without the '-s'.
for myPath in imgPaths:
(dirName, fileName) = os.path.split(myPath)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
p2=os.path.join(dirName,fileBaseName[0:-2]) + fileExtension
if os.path.exists(p2): p=p2

# find out each images's width & height
# Each element in imgData has the form [image full path, [width,
for imp in imgPaths2:
# DSCN2699m-s.JPG JPEG 307x230+0+0 DirectClass 8-bit 51.7k 0.0u
print "Identifying:", imp
imgInfo=subprocess.Popen([identify, imp],
if int(width)*int(height) > minArea: imgData.append( [imp,
[int(width), int(height)]])

##print '<a href="' + fName + '">'

# create the scaled image files in thumbnail dir. The dir structure
is replicated.
for imp in imgData:
print "Thumbnailing:", imp
thumbnailRelativePath = oriImgFullPath[ len(rPath) + 1:]
thumbnailFullPath = tbPath + '/' + thumbnailRelativePath
print 'r',thumbnailRelativePath
print 'f',thumbnailFullPath
#print '<img src="' + thumbnailRelativePath + '" alt="">'

# make dirs to the thumbnail dir
(dirName, fileName) = os.path.split(thumbnailFullPath)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
print "Creating thumbnail:", thumbnailFullPath

# create thumbnail
subprocess.Popen([convert, '-scale', str(round(sf*100,2)) +
'%', oriImgFullPath, thumbnailFullPath] )

#print '</a>'

# main

def dirHandler(dummy, curdir, filess):
if minLevel <= filessLevel <= maxLevel:
for child in filess:
# if 'act1.html' == child and os.path.isfile(curdir+'/'+child):
if '.html' == os.path.splitext(child)[1] and
print "processing:", curdir+'/'+child

buildThumbnails(curdir,child,thumbnailDir,rootDir, thumbnailSizeArea)
while inPath[-1] == '/': inPath = inPath[0:-1] # get rid of trailing
os.path.walk(inPath, dirHandler, 'dummy')

Apr 19 '06 #1
1 3153
The Python code is archived at:


Xah Lee wrote:
The following is a program to generate thumbnail images for a website.
Useful, if you want to do that.

It is used to generate the thumbnails for my “Banners, Damsels, and
Mores” project gallery. (
http://xahlee.org/Periodic_dosage_dir/lanci/lanci.html )

Comments and versions in other lang welcome.

Apr 19 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Filippo Giarratano | last post by:
Hi -- I'm trying to figure out how to make a photo thumbnail gallery page using CSS and no tables that (1) has a caption below each image and (2) is centered -- so that as browser width changes the...
by: Max Quordlepleen | last post by:
Apologies for the crossposting, I wasn't sure which of these groups to ask this in. I have been lurking in these groups for a week or so, trying to glean what I need to design a simple, clean...
by: Chris Dewin | last post by:
Hi. I run a website for my band, and the other guys want an image gallery. I'm thinking it would be nice and easy, if we could just upload a jpg into a dir called "gallery/". When the client...
by: barb | last post by:
So that the world at large benefits from our efforts, here is one fully documented way to use Windows Irfanview freeware to create thumbnail web galleries (http://www.irfanview.com). STEP 1:...
by: Jane | last post by:
Hi, I need some help (php rookie) to build a thumbnail page using php. I'v a mysql database containing links to the original image files. No thumbnails created so far. It would be nice when...
by: RB | last post by:
Hi there, I'm having a problem with an ASP.NET/VB.NET Control I am writing. The control is a simple gallery control, which shows a set of thumbnails (using a DataList), and a main image of the...
by: mishrarajesh44 | last post by:
hii all Truly telling i hav got this code from net & i am finding error while running the code below.. code:- <?php $idir = "photo/"; // Path To Images Directory $tdir =...
by: Gary Hasler | last post by:
Does anyone have any suggestions on generating GUID (Globally Unique Identifier) tags with php? They would need to be in the format 4402bd8a-cd51-40ea-99d7-b510e89e344b Specifically this is for...
by: kirstenkirsche | last post by:
Hi guys.... i know this question has been asked already and I found a few answers but it would be soo great if anyone could help me with this script, which just browses images on a webpage in an...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: lllomh | last post by:
How does React native implement an English player?
by: Mushico | last post by:
How to calculate date of retirement from date of birth

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.