resizing an image to get a thumbnail - php

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)

Related

getting image file from php image resoure

When i use imagecopyresized() function on php it returns as image resource, and what i want is to get the image data from this image resource.may be like a file location in a string or an array containg several data of the file like the one you get in the $_FILES[] global array. thanks
$source = $_FILES['image']['tmp_name'];
list($width,$height) = getimagesize($source);
echo BR.$height." ".$width;
$desired_height = 28;
$scale = $width/$height;
$new_width = $desired_height * $scale;
$new_height = $desired_height;
$original_image = imagecreatefromjpeg($source);
$resized_image = imagecreatetruecolor($new_width, $new_height);
if(imagecopyresized($resized_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height)){
echo BR."image resized".BR;
}
i want to store the location of $resized_image in to database but i cant seem to access the file location from this variable.
This will put your image contents to the $buffer variable as a jpeg.
ob_start();
imagejpeg($im, null, 90);
$buffer = ob_get_contents();
ob_end_clean();
You can then save it with file_put_contents to a desired path and save the path to the database.
See https://secure.php.net/manual/en/function.imagejpeg.php
Alternatively, you could use a 3rd party library with a nicer API, such as Nette\Utils\Image or Intervention\Image.
imagecreatetruecolor creates an image resource in memory and returns its identifier. It does not create any physical file with the image in it.
Use imagejpeg like:
imagejpeg($resized_image, '/path/to/save/img.jpg')
It will create and save an image file to disk. And then you can store that path in database.
See: http://php.net/manual/en/function.imagejpeg.php and http://php.net/manual/en/function.imagecreatetruecolor.php
$resized_image is not associated with afile.
You need to use imagejpeg, imagepng, .. methods to save resources to a file.
imagejpeg($resized_image, 'path/file.jpg');

saving imagejpeg output the file

Is there something I am missing here? If I change imagejpeg($thumb, $newImage);
to imagejpeg($thumb); it echos a load of unreadable characters. The thumb image directory exists.
My ultimate aim is to copy an image at a lower quality.
$filename = $imageDirectory . '/1.jpg';
$percent = 0.5;
$newImage = $imageDirectory . '/thumbs/1.jpeg';
echo "image: <br>";
echo $filename;
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, $newImage);
UPDATE: I now realize that the second parameter must be an image location with the new name. So... I have redefined $newImage. The path is fine... if I upload an image named 1.jpg to that location manually it exists at that path.
You'll have to add the correct Content-Type header for the response if you want to output the image to the browser:
header('Content-Type: image/jpeg');
imagejpeg($yourimage);
Please check the first example in the documentation for more information. If you want to decrease the quality before outputting to your browser check the third example.

How to save an image in a folder?

This is my code to save an external image on the server. It does work.
$imgfromurl = file_get_contents('http://www.lavanguardia.com/r/GODO/LV/p4/WebSite/2017/03/07/Recortada/img_lbernaus_20170307-110204_imagenes_lv_terceros_istock-578792430-kUN-U42609284081yLC-992x558#LaVanguardia-Web.jpg');
$im = imagecreatefromstring($imgfromurl);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = $width/2;
$newheight = $height /2;
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$newsimgpath = uniqid().'.jpg';
$imgjpeg = imagejpeg($thumb, $newsimgpath); //save image as jpg
imagedestroy($thumb);
imagedestroy($im);
But if I want to save the image in a folder, it doesn't work anymore.
I have tryed to change this:
$imgjpeg = imagejpeg($thumb, $newsimgpath);
to this
imagejpeg($thumb, '/imgnews/'.$newsimgpath);
or to this:
imagejpeg($thumb, realpath(dirname(__FILE__)).'/imgnews/'.$newsimgpath);
but the image is not saved in that folder ( that has permissions 777 ).
Why ?
EDIT:
error_log:
[10-Mar-2017 08:52:32 America/New_York] PHP Warning: imagejpeg(/home/xxx/public_html/imgnews/58c2afa0c2c4b.jpg): failed to open stream: No such file or directory in /home/xxx/public_html/ad.php on line 14
as seen in the error - you haven't that directory.
as seen in your image - http://i.imgur.com/MoKGyF6.png you have newsimg directory.
you have 2 options:
create directory imgnews
in your code change imgnews to newsimg

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

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.

Save an image Resized with PHP

I am working on improving my Facebook app. I need to be able to resize an image, then save it to a directory on the server. This is the code I have to resize:
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
My question is, how would I save this resized image? Would I need to? Is there a way to manipulate the resized image without saving it?
According to the manual on imagejpeg(), the optional second parameter can specify a file name, which it will be written into.
Filename
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
To skip this argument in order to provide the quality parameter, use NULL.
It's usually a good idea to write the results to disk for some basic caching, so that not every incoming request leads to a (resource intensive) GD call.
function resize($img){
/*
only if you script on another folder get the file name
$r =explode("/",$img);
$name=end($r);
*/
//new folder
$vdir_upload = "where u want to move";
list($width_orig, $height_orig) = getimagesize($img);
//ne size
$dst_width = 110;
$dst_height = ($dst_width/$width_orig)*$height_orig;
$im = imagecreatetruecolor($dst_width,$dst_height);
$image = imagecreatefromjpeg($img);
imagecopyresampled($im, $image, 0, 0, 0, 0, $dst_width, $dst_height, $width_orig, $height_orig);
//modive the name as u need
imagejpeg($im,$vdir_upload . "small_" . $name);
//save memory
imagedestroy($im);
}
it should be work
http://www.php.net/manual/en/function.imagecopyresampled.php#90038

Categories