PHP: crop with PNG and trans - php

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.

Related

PHP GD cropping PNG doesn't work

I'm creating a function to crop images using PHP GD.
The function works perfectly for JPEG images but when I try to use the same function for PNG I just get a blank page and the following errors when I inspect the page in chrome:
I realize this is a javascript error, but this is probably something chrome does? This is what happens when i visit the IMAGE URL. If i replicate this with the JPEG code it works perfectly.
Edit: in Firefox it says "The image [URL] cannot be displayed because it contains errors. The below js error is just a chrome error and isn't very relevant.
Uncaught TypeError: Cannot read property 'getAttribute' of null
data_loader.js:2 Uncaught TypeError: Cannot read property
'hasAttribute' of null global-shortcut.js:9
The working JPEG code is as follows:
$fileName = $_POST['file'];
$jpeg_quality = 100;
$ratio = $_POST['r'];
$src = '/var/www/admin/public_html/images/'.$fileName;
$image = imagecreatefromjpeg($src);
$target = '/var/www/admin/public_html/images/crop/'.$fileName;
$thumb_width = $_POST['w'] / $ratio;
$thumb_height = $_POST['h'] / $ratio;
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0,
0,
$_POST['x'] / $ratio, $_POST['y'] / $ratio,
$width, $height,
$width, $height);
imagejpeg($thumb, $target, $jpeg_quality);
The Broken PNG code is as follows:
$fileName = $_POST['file'];
$jpeg_quality = 100;
$ratio = $_POST['r'];
$src = '/var/www/admin/public_html/images/'.$fileName;
$image = imagecreatefrompng($src);
$target = '/var/www/admin/public_html/images/crop/'.$fileName;
$thumb_width = $_POST['w'] / $ratio;
$thumb_height = $_POST['h'] / $ratio;
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0,
0,
$_POST['x'] / $ratio, $_POST['y'] / $ratio,
$width, $height,
$width, $height);
imagepng($thumb, $target, $jpeg_quality);
I answered my own question.
imagepng() function takes quality argument from 0 to 9
imagejpeg() function takes quality argument from 0 to 100

Generated thumbnails are all black when uploading

I'm generating thumbnail images from the original jpeg files when they are being uploaded. I could actually create and move those thumbnail files to another directory, but the problem is that those thumbnail files displays only the black color while uploading.
My code.
if(isset($_POST['upload'])){
$img = $_FILES['origin']['name'];
move_uploaded_file($_FILES['origin']['tmp_name'], 'image/'.$img);
define("SOURCE", 'image/');
define("DEST", 'thumb/');
define("MAXW", 120);
define("MAXH", 90);
$jpg = SOURCE.$img;
if($jpg){
list($width, $height, $type) = getimagesize($jpg); //$type will return the type of the image
if(MAXW >= $width && MAXH >= $height){
$ratio = 1;
}elseif($width > $height){
$ratio = MAXW / $width;
}else{
$ratio = MAXH / $height;
}
$thumb_width = round($width * $ratio); //get the smaller value from cal # floor()
$thumb_height = round($height * $ratio);
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
$path = DEST.$img."_thumb.jpg";
imagejpeg($thumb, $path);
echo "<img src='".$path."' alt='".$path."' />";
}
imagedestroy($thumb);
}
and the thumbnail file looks like this:
From php manual:
imagecreatetruecolor() returns an image identifier representing a black image of the specified size.
So the problem is that you actually create this black image and save it.
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
For solution on resizing, please refer to this question on stackoverflow.
Hmm, I just found my bug right now. The problem is that I use $jpg = SOURCE.$img; instead of $jpg = imagecreatefromjpeg($jpg); and also I need to copy the sample image to the new thumbnail image using
imagecopyresampled( $thumb, $jpg, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height );
Then it works!!!
Thanks Alex for your answer which lead me to this solution.

Resize images with PHP

