473,398 Members | 2,389 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 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.

Xah
xa*@xahlee.org
http://xahlee.org/
# -*- 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
images.

# 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
['xx.jpg','../image.png']'''
FF = open(file_full_path,'rb')
txt_segs = re.split( r'src', unicode(FF.read(),'utf-8'))
txt_segs.pop(0)
FF.close()
linx=[]
for linkBlock in txt_segs:
matchResult = re.search(ur'\s*=\s*\"([^\"]+)\"',
linkBlock,re.U)
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
it.)
and trip.html contains <img ="Beijin/day1/img1.jpg">
then a thumbnail will be generated at
'/Users/mary/Public/thumbs/pictures/Beijin/day1/img1.jpg'

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.
imgPaths=[]
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'.
imgPaths2=[]
for myPath in imgPaths:
p=myPath
(dirName, fileName) = os.path.split(myPath)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
if(re.search(r'-s$',fileBaseName,re.U)):
p2=os.path.join(dirName,fileBaseName[0:-2]) + fileExtension
if os.path.exists(p2): p=p2
imgPaths2.append(p)

# find out each images's width & height
# Each element in imgData has the form [image full path, [width,
height]]
imgData=[]
for imp in imgPaths2:
# DSCN2699m-s.JPG JPEG 307x230+0+0 DirectClass 8-bit 51.7k 0.0u
0:01
print "Identifying:", imp
imgInfo=subprocess.Popen([identify, imp],
stdout=subprocess.PIPE).communicate()[0]
(width,height)=(imgInfo.split()[2]).split('x')
height=height.split('+')[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]
thumbnailRelativePath = oriImgFullPath[ len(rPath) + 1:]
thumbnailFullPath = tbPath + '/' + thumbnailRelativePath
print 'r',thumbnailRelativePath
print 'f',thumbnailFullPath
sf=scaleFactor(areaA,(imp[1][0],imp[1][1]))
#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
try:
os.makedirs(dirName,0775)
except(OSError):
pass

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

#print '</a>'

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

def dirHandler(dummy, curdir, filess):
curdirLevel=len(re.split('/',curdir))-len(re.split('/',inPath))
filessLevel=curdirLevel+1
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
os.path.isfile(curdir+'/'+child):
print "processing:", curdir+'/'+child

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

Apr 19 '06 #1
1 3208
The Python code is archived at:
http://xahlee.org/perl-python/tn_gen.html

Xah
xa*@xahlee.org
http://xahlee.org/

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

14
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...
54
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...
8
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...
8
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:...
11
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...
2
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...
7
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 =...
2
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...
2
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
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,...
0
jinu1996
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
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,...
0
isladogs
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...

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.