[thelist] PHP image resize
brian cummiskey
brian at hondaswap.com
Wed Sep 1 08:00:27 CDT 2004
ben morrison wrote:
> Im just learning PHP so this may be really obvious, I have built a
> simple file upload and am now trying to create a thumbnail on the fly
> which is scaled proportionally.
>
> On my server PHP 4.1.2 GD 1.6 Globals are set to ON.
>
> constantly getting parse errors, this is my current code:
>
> $first=ImageCreateFromJPEG("images/".$_FILES['MyFile']['name']) or
> die("couldn't open image");
> define(MAX_WIDTH, 150);
> define(MAX_HEIGHT, 150);
> $width = imagesx($first);
> $height = imagesy($first);
>
> $scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height);
>
> $new_width = floor($scale*$width);
> $new_height = floor($scale*$height);
>
> $second=ImageCreate($new_width, $new_height) or die("couldn't create
> image");
>
> ImageCopyResized($second,$first,0,0,0,0,$new_width,$new_height,$width,$h
> eight) or die("coudln't resize image");
>
> ImageJPEG($second,$thumbname) or die("couldn't save image");
>
> the original image is working, $thumbname exists, ive just shown the
> code thats causing the error.
>
> Ive tried so many different codes from tutorial sites and most of
> them don't seem to work - I presume this is due to versions and
> globals etc?
>
> ben
here's a set of scripts I use. Some of these functions Require GD 2.0,
so i would really recommend upgrading your server to it.
First, the form-
<form action="upload.php" enctype="multipart/form-data" method="post">
<!-- the enc-type is very important. -->
<input name="MAX_FILE_SIZE" type="hidden" value="1000000">
<input maxlength="128" name="image" type="file" accept="image/jpeg,
image/jpg">
<input name="submit" type="submit" value="Upload!">
</form>
then, the upload functions on upload.php:
#############################################################################################
$IMG_ORG_HEIGHT = "*"; #Width of original image stored on server
$IMG_ORG_WIDTH = "*"; #Height of original image stored on server
#set to "*" to prevent resizing on the dimension
#you will not lose X to Y ratio
$IMG_HEIGHT = "60"; # Accepted height of resized image
$IMG_WIDTH = "80"; # Accepted width of resized image
# read about "*" above
$IMG_ROOT = "./images"; # Relative path to folder where uploaded
images will be stored; no ending slash!
# Remeber to set proper attributes to that
folder. 777 will work :)
$use_imagecreatetruecolor = true; // these flags enble
ImageCreateTrueColor(); ImageCopyResampled(); GD 1.6 doesn't have these.
$use_imagecopyresampled = true;
$JPG_QUALITY = 80; // output jpeg quality
#############################################################################################
//error_reporting(53); // dont need ur warnings!
if(!$HTTP_POST_FILES ["image"]["tmp_name"] || $HTTP_POST_FILES
["image"]["tmp_name"] =="none") die("Your images may be no larger than
100KB in size. Please make it smaller, and try again.");
if( ! $f_org =
resizer_main("image","",$IMG_ORG_WIDTH,$IMG_ORG_HEIGHT))die("<br><font
color=\"red\"><b>No Image received...</b></font><br>");
if( ! $f_res =
resizer_main("image","res_",$IMG_WIDTH,$IMG_HEIGHT))die("<br><font
color=\"red\"><b>Not resized :( </b></font><br>");
$sz_org =getimagesize( "$IMG_ROOT/$f_org" );
$sz_res =getimagesize( "$IMG_ROOT/$f_res" );
$fs_org= filesize("$IMG_ROOT/$f_org" );
$fs_res= filesize("$IMG_ROOT/$f_res" );
$html =<<< EHTML
<table width="100%" border="0" align="center" cellpadding="0"
cellspacing="0" class="regtext">
<tr>
<td colspan="2" class="heading2" align="center">Thanks for your
submission!</td>
</tr>
<tr>
<td colspan="2">Your full-sized image, as well as the below
thumbnail have been successfully created and added to your album. You
will find the link to each picture by viewing your album.</td>
</tr>
<tr>
<td colspan="2"><br /><br /><a class="regtext"
href="upload.php">Click here to return to <b>Upload Another</b>.</a></td>
</tr>
<tr>
<td colspan="2" align="center"><b>Resized image:</b></td>
</tr>
<tr>
<td colspan="2">
<div align="center"><img src="$IMG_ROOT/$f_res" $sz_res[3]></div>
</td>
</tr>
<tr>
<td colspan="2"><hr></td>
</tr>
<tr>
<td colspan="2"><b>Original image:</b></td>
</tr>
<tr>
<td colspan="2"><b>Share this image: $IMG_ROOT/$f_org</b></td>
</tr>
<tr>
<td colspan="2">
<br />
<br />
<div align="center"><img src="$IMG_ROOT/$f_org" $sz_org[3]></div>
</td>
</tr>
</table>
</tr>
</td>
<td width="15%" bgcolor="#ffffff" height="100%">
</td>
</tr>
EHTML;
echo $html;
include('../footer.php');
//do SQL to insert into image DB if you have a DB for keeping track of
who uploaded what/ albums/ etc
$dateadded = date("Y-m-d");
$user_id = $myclass->member['id'];
$sql = "INSERT INTO images (id, thumbnail_url, photo_url,
thumbnail_size, photo_size, album_id, user_id, dateadded, photo_dim,
thumbnail_dim) VALUES (NULL, '$f_res', '$f_org', '$fs_res', '$fs_org',
'$album_id', '$user_id', '$dateadded', '$sz_res[3]', '$sz_org[3]')";
if(! $result = mysql_query($sql, $db))
die(mysql_error());
else
echo "<tr><td colspan=\"2\"><i>(image and thumb successfully
uploaded and inserted into the DB and into album.)</i></td></tr>";
echo "</table>";
#############################################################################################
function resizer_main($image, $dest_file_prefix,$w, $h){
//image_name = uploaded image. Name or your file field in your form.
//w,h - width and height to fit image in
global $use_imagecreatetruecolor, $use_imagecopyresampled, $IMG_ROOT,
$JPG_QUALITY, $HTTP_POST_FILES;
$image_name = $HTTP_POST_FILES [$image]["name"];
$image = $HTTP_POST_FILES [$image]["tmp_name"];
if(trim($image) == "" || trim($image) =="none") return false;
$arr_img = image_from_upload($image);
if( $arr_img["w"] != $w && $arr_img["h"] != $h){
$wh = get_sizes($arr_img["w"], $arr_img["h"], $w, $h);
$img_res = img_get_resized(
$arr_img["img"],
$arr_img["w"], $arr_img["h"],
$wh["w"], $wh["h"],
$use_imagecreatetruecolor,
$use_imagecopyresampled);
} else {
//wow it is exactly like needed!!!
$img_res = $arr_img["img"];
}
$file_name = make_filename($image_name, $dest_file_prefix);
ImageJPEG($img_res,"$IMG_ROOT/$dest_file_prefix$file_name",
$JPG_QUALITY);
return "$dest_file_prefix$file_name";
}
function image_from_upload($uploaded_file){
$img_sz = getimagesize( $uploaded_file ); ## returns array with
some properties like dimensions and type;
####### Now create original image from uploaded file. Be carefull!
GIF is often not supported, as far as I remember from GD 1.6
switch( $img_sz[2] ){
case 1:
$img_type = "GIF";
//$img = ImageCreateFromGif($uploaded_file);
die("<br><font color=\"red\"><b>Sorry, Only JPG's are
supported.</b></font><br>");
break;
case 2:
$img = ImageCreateFromJpeg($uploaded_file);
$img_type = "JPG";
break;
case 3:
$img = ImageCreateFromPng($uploaded_file);
$img_type = "PNG";
break;
case 4:
$img_type = "SWF";
//$img = ImageCreateFromSwf($uploaded_file);
die("<br><font color=\"red\"><b>Sorry, Only JPG's are
supported.</b></font><br>");
break;
default: die("<br><font color=\"red\"><b>Sorry, Only JPG's are
supported.</b></font><br>");
}//case
return array("img"=>$img, "w"=>$img_sz[0], "h"=>$img_sz[1],
"type"=>$img_sz[2], "html"=>$img_sz[3]);
}
function get_sizes($src_w, $src_h, $dst_w,$dst_h ){
//src_w ,src_h-- start width and height
//dst_w ,dst_h-- end width and height
//return array w=>new width h=>new height mlt => multiplier
//the function tries to shrink or enalrge src_w,h in such a way to
best fit them into dst_w,h
//keeping x to y ratio unchanged
//dst_w or/and dst_h can be "*" in this means that we dont care
about that dimension
//for example if dst_w="*" then we will try to resize by height not
caring about width
//(but resizing width in such a way to keep the xy ratio)
//if both = "*" we dont resize at all.
#### Calculate multipliers
$mlt_w = $dst_w / $src_w;
$mlt_h = $dst_h / $src_h;
$mlt = $mlt_w < $mlt_h ? $mlt_w:$mlt_h;
if($dst_w == "*") $mlt = $mlt_h;
if($dst_h == "*") $mlt = $mlt_w;
if($dst_w == "*" && $dst_h == "*") $mlt=1;
#### Calculate new dimensions
$img_new_w = round($src_w * $mlt);
$img_new_h = round($src_h * $mlt);
return array("w" => $img_new_w, "h" => $img_new_h, "mlt_w"=>$mlt_w,
"mlt_h"=>$mlt_h, "mlt"=>$mlt);
}
function
img_get_resized($img_original,$img_w,$img_h,$img_new_w,$img_new_h,$use_imagecreatetruecolor=false,
$use_imagecopyresampled=false){
//$img_original, -- image to be resized
//$img_w, -- its width
//$img_h, -- its height
//$img_new_w, -- resized width
//$img_new_h -- height
//$use_imagecreatetruecolor, $use_imagecopyresampled allow use of
these function
//if they exist on the server
if( $use_imagecreatetruecolor &&
function_exists("imagecreatetruecolor")){
// echo("Using ImageCreateTruecolor (better quality)<br>");
$img_resized = imagecreatetruecolor($img_new_w,$img_new_h) or
die("<br><font color=\"red\"><b>Failed to create destination
image.</b></font><br>");
} else {
// echo("Using ImageCreate (usual quality)<br>");
$img_resized = imagecreate($img_new_w,$img_new_h) or
die("<br><font color=\"red\"><b>Failed to create destination
image.</b></font><br>");
}
if($use_imagecopyresampled && function_exists("imagecopyresampled")){
// echo("Using ImageCopyResampled (better quality)<br>");
imagecopyresampled($img_resized, $img_original, 0, 0, 0,
0,$img_new_w, $img_new_h, $img_w,$img_h) or die("<br><font
color=\"red\"><b>Failed to resize @ ImageCopyResampled()</b></font><br>");
}else{
// echo("Using ImageCopyResized (usual quality)<br>");
imagecopyresized($img_resized, $img_original, 0, 0, 0,
0,$img_new_w, $img_new_h, $img_w,$img_h) or die("<br><font
color=\"red\"><b>Failed to resize @ ImageCopyResized()</b></font><br>");
}
return $img_resized;
}
function make_filename($image_name){
## creates unique name, here I assume that it will never happen that
in same second
## two files with same name on user's site will be uploaded. However
you can use your
## ways to generate unique name. Function unqueid() for example.
//$file_name = time()."_$image_name";
$file_name = uniqid('s').'.jpg';
#kick the original extension
$pos = strrpos($file_name, '.');
//personally I think jpeg rulez so I hardoce its extension here
$file_name = substr($file_name, 0,$pos).".jpg";
return $file_name;
}
?>
More information about the thelist
mailing list