Gd Thumbnail

lua-users home
wiki

The following code describes a small thumbnail resizer for jpeg/png/gif using lua-gd, usable for web galleries or similar applications - it can be used as command line program or library:

#!/usr/bin/env lua
-- gd thumbnail
-- Create a jpg thumbnail from gif/jpg/png image
-- (C) 2007 by Alex Kloss [http://www.it-rfc.de]
-- licensed under the terms of the LGPL2: http://www.fsf.org/licensing/licenses/lgpl.html

-- uses lua-gd: http://lua-gd.luaforge.net
require('gd')

-- thumbnail(imagein,imageout,maxsize) imageout and maxsize are optional
-- returns the output image name on success, nil on failure
function thumbnail(imagein,imageout,maxsize)
	-- sanitizing input options
	local maxsize = maxsize or 40
	local imageout = imageout or "t"..imagein
	-- loading input image
	local im = (imagein:match('%.jpe?g$') and gd.createFromJpeg(imagein) or
		imagein:match('%.png$') and gd.createFromPng(imagein) or
		imagein:match('%.gif$') and gd.createFromGif(imagein))
	-- getting the size right
	local x,y = im:sizeXY()
	local tx = y > x and x/y*maxsize or maxsize
	local ty = x > y and y/x*maxsize or maxsize
	-- creating the thumbnail
	local tn = gd.createTrueColor(tx,ty)
	gd.copyResampled(tn,im,0,0,0,0,tx,ty,x,y)
	if tn:jpeg(imageout,75) then return imageout
	else return nil end
end

-- command line if not called as library
if (arg ~= nil) then
	for n,i in ipairs(arg) do
		print(thumbnail(i) or "thumbnail creation failed")
	end
end
Vega++
RecentChanges · preferences
edit · history
Last edited May 23, 2013 1:04 pm GMT (diff)