Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

thumbnail with gd

Function that makes a thumbnail of a imagen and keeps it's proportion. $the fourth parameter ($fill) makes that, if the image is smaller than the size we want, the function expands it. It shows the image directly to the browser, but can be easily modificed to save the imagen on a directory.

Funcion que hace una miniatura de una imagen manteniendo su proporcion individual. El cuarto parametro ($fill) hace que, si la imagen es mas pequeña del tamaño deseado, la expande. Muestra la imagen directamente en el navegador, pero puede ser facilmente modificada para guardarla en un directorio.

<?php
function thumb($img, $w, $h, $fill = true) {
	if (!extension_loaded('gd') && !extension_loaded('gd2')) {
		trigger_error("No dispones de la libreria GD para generar la imagen.", E_USER_WARNING);
		return false;
	}

	$imgInfo = getimagesize($img);
	switch ($imgInfo[2]) {
		case 1: $im = imagecreatefromgif($img); break;
		case 2: $im = imagecreatefromjpeg($img);  break;
		case 3: $im = imagecreatefrompng($img); break;
		default:  trigger_error('Tipo de imagen no reconocido.', E_USER_WARNING);  break;
	}

	if ($imgInfo[0] <= $w && $imgInfo[1] <= $h && !$fill) {
		$nHeight = $imgInfo[1];
		$nWidth = $imgInfo[0];
	}else{
		if ($w/$imgInfo[0] < $h/$imgInfo[1]) {
			$nWidth = $w;
			$nHeight = $imgInfo[1]*($w/$imgInfo[0]);
		}else{
			$nWidth = $imgInfo[0]*($h/$imgInfo[1]);
			$nHeight = $h;
		}
	}
  
	$nWidth = round($nWidth);
	$nHeight = round($nHeight);

	$newImg = imagecreatetruecolor($nWidth, $nHeight);

	imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);

	header("Content-type: ". $imgInfo['mime']);

	switch ($imgInfo[2]) {
		case 1: imagegif($newImg); break;
		case 2: imagejpeg($newImg);  break;
		case 3: imagepng($newImg); break;
		default:  trigger_error('Imposible mostrar la imagen.', E_USER_WARNING);  break;
	}
  
	imagedestroy($newImg);
}
?>


Usage/Uso:
thumb("image.png", 200, 200);

Ruby Client for Amazon Alexa Site Thumbnail (AST) Service

It's scrappy, but it does the job.

require 'cgi'
require 'openssl'
require 'base64'
require 'open-uri'

access_id = 'YOUR_ACCESS_ID'
secret_id = 'YOUR_SECRET_ID'

source_url = ARGV.first

timestamp = Time.now.strftime("%Y-%m-%dT%H:%M:%SZ")
sig = Base64.encode64(OpenSSL::HMAC::digest(OpenSSL::Digest::Digest.new('SHA1'), secret_id, 'Thumbnail' + timestamp)).strip

url = "http://ast.amazonaws.com/Xino?Action=Thumbnail&AWSAccessKeyId=" + access_id
url << "&Signature=" + CGI.escape(sig)
url << "&Timestamp=" + CGI.escape(timestamp)
url << "&Url=" +  source_url

begin
  doc = open(url).read
rescue
  puts "Could not access AWS"
  exit
end

