Image resizing in php? Can't get it to work - php

I have this code that I have tried creating and don't know what I am doing wrong.
// SET ERROR FLAG
$error = false;
// MAKE SURE FILE IS AN IMAGE
if (!list($width, $height) = getimagesize($_FILES['avatar']['tmp_name'])) {
$error = true;
}
// MAKE SURE FILE COMES FROM FORM
if (!is_uploaded_file($_FILES['avatar']['tmp_name'])) {
$error = true;
}
// MAKE SURE FILESIZE IS NOT OVER 1MB
if (filesize($_FILES['avatar']['tmp_name']) > 1048576) {
$error = true;
}
// TARGER TO SAVE FILE AND CHANGE FILENAME AND FILE TYPE
$target = 'images/avatars/' . md5($user['id']) . '.gif';
// IMAGE RATIO AND RESIZING
$imgRatio = $width / $height;
if ($imgRatio > 1) {
$newWidth = 200;
$newHeight = 200 / $imgRatio;
} else {
$newWidth = 200 * $imgRatio;
$newHeight = 200;
}
$imgResized = imagecreatetruecolor($newWidth, $newHeight);
$newImg = imagecreatefromgif($_FILES['avatar']['tmp_name']);
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// SUCCESSFULL IMAGE UPLOAD
if (!$error && move_uploaded_file($newImg, $target)) {
echo '<p>Your avatar was uploaded successfully.</p>';
// ERROR UPLOADING IMAGE
} else {
echo '<p>There was an error uploading your avatar.</p>';
}
It always fails I cannot get the resizing to work, even a link to a good tutorial will suffice,
Happy new year!!

I think the problem is that you use GD to open the temporary image file:
$newImg = imagecreatefromgif($_FILES['avatar']['tmp_name']);
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
And then you try to move the temporary avatar file with move_uploaded_file without freeing GD resource and also discarding all the work done with GD (the resizing I mean, and I can add here you have to use resample instaead of resize method).
if (!$error && move_uploaded_file($newImg, $target)) {
The code moves the temporary uploaded file (currently opened by GD and however not physically altered by your GD work, so not resized) to the $target path.
Edit. Now I see more errors with your code. You cannot do:
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
Because imagecopyresized do not returns anything but true or false. It simply copy one portion of a source image to a different destination resource. It do not return a resource itself!
Finally. The correct workflow to the what you want to do is:
Check the uploaded file if it's ok for you (and you do it good, it seems).
Create a $img GD resource opening the uploaded file with imagecopyresized.
Create an empty destination resource $newImg with imagecreatetruecolor.
Resize or resample using imagecopyresized or imagecopyresampled to copy source image to destination resource.
Save destination resource into a GIF file using imagegif.
Discard temporary source uploaded image.
You can learn more googling something like php gd resize uploaded images. Tons of tutorial will be one click far from you.

The code itself looks alright, however there could be a number reasons why it fails. Some debug output would be helpful. Some general pointers:
check that the path for the tmp_name is set and readable
check your php settings for post_max_size, it may be set very low or not set at all.
in your code you are only handling gif type images (imagecreatefromgif), you may need to check for the filetype prior to reading from the image resource
check that GD is properly installed in your php installation (phpinfo(); in a php script or php -i from command line should display it as acticated)
That being sad, add some error messages to your output so we can help further.

Related

resizing an image to get a thumbnail

I am trying to create a thumbnail of an image. I got the php code from the php.net website, but it returns this error:
Warning: imagejpeg(/Users/michelebrizzi/Sites/htdocs/blogmichele/immagini/ragazza_thumb.jpg): failed to open stream: Permission denied in /Users/michelebrizzi/Sites/htdocs/blogmichele/prova/imagescale.php on line 19
What did I make a mistake?
This is the php code I've used:
<?php
// File and new size
$filename = $_SERVER['DOCUMENT_ROOT'].'/cartella_sito/immagini/image.jpg';
$percent = 0.5;
// Content type
// header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb, $_SERVER['DOCUMENT_ROOT']."/cartella_sito/immagini/image_thumb.jpg", 75);
?>
read error messages again. The error message itself says permission denied.
That is pretty routine - getting permission denied. Check the unix level file permissions and make sure the user under which PHP runs has read access. just to test chmod to 777. Then revert to more restrictive settings. Make sure that the entire path chain can be accessed.
It could also be that PHP does not have the directive/permission to go into that directory. I am forgetting the setting. But there is this thing; that for directories outside htdocs/webroot you need to explicitly permit that. See this - Make XAMPP/Apache serve file outside of htdocs. But it appears that this does not apply, as you are trying to access files inside of htdocs.
Try putting some error handling in:
From my experience there are two options why this won't work
1) The file doesn't exist
<?php
// File and new size
$filename = $_SERVER['DOCUMENT_ROOT'].'/cartella_sito/immagini/image.jpg';
if(!file_exists($filename)) {
die("The file does not exist");
}
$percent = 0.5;
// Content type
// header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb, $_SERVER['DOCUMENT_ROOT']."/cartella_sito/immagini/image_thumb.jpg", 75);
?>
2) You do not have the correct permissions
Assuming you are using a client such as FileZilla, right click on the folder of the image and ensure you at least have read access to the file (by going to Folder Permissions)

