Determining JPG Image Size / Websites
From: Peter Campbell (pc_at_acs.co.nz)
Date: 11/30/04
- Next message: bob decker: "wishkit"
- Previous message: Gerald W. Lester: "Re: Problems with TCL timers"
- Next in thread: Michael Schlenker: "Re: Determining JPG Image Size / Websites"
- Reply: Michael Schlenker: "Re: Determining JPG Image Size / Websites"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 30 Nov 2004 15:15:32 +1300
I am posting some code I've just written that determines the size of an
image then scales it automatically (in HTML) to a requested size.
The procedure image_dimensions { filename} returns a list {height width} for
the dimensions of the specified JPG file.
I haven't supported any other file format here.
proc image_value { data } {
set n 0
while {[string length $data]} {
scan [string range $data 0 0] %c int
set n [expr {$n * 256 + $int}]
set data [string range $data 1 end]
}
return $n
}
proc image_hexvalue { data } {
set value [image_value $data]
return [format %X $value]
}
proc image_dimensions { image_file } {
# open file, determine properties of JPG file then return {height width}
set fid [open $image_file]
fconfigure $fid -translation binary
# read first 2 digits
set data [read $fid 2]
if {[image_hexvalue $data] != "FFD8"} {
close $fid
# not a JPG file
return {0 0}
}
while {![eof $fid]} {
set header [read $fid 4]
set type [image_hexvalue [string range $header 1 1]]
set length [image_value [string range $header 2 3]]
if {$type == "DA"} { break }
set extra [read $fid [expr {$length - 2}]]
if {$type == "C0"} {
set height [image_value [string range $extra 1 2]]
set width [image_value [string range $extra 3 4]]
close $fid
return [list $height $width]
}
}
close $fid
return {0 0}
}
# The following code is part of my website application (cgi) that displays
an image.
# setup(photo_size) contains either 0 for no scaling or a maximum pixel
width, eg: 400.0
# note: include a ".0" in the photo_size value to help Tcl with the maths
(rounding issues)
# scale image?
if {$setup(photo_size)} {
# determine size of image, if wider (or higher) than say 500 pixels then
scale to that maximum
foreach {height width} [image_dimensions $photo_file] {}
if {$height > $width} {
set width [expr {int($width * ($setup(photo_size) / $height))}]
set height $setup(photo_size)
} else {
set height [expr {int($height * ($setup(photo_size) / $width))}]
set width $setup(photo_size)
}
puts "<img src=\"/$image_file\" width=\"$width\" height=\"$height\">"
} else {
puts "<img src=\"/$image_file\">"
}
I hope if anybody else needs something like this that it helps.
Cheers
- Next message: bob decker: "wishkit"
- Previous message: Gerald W. Lester: "Re: Problems with TCL timers"
- Next in thread: Michael Schlenker: "Re: Determining JPG Image Size / Websites"
- Reply: Michael Schlenker: "Re: Determining JPG Image Size / Websites"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|