Voting

: five minus two?
(Example: nine)

The Note You're Voting On

swizec at swizec dot com
16 years ago
Wrote a function for sanitising user uploaded images. It saves the native image in size roughly 800x600 so it still fits on most screens when opened, makes a desired size thumbnail and turns all images into high quality jpegs for smaller bandwidth use.

Thumbnails are made in a similar way a designer would make them in photoshop, first resize the most troublesome dimension to desired size, then crop the rest out so the image retains proportions and most of it ends up in the thumbnail.

<?php

// $image is $_FILES[ <image name> ]
// $imageId is the id used in a database or wherever for this image
// $thumbWidth and $thumbHeight are desired dimensions for the thumbnail
function processImage( $image, $imageId, $thumbWidth, $thumbHeight )
{
$type = $image[ 'type' ];
$galleryPath = 'images/collection/';

if (
strpos( $type, 'image/' ) === FALSE )
{
// not an image
return FALSE;
}
$type = str_replace( 'image/', '', $type );
$createFunc = 'imagecreatefrom' . $type;

$im = $createFunc( $image[ 'tmp_name' ] );

$size = getimagesize( $image[ 'tmp_name' ] );

$w = $size[ 0 ];
$h = $size[ 1 ];
if (
$w > 800 || $h > 600 )
{
// we make sure the image isn't too huge
if ( $w > 800 )
{
$nw = 800;
$nh = ceil( $nw*($h/$w) );
}elseif(
$h > 600 )
{
$nh = 600;
$nw = ceil( $nh*($w/$h) );
}

$im2 = imagecreatetruecolor( $nw, $nh );
imagecopyresampled( $im2, $im, 0, 0, 0, 0, $nw, $nh, $w, $h );
imagedestroy( $im );

$im = $im2;
$w = $nw;
$h = $nh;
}

// create thumbnail
$tw = $thumbWidth;
$th = $thumbHeight;
$imT = imagecreatetruecolor( $tw, $th );

if (
$tw/$th > $th/$tw )
{
// wider
$tmph = $h*($tw/$w);
$temp = imagecreatetruecolor( $tw, $tmph );
imagecopyresampled( $temp, $im, 0, 0, 0, 0, $tw, $tmph, $w, $h ); // resize to width
imagecopyresampled( $imT, $temp, 0, 0, 0, $tmph/2-$th/2, $tw, $th, $tw, $th ); // crop
imagedestroy( $temp );
}else
{
// taller
$tmpw = $w*($th/$h );
$imT = imagecreatetruecolor( $tmpw, $th );
imagecopyresampled( $imT, $im, 0, 0, 0, 0, $tmpw, $h, $w, $h ); // resize to height
imagecopyresampled( $imT, $temp, 0, 0, $tmpw/2-$tw/2, 0, $tw, $th, $tw, $th ); // crop
imagedestroy( $temp );
}

// save the image
imagejpeg( $im, $galleryPath . $imgid . '.jpg', 100 );
imagejpeg( $imT, $galleryPath . $imgid . '_thumb.jpg', 100 );
}

?>

<< Back to user notes page

To Top