How do you download, resize and store an image from a remote server using php?
This is the code I am using
$temp_image = file_get_contents($url);
$image = imagecreatefromstring($temp_image);
$thumb = imageToCanvas($image,100,75,true);
imagejpeg($thumb,$base_image_path . $thumb_path,90)
function imageToCanvas($_image, $_canvasWidth, $_canvasHeight, $forceScale=false,$x=false,$y=false)
{
$newImage = imagecreatetruecolor($_canvasWidth, $_canvasHeight);
$imageinfo = getimagesize($_image);
$sourceWidth = $imageinfo[0];
$sourceHeight = $imageinfo[1];
$sourceImage = openImage($_image);
imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $_canvasWidth, $_canvasHeight, $sourceWidth, $sourceHeight);
return $newImage;
}
function openImage($file)
{
// *** Get extension
$extension = strtolower(strrchr($file, '.'));
switch($extension) {
case '.jpg': case '.jpeg':
$img = #imagecreatefromjpeg($file);
break;
case '.gif':
$img = #imagecreatefromgif($file);
break;
case '.png':
$img = #imagecreatefrompng($file);
break;
default:
$img = false;
break;
}
return $img;
}
Doesn't work and I don't know why.
$sourceWidth & $sourceHeight doesn't have a value so I presume $image is in the wrong format
Thanks!
There is no function in php called openImage so that would be a problem if you don't define it yourself.
If you do have it defined, what does it look like and are you receiving any errors?
Edit: Based on your comments the problem would seem to be that you treat the input parameter of your openImage function as a file path. However, when you call it you are feeding it an image resource, the result of imagecreatefromstring.
If you are on a linux server and ghostscript is installed - here is an easier way
shell_exec("convert in.jpg -resize 100x75 out.jpg")
Related
I've come across some code on this site to help fix the orientation issue in regrades with iOS photos.
Here is the PhP
<?php
session_start();
$filename = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
$exif = exif_read_data($_FILES['file']['tmp_name']);
if (!empty($exif['Orientation'])) {
$imageResource = imagecreatefromjpeg('/uploads'); // provided that the image is jpeg. Use relevant function otherwise
switch ($exif['Orientation']) {
case 3:
$image = imagerotate($imageResource, 180, 0);
break;
case 6:
$image = imagerotate($imageResource, -90, 0);
break;
case 8:
$image = imagerotate($imageResource, 90, 0);
break;
default:
$image = $imageResource;
}
}
imagejpeg($image, $filename, 90);
?>
This code seems to work but I havn't seen the outputted image as I can't move the altered image to the server. What I need to do is move the image onto the servers.
I didn't even know that Apple phone did this little bit of extra evil.
Thanks for any help.
I found this, maybe stripping the EXIF from the image?
$filename = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
$exif = exif_read_data($_FILES['file']['tmp_name']);
if (!empty($exif['Orientation'])) {
$imageResource = imagecreatefromjpeg($filePath); // provided that the
image is jpeg. Use relevant function otherwise
switch ($exif['Orientation']) {
case 3:
$image = imagerotate($imageResource, 180, 0);
break;
case 6:
$image = imagerotate($imageResource, -90, 0);
break;
case 8:
$image = imagerotate($imageResource, 90, 0);
break;
default:
$image = $imageResource;
}
}
I'm not 100% sure if its the best practice but if it works!
I want to use watermark image with php. This is my reference page
function imagecreatefromfile($image_path)
{
list($width, $height, $image_type) = getimagesize($image_path);
switch ($image_type)
{
case IMAGETYPE_GIF: return imagecreatefromgif($image_path); break;
case IMAGETYPE_JPEG: return imagecreatefromjpeg($image_path); break;
case IMAGETYPE_PNG: return imagecreatefrompng($image_path); break;
default: return ''; break;
}
}
$image = imagecreatefromfile($_GET['image']);
if (!$image) die('Unable to open image');
$watermark = imagecreatefromfile('uploads/files/water.png');
if (!$image) die('Unable to open watermark');
$watermark_pos_x = imagesx($image) - imagesx($watermark) - 8;
$watermark_pos_y = imagesy($image) - imagesy($watermark) - 10;
imagecopy($image, $watermark, $watermark_pos_x, $watermark_pos_y, 0, 0,
imagesx($watermark), imagesy($watermark));
header('Content-Type: image/jpg');
imagejpeg($image, '', 100);
imagedestroy($image);
imagedestroy($watermark);`
but my page seems empty ,
This is my test page
http://www.alanyaticaretrehberi.com/watermark.php?image=uploads/firmaresim/750/address-cikcilli-3jpg.jpeg
this worked in other servers but not worked in my server.
This is my phpinfo page..
http://www.alanyaticaretrehberi.com/php.php
I guess some setting missed in my php settings but i dont know what it is. May be it is about gd library or something else, can you give some advices for this issue.
I've got a GD Library upload script which processing and resizes images. After uploading PNGs are getting rendering as a different image, some stock-looking image, on the browser side, yet when opened on disk they are correct. I've re-saved the affected pngs via photoshop and uploaded directly, this fixes the display issue, but when i upload that image via the script the display issue returns, thus the script encoding seems to cause issue with the browser display, but why i know not.
Hosting environment is Hetzner Server.
Upload Sample:
//resize images
protected function resize($img, $w, $h, $newfilename) {
//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2')) {
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}
//Get Image size info
$imgInfo = getimagesize($img);
switch ($imgInfo[2]) {
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img); break;
case 3: $im = imagecreatefrompng($img); break;
default: trigger_error('Unsupported filetype!', E_USER_WARNING); break;
}
//If image dimension is smaller, do not resize
if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
$nHeight = $imgInfo[1];
$nWidth = $imgInfo[0];
}
else{
// yeah, resize it, but keep it proportional
if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
$nWidth = $imgInfo[0]*($h/$imgInfo[1]);
$nHeight = $h;
}
else{
$nWidth = $w;
$nHeight = $imgInfo[1]*($w/$imgInfo[0]);
}
}
$nWidth = round($nWidth);
$nHeight = round($nHeight);
$newImg = imagecreatetruecolor($nWidth, $nHeight);
/* Check if this image is PNG or GIF, then set if Transparent*/
if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
//Generate the file, and rename it to $newfilename
switch ($imgInfo[2]) {
case 1: imagegif($newImg,$newfilename); break;
case 2: imagejpeg($newImg,$newfilename,100); break;
case 3: imagepng($newImg,$newfilename,0); break;
default: trigger_error('Failed resize image!', E_USER_WARNING); break;
}
return $newfilename;
}
Can anyone give me some insight into this. Will provide more info if necessary. Ty
EDIT:
Browser Display
Disk Display
I have no clue where that image is coming from, it's on multiple uploads, when browsing the full path to the image on the browser the same image comes up so it's not a pathing issue.
I have the following problem. User can upload image, and I would like to display the image about 5 times smaller, without to cause distortion on the image. That is I would like to avoid. How can I find the width and height of the original image and divide it by 5?
I use php, forgot to mention that detail.
Regards,Zoran
From the sounds of your comments, you are looking for something simpler than the answers you are getting. Have you tried getimagesize? http://php.net/manual/en/function.getimagesize.php
You can do something like this:
$size = getimagesize($filename);
echo $size[0]/5; //width
echo $size[1]/5; //height
This method also has the advantage of not having to rely on an image library like GD or anything.
http://php.net/manual/en/imagick.resizeimage.php
call it with FILTER_GAUSSIAN
<?php
$image = new Imagick( $filename );
$imageprops = $image->getImageGeometry();
if ($imageprops['width'] <= 200 && $imageprops['height'] <= 200) {
// don't upscale
} else {
$image->resizeImage(200,200, imagick::FILTER_GAUSSIAN, 0.9, true);
}
?>
The idea is to blur the image by using gaussian filter and than subsampling it.
After image upload is done, use the following function:
<?php
function generate_image_thumbnail($source_image_path, $thumbnail_image_path){
list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
switch ($source_image_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_image_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_image_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_image_path);
break;
}
if ($source_gd_image === false) {
return false;
}
$thumbnail_image_width = $source_image_width/5;
$thumbnail_image_height = $source_image_height/5;
$thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
imagedestroy($source_gd_image);
imagedestroy($thumbnail_gd_image);
return true;
}
?>
Pass right param to the function, it will do the job.
And make sure GD is enabled in your php settings. it uses gd library.
I'm trying to load an image from an external site over which I have no control.
Most of the time it works fine (hundreds of images tested so far).
It's now giving me this error for one particular image:
imagecreatefromstring(): gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: premature end of data segment
from this line:
$im = #imagecreatefromstring( $imageString );
The advice I'd read so far suggests adding:
ini_set("gd.jpeg_ignore_warning", true);
but that's had no effect and I'm still getting the error. I'm doing the ini_set just before the call. Is that relevant?
I'm really stuck on how to ignore this error and carry on.
The problem was due to my error handling. I'd set up an error handler so my call to
$im = #imagecreatefromstring( $imageString );
wasn't suppressing errors.
By modifying my error handler with:
if (error_reporting() === 0)
{
// This copes with # being used to suppress errors
// continue script execution, skipping standard PHP error handler
return false;
}
I can now correctly suppress selected errors.
I found the info here: http://anvilstudios.co.za/blog/php/how-to-ignore-errors-in-a-custom-php-error-handler/
this can be solve with:
ini_set ('gd.jpeg_ignore_warning', 1);
If you are just showing the image, then I suggest simply reading the contents and display the image as follows:
$img = "http://path/to/image";
$contents = file_get_contents($img);
header("Content-Type: image/jpeg");
print($contents);
If you are wanting to copy the image to your server, you have a few options, two of which are the copy() function or the method used above and then fwrite():
Option 1 - The copy() function, available from PHP 4
$file1 = "http://path/to/file";
$dest = "/path/to/yourserver/lcoation";
$docopy = copy($file1, $dest);
Option 2 - Using file_get_contents() and fwrite()
$img = "http://path/to/image";
$contents = file_get_contents($img);
$newfile = "path/to/file.ext";
$fhandler = fopen($newfile, 'w+'); //create if not exists, truncate to 0 length
$write = fwrite($fhandler, $contents); //write image data
$close = fclose($fhandler); //close stream
chmod(0755, $newfile); //make publically readable if you want
I hope you find some use in the above
Considering that you want to make a thumbnail and save it, you could implement a handy resize function like the following:
<?php
function resize($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality){
$ext1 = explode(".",trim($sourcefile));
$ext = strtolower(trim(array_slice($sext1,-1)));
switch($ext):
case 'jpg' or 'jpeg':
$img = imagecreatefromjpeg($sourcefile);
break;
case 'gif':
$img = imagecreatefromgif($sourcefile);
break;
case 'png':
$img = imagecreatefrompng($sourcefile);
break;
endswitch;
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
}
else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
switch($ext):
case 'jpg' or 'jpeg':
$makeimg = imagejpeg($tmpimg, $endfile, $quality);
break;
case 'gif':
$makeimg = imagegif($tmpimg, $endfile, $quality);
break;
case 'png':
$makeimg = imagepng($tmpimg, $endfile, $quality);
break;
endswitch;
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
if($makeimg){
chmod($endfile,0755);
return true;
}else{
return false;
}
}
?>
Then, after you've copied the file to your server using one of my methods in my answer above this, you could simply apply the function as follows:
$doresize = resize($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality);
echo ($doresize == true ? "IT WORKED" : "IT FAILED");
This function serves me pretty well. I apply it to 1000's of images a day and it works like a charm.