I have a quick question that I'm not quite sure to set up. I've seen examples elsewhere but nothing specifically like my situation. I would like to resize images using PHP so they're readable and not just wonkily stretched like if you use HTML. If they're not 250 pixels wide, or 160 pixels tall, how can I resize the picture so it's proportionate but fits within that space?
Thanks!
PHP does not manipulate images directly. You will need to use an image manipulation library such as gd or ImageMagick to accomplish this goal.
In ImageMagick, image resizing is accomplished like this:
$thumb = new Imagick('myimage.gif');
$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
With GD, you can do it like this:
<?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);
?>
Ok, so below is an Image object that I use in my store. It maintains scale - requires GD
<?php
class Store_Model_Image extends My_Model_Abstract
{
const PATH = STORE_MODEL_IMAGE_PATH;
const URL = "/store-assets/product-images/";
public function get_image_url($width, $height)
{
$old_file = self::PATH . $this->get_filename();
$basename = pathinfo($old_file, PATHINFO_FILENAME);
$new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);
if(file_exists(self::PATH . $new_name))
{
return self::URL . $new_name;
}
else
{
list($width_orig, $height_orig, $image_type) = #getimagesize($old_file);
$img = FALSE;
// Get the image and create a thumbnail
switch($image_type)
{
case 1:
$img = #imagecreatefromgif($old_file);
break;
case 2:
$img = #imagecreatefromjpeg($old_file);
break;
case 3:
$img = #imagecreatefrompng($old_file);
break;
}
if(!$img)
{
throw new Zend_Exception("ERROR: Could not create image handle from path.");
}
// Build the thumbnail
if($width_orig > $height_orig)
{
$width_ratio = $width / $width_orig;
$new_width = $width;
$new_height = $height_orig * $width_ratio;
}
else
{
$height_ratio = $height / $height_orig;
$new_width = $width_orig * $height_ratio;
$new_height = $height;
}
$new_img = #imagecreatetruecolor($new_width, $new_height);
// Fill the image black
if(!#imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))
{
throw new Zend_Exception("ERROR: Could not fill new image");
}
if(!#imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))
{
throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");
}
// Use a output buffering to load the image into a variable
ob_start();
imagejpeg($new_img, NULL, 100);
$image_contents = ob_get_contents();
ob_end_clean();
// lastly (for the example) we are writing the string to a file
$fh = fopen(self::PATH . $new_name, "a+");
fwrite($fh, $image_contents);
fclose($fh);
return self::URL . $new_name;
}
}
}
I resize the image at request time, so the first time the page loads an image will be resized to the required size for the template. (this means I don't have to crash a shared host trying to regenerate image thumbnails everytime my design changes)
So in the template you pass your image object, and when you need a image thumb,
<img src="<?php echo $image->get_image_url(100, 100); ?>" />
you now have a 100x100 thumb, which is saved to the Server for reuse at a later date
gd and imagemagick are two tools that may work for you
http://php.net/manual/en/book.image.php
http://php.net/manual/en/book.imagick.php
Here is something I used to use
class cropImage{
var $imgSrc,$myImage,$cropHeight,$cropWidth,$x,$y,$thumb;
function setImage($image,$moduleWidth,$moduleHeight,$cropPercent = "1") {
//Your Image
$this->imgSrc = $image;
//getting the image dimensions
list($width, $height) = getimagesize($this->imgSrc);
//create image from the jpeg
$this->myImage = imagecreatefromjpeg($this->imgSrc) or die("Error: Cannot find image!");
if($width > $height) $biggestSide = $width; //find biggest length
else $biggestSide = $height;
//The crop size will be half that of the largest side
//$cropPercent = 1.55; // This will zoom in to 50% zoom (crop)
if(!$cropPercent) {
$cropPercent = 1.50;
}
$this->cropWidth = $moduleWidth*$cropPercent;
$this->cropHeight = $moduleHeight*$cropPercent;
//$this->cropWidth = $biggestSide*$cropPercent;
//$this->cropHeight = $biggestSide*$cropPercent;
//getting the top left coordinate
$this->x = ($width-$this->cropWidth)/2;
$this->y = ($height-$this->cropHeight)/2;
}
function createThumb($moduleWidth,$moduleHeight){
$thumbSize = 495; // will create a 250 x 250 thumb
$this->thumb = imagecreatetruecolor($moduleWidth, $moduleHeight);
//$this->thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $moduleWidth, $moduleHeight, $this->cropWidth, $this->cropHeight);
//imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $thumbSize, $thumbSize, $this->cropWidth, $this->cropHeight);
}
function renderImage(){
header('Content-type: image/jpeg');
imagejpeg($this->thumb);
imagedestroy($this->thumb);
}
}
Call it by using
$image = new cropImage;
$image->setImage($imagepath,$moduleWidth,$moduleHeight,$scaleRelation);
$image->createThumb($moduleWidth,$moduleHeight);
$image->renderImage();
Use GD or ImageMagick. Here you may find a real production example of code (used by MediaWiki) that supports consoled ImageMagick interface (transformImageMagick method), ImageMagick extension interface (transformImageMagickExt method) and GD (transformGd method).
There a simple to use, open source library called PHP Image Magician that will can help you out.
Example of basis usage:
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');

imagejpeg() doesnt give the output properly in php

I want to upload an image from disk, resize it, and then upload it to Amazon S3.
However, I cant get the proper image output from imagejpeg().
heres my code:
$sourceUrl = $_FILES['path']['tmp_name'];
$thumbWidth = '100';
$thumbid = uniqid();
$img = imagecreatefromjpeg($sourceUrl);
$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
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// output the image
imagejpeg($tmp_img);
// upload thumbnail to s3
$s3->putObjectFile($tmp_img, "mybucket", $thumbid, S3::ACL_PUBLIC_READ);
Firebug gives me this error :
illegal character
[Break on this error] (�����JFIF���������>CREATOR: g...(using IJG JPEG v62), default quality\n
If I modify imagejpeg this way,
imagejpeg($tmp_img, 'abc.jpg');
then I get the same error. :(
Can i get some help here please ?
If you check the documentation of imagejpeg you can see it outputs the image, it means the way you call it it gets sent to the browser. You can get it to save to a file the second way you call it - by passing a filename in the second parameter.
Also, $tmp_img is an image resource, not a ready-to-use image file.
I don't know how your upload function works, but: if you need the file contents to upload, do it like this:
ob_start();
imagejpeg($tmp_image);
$image_contents = ob_get_clean();
$s3->putObjectFile($image_contents, "mybucket", $thumbid, S3::ACL_PUBLIC_READ);
if you need a filename to upload:
$filename = tempnam(sys_get_temp_dir(), "foo");
imagejpeg($tmp_image, $filename);
$s3->putObjectFile($filename, "mybucket", $thumbid, S3::ACL_PUBLIC_READ);
You have to define the header:
header('Content-type: image/jpeg');
1) $tmp_img is a resource not a file. You probably need to save the image to disc and use that for putObjectFile
2) You probably need to tell S3 that the file you're uploading is of type image/jpeg
Well guys thank you very much again, I screwed around a bit more and combining that with your responses I got this working as follows :)
$thumbid .= ".jpg";
$img = imagecreatefromgif($sourceUrl);
$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
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$path = '/var/www/1.4/wwwroot/cdn/'.$thumbid;
// output the image
if(imagegif($tmp_img, $path)){
$thumblink = "";
// upload thumbnail to s3
if($s3->putObjectFile($path, "mybucket", $thumbid, S3::ACL_PUBLIC_READ)){
$thumblink = "http://dtzhqabcdscm.cloudfront.net/".$thumbid;
imagedestroy($tmp_img);
}
return $thumblink;
}

Image resize issue in PHP - gd creates ugly resized images

I am creating thumbnails of fixed height and width from my PHP script using the following function
/*creates thumbnail of required dimensions*/
function createThumbnailofSize($sourcefilepath,$destdir,$reqwidth,$reqheight,$aspectratio=false)
{
/*
* $sourcefilepath = absolute source file path of jpeg
* $destdir = absolute path of destination directory of thumbnail ending with "/"
*/
$thumbWidth = $reqwidth; /*pixels*/
$filename = split("[/\\]",$sourcefilepath);
$filename = $filename[count($filename)-1];
$thumbnail_path = $destdir.$filename;
$image_file = $sourcefilepath;
$img = imagecreatefromjpeg($image_file);
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
if($aspectratio==true)
{
$new_height = floor( $height * ( $thumbWidth / $width ) );
}
else
{
$new_height = $reqheight;
}
// 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 );
// save thumbnail into a file
$returnvalue = imagejpeg($tmp_img,$thumbnail_path);
imagedestroy($img);
return $returnvalue;
}
and I call this function with following parameters
createThumbnailofSize($sourcefilepath,$destdir,48,48,false);
but the problem is the resulting image is of very poor quality, when I perform the same operation with Adobe Photo shop, it performs a good conversion.. why it is so? I am unable to find any quality parameter, through which I change the quality of output image..
Use imagecopyresampled() instead of imagecopyresized().
if it is image quality you are after you need to give the quality parameter when you save the image using imagejpeg($tmp_img,$thumbnail_path,100) //default value is 75
/*creates thumbnail of required dimensions*/
function
createThumbnailofSize($sourcefilepath,$destdir,$reqwidth,$reqheight,$aspectratio=false)
{
/*
* $sourcefilepath = absolute source file path of jpeg
* $destdir = absolute path of destination directory of thumbnail ending with "/"
*/
$thumbWidth = $reqwidth; /*pixels*/
$filename = split("[/\\]",$sourcefilepath);
$filename = $filename[count($filename)-1];
$thumbnail_path = $destdir.$filename;
$image_file = $sourcefilepath;
$img = imagecreatefromjpeg($image_file);
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
if($aspectratio==true)
{
$new_height = floor( $height * ( $thumbWidth / $width ) );
}
else
{
$new_height = $reqheight;
}
// 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 );
// save thumbnail into a file
$returnvalue = imagejpeg($tmp_img,$thumbnail_path,100);
imagedestroy($img);
return $returnvalue;
}
You could also consider using ImageMagick (http://us3.php.net/manual/en/book.imagick.php) instead of Gd. I had the same problem just a couple of days ago with Java. Going for ImageMagick instead of Java Advanced Images resultet in a huge quality difference.
tried using the php.Thumbnailer ?
$thumb=new Thumbnailer("photo.jpg");
$thumb->thumbSquare(48)->save("thumb.jpg");
Result photo will be 48x48px. Easy right? :)
You might also want to take a look at the Image_Transform PEAR package. It takes care of a lot of the low-level details for you and makes creating and manipulating images painless. It also lets you use either GD or ImageMagick libraries. I've used it with great success on several projects.

Categories