In search of snippet

GD and GD2 are useful libraries for creating graphics on-the-fly. Discuss your PHP GD and GD2 scripts here.

Moderators: onion2k, General Moderators

Post Reply
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

In search of snippet

Post by jayshields »

Hi,

I have never used GD before, and I am wanting to code something but don't know where to start, so perhaps someone could direct me to a tutorial or a related (well commented) snippet.

I want to upload an image and if its width is above 400, resize it to 400 width and resize the height in proportion to it. Then, if the width is also above 200, do the same but with 200 width and save it seperately. Then ofcourse delete the original image.

Any help appreciated.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

look for the thumbnail generator in Code Snippets.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

I've just looked at it, but I don't understand it's usage.

All I want is a snippet to convert a file on my server to a different size and save it elsewhere. I can do the rest.
User avatar
Buddha443556
Forum Regular
Posts: 873
Joined: Fri Mar 19, 2004 1:51 pm

Post by Buddha443556 »

Maybe this will help. It's a work in progress ... matter of fact just added the comments just for you. :wink:

Code: Select all

$annwyn_resize_image_source = false;
$annwyn_resize_image_dest = false;

// Just in case user aborts.
function shutdown_func() {
	
   	global $annwyn_resize_image_source, $annwyn_resize_image_dest;
	if($annwyn_resize_image_source) {
		@imagedestroy($annwyn_resize_image_source);
	}
	if($annwyn_resize_image_dest) {
		@imagedestroy($annwyn_resize_image_dest);
	}
}

// $image - path to original image.
// $new_image - path to save new image,
// $new_width - should probably raname this max width. 
function annwyn_resize_image($image, $new_image, $new_width) {

  	global $annwyn_resize_image_source, $annwyn_resize_image_dest;

	$imagesize = getimagesize($image);

	if($imagesize === false) {
		return false;
	}
	
	register_shutdown_function("shutdown_func");
	
	switch($imagesize[2]) {
		case IMAGETYPE_JPEG:
			if(($annwyn_resize_image_source =
				@imagecreatefromjpeg($image)) === false) {

				return false;

			}
			break;
		case IMAGETYPE_PNG:
			if(($annwyn_resize_image_source = @imagecreatefrompng($image)) === false) {

				return false;

			}
			break;
		case IMAGETYPE_GIF:
			if(($annwyn_resize_image_source = @imagecreatefromgif($image)) === false) {

				return false;

			}
			break;
		default:
			return false;
			break;
	}
	
	// Don't enlarge but reduce proportionally.
	if($imagesize[0] < $new_width) {
		
		$new_width = $imagesize[0];
		$new_height = $imagesize[1];
		
	} else {

		$new_height = $new_width * ($imagesize[1] / $imagesize[0]);
		
	}
	
	// Use imagecreat() for GIF images.
	if($imagesize[2] == IMAGETYPE_GIF) {
		$annwyn_resize_image_dest = imagecreate($new_width, $new_height);
	} else {
		$annwyn_resize_image_dest = imagecreatetruecolor($new_width, $new_height);
	}

	// Save the alphablending of PNG images.
	if($imagesize[2] == IMAGETYPE_PNG) {
		imagealphablending($annwyn_resize_image_dest, false);
		imagesavealpha($annwyn_resize_image_dest, true);
	}

	// Save the transparency of GIF images.
	if($imagesize[2] == IMAGETYPE_GIF) {
		$colorTransparent = imagecolortransparent($annwyn_resize_image_source);
		imagepalettecopy($annwyn_resize_image_dest,$annwyn_resize_image_source);
		imagefill($annwyn_resize_image_dest,0,0,$colorTransparent);
		imagecolortransparent($annwyn_resize_image_dest, $colorTransparent);

	}

	imagecopyresampled(
		$annwyn_resize_image_dest, 
		$annwyn_resize_image_source, 
		0, 0, 0, 0, $new_width, $new_height, $imagesize[0], $imagesize[1]);

	// Output the same image type as the original.
	switch($imagesize[2]) {
		case IMAGETYPE_JPEG:
			imagejpeg($annwyn_resize_image_dest, $new_image);
			break;
		case IMAGETYPE_PNG:
			imagepng($annwyn_resize_image_dest, $new_image);
			break;
		case IMAGETYPE_GIF:
			imagegif($annwyn_resize_image_dest, $new_image);
			break;
		default:
			return false;
			break;
	}
	
	imagedestroy($annwyn_resize_image_source);
	$annwyn_resize_image_source = false;
	imagedestroy($annwyn_resize_image_dest);
	$annwyn_resize_image_dest = false;
	return true;

}
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