PHP - Image resizing issue when uploaded

I'm having a hard time to make my web-application work properly. I have been trying to make my avatar not feel pushed and make it resize automatically when uploaded. I'm not the best with PHP hence why I can't do this on my own. I would appreciate if someone could help me out. That's the code of the file that is the avatar.
Best regards!
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
You'll require to store Uploaded Picture on your webserver
For that:
You'll Require:
move_uploaded_file()
and for resizing purpose you can use:
imagecopyresampled()
as follows:
function resizeIMG($o_img // original image
, $target_image // Resized New Image
, $newWidth, $newHeight){
// Get Original Dimensions as follows:
$original_width=imagesx($o_image); //Returns width of image
$original_height=imagesy($o_image); //Returns height of image
$tmp = imagecreatetruecolor($newWidth, $newHeight); // Create New temp. image with new dimensions
imagecopyresampled($tmp_img, $o_img, 0, 0, 0, 0, $newWidth, $newHeight, $original_width, $original_height); // Resize original image to temporary Image
imagejpeg($tmp, $target_image, $quality); // Copy temp Image to Target File for JPG images
imagedestroy($tmp); // Destroy Temporary Image.
/* Use
imagepng() instead of imagejpeg() for PNG images
imagegif() instead of imagejpeg() for GIF images
*/
}
For all these functions mentioned you'll need to enable gd_drivers for your php. By simply removing ; before line extension=php_gd2.dll if you're using windows or See this for others.
Or you can Use image_magick for php.
also do have a look at: Resize images in PHP without using third-party libraries?
hope it helps.. cheers :).

PHP: how to use getimgasize() after the image is resized using getimageresized after upload?

using the example given at http://www.php.net/manual/en/function.imagecopyresized.php ... how to get image sizes afterward using getimagesize() function?
CODE:
<?php
if(isset($_FILES['images'])){
//TEST1:
$img = resize_this_image_now($_FILES['images']['tmp_name']);
//TEST2:
$img = resize_this_image_now($_FILES['images']['name']);/// This Drastically failed.
$new_image = getimagesize($img);
var_dump($new_image[0]);// I guessed this should have printed out the WIDTH_OF_THE_IMAGE... but, it prints some NON_READABLE stuffs (why?)
}
// The PHP.NET CODE in a Function
function resize_this_image_now($filename){
// File and new size
// $filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
return imagejpeg($thumb);
}
?>
All I want is to get the Size of the Image.... also, is it possible to do something like:
$_FILES['images']['tmp_name'] = $the_newly_resized_image_returned_from_the_PHP_dot_NET_code'; .... So that the ['images']['tmp_name'] will now have as source this new image??
Any suggestion is highly appreciated...
I decided to spend sometime examining you question. What I found out is that, I don't think you'd need to return the resized image through imagejpeg() the way you did. You might also need to add a imagedestroy(), after you call imagejpeg() in you function, to destroy the temporary memory used.
You need to first fully Upload the Image before resizing it. If you'd like, you could send the image in a temporary storage while you do whatever you want to it so that Php does not have to deal with it in a 'tmp_name' format...Then You can destroy the image later on.
Once the image is fully uploaded, things become easier. The codes might look something like:
if(isset($_FILES['images'])){
//may be some random numbers to accompany it.
$rand = floor((mt_rand()+rand()+mt_rand())/3);
//Send it to the temporary folder you have had to create.
if(move_uploaded_file(
$_FILES['images']['tmp_name'],'temporary_storage/image_'.$rand.'.jpg')){
//Then run the `resize` function from here.
$image_resized = resize_this_image_now('temporary_storage/image_'.$rand.'.jpg');
//Now You can get the size if you wish.
list($width,$height) = getimagesize('temporary_storage/image_'.$rand.'.jpg');
// Out put
echo "W:".$width."<br>H:".$height;
//After you use it as desired, you can now destroy it using unlink or so.
unlink('temporary_storage/image_'.$rand.'.jpg');
}else{
echo "Upload Error goes here";
}
}
Note this answer is produced after several trials and errors... Please use this strategy wisely.
Hope it helps.

