Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

saving image

Status
Not open for further replies.

thepain009

Technical User
Oct 22, 2005
42
US
Hello,

I found a script that is able to resize any image to a desired size. Right now it only outputs the resized image to a browser, however I would like to be able to save it to the server for future use. Is there any way to do this?

I basically have an variable at the end of the script thats the same that you get when u execute imageCreateTrueColor() method, only its been modified.

Any help is grately appreciated :)
 
how about
Code:
<?
$fh = fopen("image.jpg", "wb");
fwrite ($fh, $imagecontents);
fclose ($fh);
?>
 
Ohhhhh, that makes sense! Since we are outputing the 'image' headers and all! Thanks a lot!
 
Hmmm, even though this idea is great, I cant seem to make it work.

Here is my code and variables:

Code:
<?php
/*=============================================
              Drop-In Photo Gallery
                  Version 0.8


            by Sam Perkins-Harbin
               [URL unfurl="true"]www.forge22.com[/URL]
          Last Revision: 12 February, 2006
=============================================*/

$image = $_GET['i'];
$max_width = $_GET['w'];
$max_height = $_GET['h'];
$pic = $_GET['p'];

$picture_location = $image;

$picture_save = str_replace($image, array(".jpg", ".gif", ".png"), ".temp");

$im_size = GetImageSize ( $picture_location);
$imageWidth = $im_size[0];
$imageHeight = $im_size[1];

if (eregi('.jpg', $picture_location)) { //If file is a JPG
  $im2 = ImageCreateFromJPEG($picture_location);
} elseif (eregi('.gif', $picture_location)) { //If file is a GIF
  $im2 = ImageCreateFromGIF($picture_location);
} elseif (eregi('.png', $picture_location)) { //If file is a PNG
  $im2 = ImageCreateFromPNG($picture_location);
}

$x_ratio = $max_width / $imageWidth;
$y_ratio = $max_height / $imageHeight;

if ( ($imageWidth <= $max_width) || ($imageHeight <= $max_height) ) {
  $tn_width = $imageWidth;
  $tn_height = $imageWeight;
}


if (($x_ratio * $imageHeight) < $max_height) {
  $tn_height = ceil($x_ratio * $imageHeight);
  $tn_width = $max_width;
}
else {
  $tn_width = ceil($y_ratio * $imageWidth);
  $tn_height = $max_height;
}



$im = imageCreateTrueColor( $tn_width, $tn_height );

ImageCopyResampled ($im,$im2, 0, 0, 0, 0, $tn_width, $tn_height,$imageWidth, $imageHeight);
if (eregi('.jpg', $picture_location)) { //If file is a JPG
  Header("Content-type: image/jpeg");
  Imagejpeg($im,'',100); //to print to screen
  Imagejpeg($im,$picture_save,100);


} elseif (eregi('.gif', $picture_location)) { //If file is a GIF
  Header("Contrnt-type: image/gif");
  Imagegif($im,'',100);
  Imagegif($im,$picture_save,100);
} elseif (eregi('.png', $picture_location)) { //If file is a PNG
  Header("Content-type: image/png");
  Imagepng($im,'',100);
  Imagepng($im,$picture_save,100);
}

[red]
$fh = fopen("../mytests/thumbs/$pic", "wb");
fwrite ($fh, $im2);
fclose ($fh);
[/red]	
			
ImageDestroy($im);
ImageDestroy ($im2);



?>
 
(ooops, I pressed submit insdead of preview)

The script was made by someone else (credit given on top). The stuff in red is what im trying to add to make the resiezed image save.
After this script is executed, a file is created in the right folder, but there is no actual image inside.

Any ideas on how to do this are grately appreciated.
 
this won't work. the stream being output to the browser is returned by imagejpeg and you can't save that to a string and reuse it (sfaik).

basically you save the file by supplying a second argument to the imagejpeg function. the argument must be a filename that is writeable.

i have reworked the code a bit to make the calls a bit neater (avoiding regex and using variable function names). this code will save the file and then display it for you. the files are stored in your OS temp directory with the prefix "resampled_"

Code:
<?php
/*=============================================
              Drop-In Photo Gallery
                  Version 0.8


            by Sam Perkins-Harbin
               [URL unfurl="true"]www.forge22.com[/URL]
          Last Revision: 12 February, 2006
=============================================*/

$image = $_GET['i'];
$max_width = $_GET['w'];
$max_height = $_GET['h'];
$pic = $_GET['p'];
clearstatcache();
$picture_location = $image;

$im_size = getimagesize ( $picture_location);
$imageWidth = $im_size[0];
$imageHeight = $im_size[1];