Ok, I've tried using your snippet, but still no cigar :(

Here's what I've got:

inc/imageresize.php:

Code: Select all

<?php

$annwyn_resize_image_source = false; 
$annwyn_resize_image_dest = false; 

// Just in case user aborts. 
function shutdown_func() { 
     
       global $annwyn_resize_image_source, $annwyn_resize_image_dest; 
    if($annwyn_resize_image_source) { 
        @imagedestroy($annwyn_resize_image_source); 
    } 
    if($annwyn_resize_image_dest) { 
        @imagedestroy($annwyn_resize_image_dest); 
    } 
} 

// $image - path to original image. 
// $new_image - path to save new image, 
// $new_width - should probably raname this max width.  
function annwyn_resize_image($image, $new_image, $new_width) { 

      global $annwyn_resize_image_source, $annwyn_resize_image_dest; 

    $imagesize = getimagesize($image); 

    if($imagesize === false) { 
        return false; 
    } 
     
    register_shutdown_function("shutdown_func"); 
     
    switch($imagesize[2]) { 
        case IMAGETYPE_JPEG: 
            if(($annwyn_resize_image_source = 
                @imagecreatefromjpeg($image)) === false) { 

                return false; 

            } 
            break; 
        case IMAGETYPE_PNG: 
            if(($annwyn_resize_image_source = @imagecreatefrompng($image)) === false) { 

                return false; 

            } 
            break; 
        case IMAGETYPE_GIF: 
            if(($annwyn_resize_image_source = @imagecreatefromgif($image)) === false) { 

                return false; 

            } 
            break; 
        default: 
            return false; 
            break; 
    } 
     
    // Don't enlarge but reduce proportionally. 
    if($imagesize[0] < $new_width) { 
         
        $new_width = $imagesize[0]; 
        $new_height = $imagesize[1]; 
         
    } else { 

        $new_height = $new_width * ($imagesize[1] / $imagesize[0]); 
         
    } 
     
    // Use imagecreat() for GIF images. 
    if($imagesize[2] == IMAGETYPE_GIF) { 
        $annwyn_resize_image_dest = imagecreate($new_width, $new_height); 
    } else { 
        $annwyn_resize_image_dest = imagecreatetruecolor($new_width, $new_height); 
    } 

    // Save the alphablending of PNG images. 
    if($imagesize[2] == IMAGETYPE_PNG) { 
        imagealphablending($annwyn_resize_image_dest, false); 
        imagesavealpha($annwyn_resize_image_dest, true); 
    } 

    // Save the transparency of GIF images. 
    if($imagesize[2] == IMAGETYPE_GIF) { 
        $colorTransparent = imagecolortransparent($annwyn_resize_image_source); 
        imagepalettecopy($annwyn_resize_image_dest,$annwyn_resize_image_source); 
        imagefill($annwyn_resize_image_dest,0,0,$colorTransparent); 
        imagecolortransparent($annwyn_resize_image_dest, $colorTransparent); 

    } 

    imagecopyresampled( 
        $annwyn_resize_image_dest, 
        $annwyn_resize_image_source, 
        0, 0, 0, 0, $new_width, $new_height, $imagesize[0], $imagesize[1]); 

    // Output the same image type as the original. 
    switch($imagesize[2]) { 
        case IMAGETYPE_JPEG: 
            imagejpeg($annwyn_resize_image_dest, $new_image); 
            break; 
        case IMAGETYPE_PNG: 
            imagepng($annwyn_resize_image_dest, $new_image); 
            break; 
        case IMAGETYPE_GIF: 
            imagegif($annwyn_resize_image_dest, $new_image); 
            break; 
        default: 
            return false; 
            break; 
    } 
     
    imagedestroy($annwyn_resize_image_source); 
    $annwyn_resize_image_source = false; 
    imagedestroy($annwyn_resize_image_dest); 
    $annwyn_resize_image_dest = false; 
    return true; 

} 

?>
prodimages.php:

Code: Select all

