I am using php Imagick for uploading cropped image using `cropImage' after that I want to resize that cropped image using 'resizeImage'. Here image cropping is working but resize image is showing exception my code is below.
upload.php
move_uploaded_file($_FILES["file"]["tmp_name"], $newUploadDir. $newfilename);
cropImage($newUploadDir.$newfilename,$newUploadDirSmall.$newfilename,$x,$y,$w,$h);
resizeImage($newUploadDirSmall.$newfilename,$newUploadDirSm.$newfilename,211, 50, 0, 0, true, false);
MagikLib.php
<?php
function cropImage($source,$destination, $startX, $startY, $width, $height)
{
$imagick = new \Imagick(realpath($source));
$imagick->cropImage($width, $height, $startX, $startY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
$imagick->writeImage($destination);
}
function resizeImage($source,$destination, $width, $height, $filterType, $blur, $bestFit, $cropZoom)
{
//The blur factor where > 1 is blurry, < 1 is sharp.
$imagick = new \Imagick(realpath($source));
$imagick->resizeImage($width, $height, $filterType, $blur, $bestFit);
$cropWidth = $imagick->getImageWidth();
$cropHeight = $imagick->getImageHeight();
if ($cropZoom) {
$newWidth = $cropWidth / 2;
$newHeight = $cropHeight / 2;
$imagick->cropimage(
$newWidth,
$newHeight,
($cropWidth - $newWidth) / 2,
($cropHeight - $newHeight) / 2
);
$imagick->scaleimage(
$imagick->getImageWidth() * 4,
$imagick->getImageHeight() * 4
);
}
header("Content-Type: image/jpg");
$imagick->writeImage($destination);
}
?>
MagicLib.php is reffered from http://phpimagick.com/Imagick/cropImage and http://phpimagick.com/Imagick/resizeImage
cropImage is working properly and saving image to folder but resizeImage is showing following errors
Warning: Cannot modify header information - headers already sent by (output started at /home/a/public_html/img/MagikLib.php:7) in /home/a/public_html/img/MagikLib.php on line 34
Fatal error: Uncaught exception 'ImagickException' with message 'unable to open image `/home/a/public_html/img/images//b6d767d2f8ed5d21a44b0e5886680cb9/user/sm/image1.jpg': No such file or directory # error/blob.c/OpenBlob/2709' in /home/a/public_html/img/MagikLib.php:35 Stack trace: #0 /home/a/public_html/img/MagikLib.php(35): Imagick->writeimage('/home/a/pu...') #1 /home/a/public_html/img/upload1.php(74): resizeImage('/home/a/pu...', '/home/a/pu...', 211, 50, 0, 0, true, false) #2 {main} thrown in /home/a/public_html/img/MagikLib.php on line 35
How to resolve this problem?
This is usually caused by the dir is not exists.
add this code:
$destinationPath = dirname($destination);
`mkdir -p $destinationpath`;
before
$imagick->writeImage($destination);
To recursively create path.
Related
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
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)
This question already has answers here:
imagecreatefromjpeg and similar functions are not working in PHP
(14 answers)
Closed 8 years ago.
I need to resize a picture to a fixed size. But it doesn't work and have error, what do i do?
ONLINE DEMO: http://codepad.org/3OrIHfoy
ERROR:
Fatal error: Call to undefined function imagecreatefromjpeg() on line
58
PHP:
<?php
function thumbnail_box($img, $box_w, $box_h) {
//create the image, of the required size
$new = imagecreatetruecolor($box_w, $box_h);
if($new === false) {
//creation failed -- probably not enough memory
return null;
}
//Fill the image with a light grey color
//(this will be visible in the padding around the image,
//if the aspect ratios of the image and the thumbnail do not match)
//Replace this with any color you want, or comment it out for black.
//I used grey for testing =)
$fill = imagecolorallocate($new, 200, 200, 205);
imagefill($new, 0, 0, $fill);
//compute resize ratio
$hratio = $box_h / imagesy($img);
$wratio = $box_w / imagesx($img);
$ratio = min($hratio, $wratio);
//if the source is smaller than the thumbnail size,
//don't resize -- add a margin instead
//(that is, dont magnify images)
if($ratio > 1.0)
$ratio = 1.0;
//compute sizes
$sy = floor(imagesy($img) * $ratio);
$sx = floor(imagesx($img) * $ratio);
//compute margins
//Using these margins centers the image in the thumbnail.
//If you always want the image to the top left,
//set both of these to 0
$m_y = floor(($box_h - $sy) / 2);
$m_x = floor(($box_w - $sx) / 2);
//Copy the image data, and resample
//
//If you want a fast and ugly thumbnail,
//replace imagecopyresampled with imagecopyresized
if(!imagecopyresampled($new, $img,
$m_x, $m_y, //dest x, y (margins)
0, 0, //src x, y (0,0 means top left)
$sx, $sy,//dest w, h (resample to this size (computed above)
imagesx($img), imagesy($img)) //src w, h (the full size of the original)
) {
//copy failed
imagedestroy($new);
return null;
}
//copy successful
return $new;
}
$i = imagecreatefromjpeg("http://techstroke.com/wp-content/uploads/2008/12/image2.png");
$thumb = thumbnail_box($i, 210, 150);
imagedestroy($i);
if(is_null($thumb)) {
/* image creation or copying failed */
header('HTTP/1.1 500 Internal Server Error');
exit();
}
header('Content-Type: image/jpeg');
imagejpeg($thumb);
that error...
Fatal error: Call to undefined function imagecreatefromjpeg() on line 58
imagecreatefromjpeg() is not callable because it does not exist. This means that the GD library has yet to be installed on your system.
here are the installation notes. you'll need them to get everything going. since you snagged that php function off the internet, it should work okay once you get the GD library installed.
Hi i am working on zend framework and trying to crop image after upload and save the cropped image but i am continuously getting path error. I am working on windows platform. Please someone help me out.
I am getting this error
Warning: getimagesize(C:\wamp\www\ModuleEx.com/public/image/) [function.getimagesize]: failed to open stream: No such file or directory in C:\wamp\www\ModuleEx.com\application\modules\admin\controllers\IndexController.php on line 21
Here is my code
public function indexAction()
{
if(isset($_FILES["img"]["name"])){
$names = $_FILES["img"]["name"];
$tmp = $_FILES["img"]["tmp_name"];
$upload_dir = "./public/image/".$names;
$move=move_uploaded_file($tmp, "$upload_dir");
$a="/public/image/".$names;
$this->view->a = $upload_dir;
$b=BASE_PATH."/public/image/".$names;
list($width, $height) = getimagesize($b);
$newwidth = "150";
$newheight = "90";
$thumb = imagecreatetruecolor($newwidth, $newheight);
if($_FILES["img"]["type"]=="image/jpeg"){
$source = imagecreatefromjpeg($b);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,BASE_PATH."/public/image/".$names , 90);
}
}
}
Im having issue when a user uploads and try's to crop a PNG or transparent image( with .gif)
I am getting:
Warning: imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error: in statusUpFunctions.php on line 100
Warning: imagecreatefromjpeg(): 'images/status/photo/1-6.jpg' is not a valid JPEG file in statusUpFunctions.php on line 100
Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in statusUpFunctions.php on line 114
This may be because of my php crop function:
case 'crop':
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
ini_set('memory_limit', '256M');
$jpeg_quality = 90;
$src = "images/status/photo/".$_POST['fname'];
$img_r = imagecreatefromjpeg($src);
if($_POST['fixed'] == 0) {
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
}
else {
$targ_h = $_POST['sizeh'];
$targ_w = $_POST['sizew'];
}
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
$path_thumbs = "images/status/photo";
$filename = $newfilename;
$thumb_path = $path_thumbs . '/' . $filename;
imagejpeg($dst_r,$thumb_path,$jpeg_quality);
}
break;
}
It creates from jpg, cant i make so it creates from gif and png and bmp and so..? and then convert it somehow..
How should this be solved?
The function imagecreatefromjpeg() creates a generic PHP image object from a jpeg image. You can then do whatever you want with the object.
imagecreatefromjpeg() will ONLY create a generic image object FROM a JPEG. If you want to create a generic image object FROM a PNG or GIF, you need to use their respective functions: imagecreatefrompng() and imagecreatefromgif(). One quick way to detect an image's type is by reading its file extension.
Once you have that generic image object, then you can do what you want with it (including using imagecopyresampled()), and then create a jpeg image from it using imagejpeg().
EDIT:
You can use pathinfo() to detect the file's extension:
$filename = pathinfo($_POST['fname']); // Returns an array of file details
$extension = $filename['extension'];
If you are getting the filename from a $_POST value, you need to make sure that you are copying the temporary image file to that filename. I don't see any $_FILES values used in your code (maybe you're doing it in another script?). If not, here's a good tutorial on handling file uploads. It also covers file extensions.
Try This... It will work..
<?php
$image = imagecreatefrompng('photo.png');
$thumb_width = 280;
$thumb_height = 200;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect ){
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}else{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$crop = imagecreatetruecolor($thumb_width,$thumb_height);
imagealphablending($crop, false);
$white = imagecolorallocatealpha($crop, 0, 0, 0, 127); //FOR WHITE BACKGROUND
imagefilledrectangle($crop,0,0,$thumb_width,$thumb_height,$white);
imagesavealpha($crop, true);
$userImage = imagecopyresampled($crop, $image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0, $new_width, $new_height,
$width, $height);
header('Content-type: image/png');
imagepng($crop);
?>
It fails to load the image, causing imagecreatefromjpeg() to return false. Make sure that you're trying to open an valid image.
For gif and png files you need to get the image identifier using imagecreatefromgif and imagecreatefrompng
<?php
$image = imagecreatefrompng('myPhoto.png');
$crop = imagecreatetruecolor(50,50);
$userImage = imagecopyresampled($crop, $image, 0, 0, 0, 0, 50, 50, 8, 8);
header('Content-type: image/png');
imagepng($crop);
?>
This will return cropped image.