//++++++++++++++++++++++++++++++++++
/*if (eregi('.jpg', $picture_location)) { //If file is a JPG
  $im2 = ImageCreateFromJPEG($picture_location);
} elseif (eregi('.gif', $picture_location)) { //If file is a GIF
  $im2 = ImageCreateFromGIF($picture_location);
} elseif (eregi('.png', $picture_location)) { //If file is a PNG
  $im2 = ImageCreateFromPNG($picture_location);
}
*/
//i'd consider changing the code block above to the following
//you are running three regex above which is not time friendly

$path_parts = pathinfo($picture_location);
if (
		in_array(
				strtolower($path_parts['extension']), 
				array("gif", "jpg", "png", "jpeg")
				)):
	if ($path_parts['extension'] == "jpg" ) $path_parts['extension'] ="jpeg"; //we need the full monty here
	$t_func = "imagecreatefrom".strtolower($path_parts['extension']);
	$im2 = $t_func($picture_location);
else:
	die("image is not an acceptable type");
endif;

//++++++++++++++++++++++++++++++++++++

$x_ratio = $max_width / $imageWidth;
$y_ratio = $max_height / $imageHeight;

if ( ($imageWidth <= $max_width) || ($imageHeight <= $max_height) ) {
  $tn_width = $imageWidth;
  $tn_height = $imageWeight;
}


if (($x_ratio * $imageHeight) < $max_height) {
  $tn_height = ceil($x_ratio * $imageHeight);
  $tn_width = $max_width;
}
else {
  $tn_width = ceil($y_ratio * $imageWidth);
  $tn_height = $max_height;
}



$im = imagecreatetruecolor( $tn_width, $tn_height );
imagecopyresampled ($im,$im2, 0, 0, 0, 0, $tn_width, $tn_height,$imageWidth, $imageHeight);
//now we can reuse the path_parts

//let's save it and then display it
//destination will be in the existing dir if it is writeable 
//otherwise the temp directory
if (OS_WINDOWS):
	$sep = "\\";
else:
	$sep="/";
endif;
$dir= pathinfo(tempnam("",""));
$dir = $dir['dirname'];
$filename = $dir.$sep."resampled_".$path_parts['basename'];
$varfunc  = "image".strtolower($path_parts['extension']);
$varfunc( $im, $filename,100);
//now display the file
header("Content-type: image/".strtolower($path_parts['extension']));
$varfunc($im,'',100); //to print to screen
//clean up
imagedestroy($im);
imagedestroy ($im2);
?>
 
Wow, thanks a lot. This worked perfectly. I only changed the directory to where it saves the pictures to.
Now I have another problem which seems very silly becuase its a simple if statement...
Im trying to run the script above if the resampled image doesnt exists and if it does, display it.

Code:
if (!file_exists('../mytests/thumbs/resampled_$pic'))
{
	echo "<p class='thumb' valign='middle'><tt><a href='../mytests/thumbs/resampled_$pic'><img src='image_resize.php?i=$d$pic&w=$w&h=$h&p=$pic' alt='$pic' />../mytests/thumbs/resampled_$pic</a>\n";	
}
else
{
	echo "<p class='thumb' valign='middle'><tt><a href='makeimg.php?photo=$current_dir$pic'><img src='../mytests/thumbs/resampled_$pic' alt='$pic' /></a>\n";	
}

This code doesnt seem to find the created files. IT always goes though the first part of the if statement and goes to though resize script every time. I thought that the path was wrong, but I made a link out of it, and upon clicking the already resized picture appears.
I tried file_exists() and if_file() and both behave similarly.
Any ideas whythis is happening?
 
do the links look ok in the source code? they don't look quite right in the php code posted above. (variables are not expanded in single quotes). also is the $_GET['i'] variable correctly set up?

you might try the heredoc syntax for clarity
Code:
    echo <<<EOF
<p class='thumb' valign='middle'>
 <tt>
   <a href="../mytests/thumbs/resampled_$pic">
     <img src="image_resize.php?i=$d$pic&w=$w&h=$h&p=$pic" alt="$pic" />
       ../mytests/thumbs/resampled_$pic
   </a>\n"; 
EOF;
 
Oh yea, im sorry. This is just a part of the php file. All variables are defined and links work correctly. The only problem is that the script doesn't see the file in the ../mytests/thumbs/ directory (first line in the code i posted).
 
substitute this line
Code:
if(!file_exists("../mytests/thumbs/resampled_$pic")
for this line
Code:
if(!file_exists('../mytests/thumbs/resampled_$pic')
variables do not get expanded in single quotes
 
I wish I was at home and could try this right now... insdead i have to wait 5 hours... Hehe.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top