<?php

	if($_POST['submit']) { //If the user is uploading an image..
	
		include('inc/imageresize.php'); //Include the image resizing function

		//if(!$_POST['upload']) {
			//$usermsg .= '<font color="red">You didn\'t choose a file.</font>';
		//} else {
			$uploaddir = 'prodimages/';
			$uploadfile = $uploaddir . basename($_FILES['upload']['name']);

			if (move_uploaded_file($_FILES['upload']['tmp_name'], $uploadfile)) {
				echo "Image with default width saved successfully:<br><img src='$uploadfile'><br><br>";
				
				//Change the width of the image and save it somewhere else
				$file = $uploadfile;
				$newfile = $uploaddir . 'lrg_' . basename($_FILES['upload']['name']);
				$newwidth = 400;
				if(annwyn_resize_image($file, $newfile, $newwidth)) {
					echo "Image with 400 width saved successfully:<br><img src='$newfile'><br><br>";
				} else {
					echo "The image couldn't be resized to 400 width.<br><br>";
				}

				//Change the width of the image and save it somewhere else
				$file = $uploadfile;
				$newfile = $uploaddir . 'sml_' . basename($_FILES['upload']['name']);
				$newwidth = 200;
				if (annwyn_resize_image($file, $newfile, $newwidth)) {
					echo "Image with 200 width saved successfully:<br><img src='$newfile'><br><br>";
				} else {
					echo "The image couldn't be resized to 200 width.<br><br>";
				}

			} else {
			   $usermsg .= "<font color='red'>Possible file upload attack!</font>";
			}
		//}
	}

	echo '<center>';
	if($usermsg) {
		echo $usermsg; 
	}
	echo '<form action="prodimages.php" method="post" enctype="multipart/form-data">';
	echo '<strong>Image: <input type="file" name="upload" size="40"><br>';
	echo '<input type="submit" name="submit" value="Upload">';
	echo '</form>';
	echo '</center>';

?>
The page shows the default image uploaded success message and then the image, but that's all it shows; how!?!?! I've made it show something if the resizing goes right OR wrong, so surely the page should show something else. If i look in the prodimages/ folder on thr FTP there is only the original file there.

Any help appreciated :)
User avatar
Buddha443556
Forum Regular
Posts: 873
Joined: Fri Mar 19, 2004 1:51 pm

Post by Buddha443556 »

Jay have you checked to make sure GD is enabled on your server? This info should be available via phpinfo().

I got your snippet working but none of the changes should of made a difference. I just surpress a warning and initiated a missing variable. Might want to turn your errors on!

Code: Select all

<?php
include('inc/imageresize.php'); //Include the image resizing function

$usermsg = ''; // missing

    if(@$_POST['submit']) { //If the user is uploading an image.. Surpressed warning.
    
        //if(!$_POST['upload']) {
            //$usermsg .= '<font color="red">You didn\'t choose a file.</font>';
        //} else {
            $uploaddir = 'prodimages/';
            $uploadfile = $uploaddir . basename($_FILES['upload']['name']);

            if (move_uploaded_file($_FILES['upload']['tmp_name'], $uploadfile)) {
                echo "Image with default width saved successfully:<br><img src='$uploadfile'><br><br>";
                
                //Change the width of the image and save it somewhere else
                $file = $uploadfile;
                $newfile = $uploaddir . 'lrg_' . basename($_FILES['upload']['name']);
                $newwidth = 400;
                if(annwyn_resize_image($file, $newfile, $newwidth)) {
                    echo "Image with 400 width saved successfully:<br><img src='$newfile'><br><br>";
                } else {
                    echo "The image couldn't be resized to 400 width.<br><br>";
                }

                //Change the width of the image and save it somewhere else
                $file = $uploadfile;
                $newfile = $uploaddir . 'sml_' . basename($_FILES['upload']['name']);
                $newwidth = 200;
                if (annwyn_resize_image($file, $newfile, $newwidth)) {
                    echo "Image with 200 width saved successfully:<br><img src='$newfile'><br><br>";
                } else {
                    echo "The image couldn't be resized to 200 width.<br><br>";
                }

            } else {
               $usermsg .= "<font color='red'>Possible file upload attack!</font>";
            }
        //}
    }

    echo '<center>';
    if($usermsg) {
        echo $usermsg;
    }
// added $_SERVER['PHP_SELF'] here
    echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post" enctype="multipart/form-data">';
    echo '<strong>Image: <input type="file" name="upload" size="40"><br>';
    echo '<input type="submit" name="submit" value="Upload">';
    echo '</form>';
    echo '</center>';
?>
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

That's why...!

I asked him before I started if GD was installed and enabled and he said yes, but it obviously isn't as

Code: Select all

<?php
gd_info();
?>
Gives me a call to an undefined function.

Gggrrr. He's offline now but I'll pester him when he's back and get him to sort it.

I presumed it would give me a call to an undefined function when trying to use other GD functions and then I would know it wasn't installed, but that's not the case.

Anyway thanks for telling me that or I would've been messing with this for weeks...

I'll let you know how it goes when he's sorted it for me (it's shared hosting).
Post Reply