PHP create thumbnail from uploaded file and moving to server

I have encountered a problem with creating a thumbnail from an uploaded image file, then to upload it to the server.
As of now, I have a function that creates the thumbnail, saves it as a temp and returns it to the caller.
Then what I try to do, is upload that created thumb image with move_uploaded_file(tempthumb, path);
Here is the createThumb function and the caller:
function createThumb( $image, $thumbWidth )
{
// load image and get image size
$img = imagecreatefromjpeg( "{$image}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
return $tmp_img;
}
return $tmp_img; // Here I return the new image. Is this the proper way to get a binary image back??
Here is the caller:
$thumb = createThumb($_FILES['propform-previmg']['tmp_name'], $max_previmg_width);
$filenamepath = $src_dir . '/thumb/' . $_FILES['propform-previmg']['name'];
if ( !move_uploaded_file($thumb, $filenamepath ))
echo "Error moving file {$filenamepath}";
I tried to just upload the uploaded file directly without trying to make a thumbnail first, and that worked fine. So I guess there is some error with the variable I return from the createThumb function, but I can't figure out exactly what.
Also, I need to do the upload from the caller code, and not inside the createThumb function with imagejpeg(file, path).
Thank you!
First line from the manual:
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
Your thumbnail wasn't uploaded, it even isn't a file yet, but just an image resource. To write the image, call something like imagejpeg($resource, $filename) to write it to the path specified in $filename.

Produce a correctly sized error.jpg image if requested image does not exist in php

An illegal request is made for image=90273497823 when the source doesn't
exist, you should return a correctly sized placeholder image in its stead.
An example might be:
<img src="resources/image.php?id=95648633&x=160&y=120&color=1" alt="kitty"/>
Instead of allowing the webpage to directly pull images from my server, I call the script image.php to service this request, and to handle exceptions if needed. The script works for all images that exist, but for the non existent images the script fails to load the error.jpg image that I have; Leading me to believe my error handling is incorrect.
What I expect my script to do is check whether the file exists, and if not replace with the correctly sized(the same size request of the non-existent image) error.jpg
My script as follows.
<?php
header('Content-type: image/jpg');//override the return type
//so browser expects image not file
$id=$_GET['id'];//get file name
$new_width=$_GET['x'];//get width
$new_height=$_GET['y'];//get heigth
$color=$_GET['color'];//get colored version type
$filename=$id;//file id is set as file name
$filename.=".jpg";//append .jpg onto end of file name
// create a jpeg from the id get its size
$im=imagecreatefromjpeg($filename);
// get the size of the image
list($src_w, $src_h, $type, $attr)=getimagesize($filename);
/*
Exception handling for when an image is requested and the file dosent exist
in the current file system or directory. Returns file "error.jpg" correctly
sized in the place of the requested null file.
*/
if(!file_exists($filename))//(file_exists($filename) == false)
//(!file_exists($filename))
{
imagedestroy($im);//why do I have to destroy it, why cant I write over it?
$im=imagecreatefromjpeg("error.jpg");
list($src_w, $src_h, $type, $attr)=getimagesize($im);
}
/*
this function will resize the image into a temporary image
and then copy the image back to $im
*/
if($new_width != '' && $new_height != '')
{
//MAKE A TEMP IMAGE TO COPY FROM
$imTemp=imagecreate($new_width, $new_height);
imagecopyresized($imTemp, $im, 0, 0, 0, 0, $new_width, $new_height, $src_w,
$src_h);
imagedestroy($im);//free up memory space
//COPY THE TEMP IMAGE OVER TO $im
$im=imagecreate($new_width, $new_height);
imagecopy($im, $imTemp, 0, 0, 0, 0, $new_width, $new_height);
imagedestroy($imTemp);//free up memory space
}
/*
If the image being requested has color = 0, then we return a grayscale image,
but if the image is already grayscale
*/
if($color == 0)
{
imagefilter($im, IMG_FILTER_GRAYSCALE);
}
//What do we do if color = 0, but they want a colorized version of it???
imagejpeg($im);//output the image to the browser
imagedestroy($im);//free up memory space
?>
getimagesize takes a filename, not an image resource handle. That might one place you are going wrong.

Categories