m = doc.match(/\<aws:thumbnail[^\>]+exists=\"true\"\>(.+?)\<\//i)

if m && m[1]
  thumb_url = m[1]
  thumb_url.gsub!(/\&amp;/, '&')
  File.open("#{source_url}.jpg", "w") { |f| f.write open(thumb_url).read }
  puts "Saved to #{source_url}.jpg"
elsif m && m.match(/exists=\"false\"/)
  puts "No thumbnail for #{source_url}"
else
  puts "Error"
end

PyS60 - Gallery Thumbnail Ver. 2

// Versione riveduta e corretta di Gallery Thumbnail postata da korakot ^_^

import appuifw
import e32
import graphics
import key_codes
import os

class FlickrS60Error(Exception): pass

class FlickrS60Thumb:

	def __init__(self, path):

		self.path = unicode(path)
		self.listFile = []
		self.ldivx = 0
		self.ldivy = 0
		self.lock = e32.Ao_lock()
		self.canvas = None
		self.img = graphics.Image.new((176, 144))
		self.img_tmp = graphics.Image.new((42, 36))
		self.x, self.y = 0, 0
		self.p = 0
		self.pages = 0
		self.currpages = 0
		self.mpath = 0

	def OnRun(self):

		appuifw.app.exit_key_handler = self.lock.signal
	
		self._createList()
		
		self.canvas = appuifw.Canvas(redraw_callback=self.OnUpdate)
		appuifw.app.body = self.canvas

		self.canvas.bind(key_codes.EKeyRightArrow, lambda: self.move(1, 0))
		self.canvas.bind(key_codes.EKeyLeftArrow, lambda: self.move(-1, 0))
		self.canvas.bind(key_codes.EKeyUpArrow, lambda: self.move(0, -1))
		self.canvas.bind(key_codes.EKeyDownArrow, lambda: self.move(0, 1))
		self.canvas.bind(key_codes.EKeySelect, self.IMG)

		self._drawIMG()
		
		self.lock.wait()

	def OnUpdate(self, rect):

		self.canvas.blit(self.img)
		self.canvas.rectangle([(self.p+(42*self.x), 36*self.y), (self.p+(42*self.x)+42, (36*self.y)+36)], width=2, outline=0x123456)

	def move(self, x, y):

		self.x = (self.x+x)%4
		self.y = (self.y+y)

		if x == 1: self.p = (self.p+2)%8
		if x == -1: self.p = (self.p-2)%8

		if self.y == 4:
			if self.currpages < self.pages-1:
				self.y = 0
				self.currpages += 1
				self._drawIMG(start=self.currpages)
			else:
				self.y = 3
			
		if self.y == -1:
			if self.currpages > 0:
				self.y = 3
				self.currpages -= 1
				self._drawIMG(start=self.currpages)
			else:
				self.y = 0
	
		self.mpath = (4*self.y + self.x)+(16*self.currpages)
		
		self.OnUpdate(None)
	
	def IMG(self):

		try:
			m = self.listFile[self.mpath].replace('_PalbTN\\', '')
			appuifw.Content_handler().open(m)
		except:
			pass
		
	def _drawIMG(self, start=0):

		self.img.clear(0xffffff)
		z = 0
		
		for id in range(start*16, (start+1)*16):
			j, i = divmod(id-(start*16), 4)
			try:
				self.img_tmp.load(self.listFile[id])
				self.img.blit(self.img_tmp, target=(z+(42*i)+(z+1), 36*j))
				z = (z+1)%4
			except:
				break

		self.OnUpdate(None)

	def _createList(self):

		try:
			for id in os.listdir(self.path):
				self.listFile.append(self.path + id)

			self.ldivx, self.ldivy = divmod(len(self.listFile), 16)

			self.pages = self.ldivx
			if self.ldivy <> 0: self.pages += 1
		except:
			raise FlickrS60Error('Errore nella creazione della lista.')

if __name__ == '__main__':

	FlickrS60Thumb('E:\\Images\\_PalbTN\\').OnRun()

Gallery thumbnails

from appuifw import *
from graphics import Image
from key_codes import *
#from status import *
#from e32db import format_time
import os, e32

dir = u'C:\\Nokia\\Images\\_PAlbTN\\'
os.chdir(dir)
fs = os.listdir('')
mtime = os.path.getmtime
# newest first
fs.sort(lambda a,b: cmp(mtime(b), mtime(a)))

app.body = canvas = Canvas()
# show just 16 images
for k in range(min(16, len(fs))):
    j, i = divmod(k, 4)
    im = Image.open(dir + fs[k])
    canvas.blit(im, target=(2+44*i, 2+34*j))
canvas.rectangle([(0,0), (43,33)], 0xff, width=2)  # selected

x, y, k = 0, 0, 0
def move(dx, dy):
    global x, y, k
    canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xffffff, width=2)  
    k = 4*y + x + 4*dy + dx
    y, x = divmod(k, 4)
    canvas.rectangle([(44*x,34*y), (44*x+43,34*y+33)], 0xff, width=2)
    if 0 <= k < len(fs):
        app.title = u''+fs[k]
        #status_on(format_time(mtime(fs[k])))

# move cursor and open image
canvas.bind(EKeyUpArrow,   lambda: move(0,-1))
canvas.bind(EKeyDownArrow, lambda: move(0,1))
canvas.bind(EKeyLeftArrow, lambda: move(-1,0))
canvas.bind(EKeyRightArrow,lambda: move(1,0))
canvas.bind(EKeySelect,    lambda: Content_handler().open(dir[:-8]+fs[k]))

# standard code for non-loop app
lock = e32.Ao_lock()
app.exit_key_handler = lock.signal
lock.wait()

[Multiplatform] Thumbnails of all (gif, jpeg, and png) images in a directory

Thanks Dorrin for your Thumbnailer!
I hope you don't mind, but I did some minor fixes and made your script more portable. Now, you can use it on Windows too.
By the way, as I revealed there is no dependency of "from mod_python import apache", so I removed it.

import os
import re
from PIL import Image

header = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Directory Listing</title></head>
<body>'''
images_per_row = 5
max_width,max_height = 150,150

path = os.path.dirname(__file__)
  
def thumbnail(filename):
  thumbsdir = os.path.join(path, ".thumbnails")
  thumbfile = os.path.join(thumbsdir, filename)
  if os.path.exists(thumbfile):
    return

  if not os.path.exists(thumbsdir):
    os.mkdir(thumbsdir);
    
  filepath = os.path.join(path, filename)
  image = Image.open(filepath)
  image.thumbnail((max_width, max_height), Image.ANTIALIAS)
  image.save(thumbfile)

def index(req):
  return_value = header

  dir_list = os.listdir(path)
  image_list = []

  search = re.compile("(.*\.[Jj][Pp][Ee]?[Gg]$)|(.*\.[Pp][Nn][Gg]$)|(.*\.[Gg][Ii][Ff]$)")

  image_count = 0
  for file in dir_list:
    if search.match(file):
      image_count += 1
      image_list.append(file)

  if image_count > 0:
    image_list.sort()
    num_rows = image_count / images_per_row

    image_num = 0
    return_value += '<table width="100%" border="0"><tr>\n'

    for image in image_list:
      thumbnail(image)
      image_num += 1
      return_value += '<td><a href="' + image + '"><img src=".thumbnails/' + image + '" alt="' + image + '"></a>'

      if image_num % images_per_row:
        return_value += '</td>\n'

      else:
        return_value += '</td></tr><tr>\n'

  return_value += "</table></body></html>"
  return return_value


Here is small test script.
It generates thumbnails with Dorrin's script, then grabs HTML output and writes it to index.html file, so you get nice index page.

import thumbnail
import os

html = thumbnail.index(0)

htmlfile = os.path.join(os.getcwd(), "index.html")
f = open(htmlfile, "w")
f.write(html);
f.close()
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS