473,722 Members | 2,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
thumbnailSizeAr ea = 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(fi le_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.gro up(1).encode('u tf-8') )
return linx

def linkFullPath(di r,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('h ttp')) and (not
x.endswith('ico n_sum.gif')), getInlineImg(dP ath + '/' + fName)):
imgPaths.append (linkFullPath(d Path, 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(m yPath)
(fileBaseName, fileExtension)= os.path.splitex t(fileName)
if(re.search(r'-s$',fileBaseNam e,re.U)):
p2=os.path.join (dirName,fileBa seName[0:-2]) + fileExtension
if os.path.exists( p2): p=p2
imgPaths2.appen d(p)

# 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 "Identifyin g:", imp
imgInfo=subproc ess.Popen([identify, imp],
stdout=subproce ss.PIPE).commun icate()[0]
(width,height)= (imgInfo.split( )[2]).split('x')
height=height.s plit('+')[0]
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
oriImgFullPath= imp[0]
thumbnailRelati vePath = oriImgFullPath[ len(rPath) + 1:]
thumbnailFullPa th = tbPath + '/' + thumbnailRelati vePath
print 'r',thumbnailRe lativePath
print 'f',thumbnailFu llPath
sf=scaleFactor( areaA,(imp[1][0],imp[1][1]))
#print '<img src="' + thumbnailRelati vePath + '" alt="">'

# make dirs to the thumbnail dir
(dirName, fileName) = os.path.split(t humbnailFullPat h)
(fileBaseName, fileExtension)= os.path.splitex t(fileName)
print "Creating thumbnail:", thumbnailFullPa th
os.makedirs(dir Name,0775)
except(OSError) :

# create thumbnail
subprocess.Pope n([convert, '-scale', str(round(sf*10 0,2)) +
'%', oriImgFullPath, thumbnailFullPa th] )

#print '</a>'

############### ##
# main

def dirHandler(dumm y, curdir, filess):
curdirLevel=len (re.split('/',curdir))-len(re.split('/',inPath))
filessLevel=cur dirLevel+1
if minLevel <= filessLevel <= maxLevel:
for child in filess:
# if 'act1.html' == child and os.path.isfile( curdir+'/'+child):
if '.html' == os.path.splitex t(child)[1] and
os.path.isfile( curdir+'/'+child):
print "processing :", curdir+'/'+child

buildThumbnails (curdir,child,t humbnailDir,roo tDir,thumbnailS izeArea)
while inPath[-1] == '/': inPath = inPath[0:-1] # get rid of trailing
os.path.walk(in Path, dirHandler, 'dummy')

Apr 19 '06 #1
1 3231
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 images consistently reconstitute themselves as centered rows with the maximum number of images on each row. I've made a test page at http://www.americanstate.org/test/gal01/ that illustrates what I'm aiming for and how close I've gotten. I've...
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 set of pages that get the w3c tick for XHTML 1.0 Strict, and CSS2. So far, I have succeeded, thanks to the great information in these groups. Now, however, I'm having trouble. A few days ago, I read a thread that dealt with this issue of...
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 clicks the "gallery" link, a cgi script could search the gallery/ dir, and create thumbnails of any jpeg images that don't already have a thumbnail associated with them. The script could then generate a page of clickable thumbnails. A few questions:
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: Start with original thumbnails & two empty sub directories STEP 2: Create smaller versions of the originals for one sub directory STEP 3: Create thumbnail version of the originals the other sub directory STEP 4: Create an index.html pointing to the...
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 the thumbnail contains a link to the original file :-) Jane
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 selected thumbnail. It also has "Add Picture" and "Delete Picture" buttons. "Add Picture" will add a new picture, while "Delete Picture" will remove the currently selected picture. These are both ASP:ImageButtons, with the functionality...
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 = "photo/thumbs/"; // Path To Thumbnails Directory $twidth = "125"; // Maximum Width For Thumbnail Images
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 adding accessibility for the PicLens browser add-on (which uses an .rss file) to some of our photo gallery pages. It seems to require each thumbnail have an identical GUID tag in both the html and the rss file.
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 image folder on a server. the script so far is working (a friend gave it to me): http://dev.perfectday.gb.com/tom/chiaraweb/photo.php the number on the images are the filenames. I want to order the images by filenames. the only thing is the...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.