Why is my scaled image always black? - php

I am making thumbnails and for some reason, my output is the correct size, but always black. I saw another Stack Overflow post on a similar topic but in his case, he was passing parameters incorrectly.
I am capturing an image from a video camera and then using this code:
$data = base64_decode($data); // the data will be saved to the db
$image = imagecreatefromstring($data); // need to create an image to grab the width and height
$img_width = imagesx($image);
$img_height = imagesy($image);
// calculate thumbnail size
$new_height = 100;
$new_width = floor( $img_width * ( 100 / $img_height ) );
// create a new temporary image
$new_image = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
$url = IMGDIR.$imgname;
$thumburl = IMGDIR."thumb/".$imgname;
// save image and thumb to disk
imagepng($image,$url);
imagepng($new_image,$thumburl);
The result I get is both files saved to the proper directories, both the proper size, but the thumbnail is all black. There must be something simple I am missing. Any ideas?

Remember that PNG files have alpha channels. So be sure to use imagealphablending and imagesavealpha. Here they are integrated into your code.
$data = base64_decode($data); // the data will be saved to the db
$image = imagecreatefromstring($data); // need to create an image to grab the width and height
$img_width = imagesx($image);
$img_height = imagesy($image);
// calculate thumbnail size
$new_height = 100;
$new_width = floor( $img_width * ( 100 / $img_height ) );
// create a new temporary image
$new_image = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
$url = IMGDIR . $imgname;
$thumburl = IMGDIR . "thumb/" . $imgname;
// Set the image alpha blending settings.
imagealphablending($image, false);
imagealphablending($new_image, false);
// Set the image save alpha settings.
imagesavealpha($image, true);
imagesavealpha($new_image, true);
// save image and thumb to disk
imagepng($image,$url);
imagepng($new_image,$thumburl);

Try saving your image's alpha channel with imagesavealpha and passing true for the 2nd argument
imagesavealpha($image, true);
imagepng($image,$url);
imagesavealpha($new_image, true);
imagepng($new_image,$thumburl);

Related

Make a move_uploaded_file after imagecopyresampled in PHP

I'm trying to resize image in PHP.
But after all this work how can I use the move_uploaded_file function to move the tmp_file file to it final directory ?
Here's my code:
$image = imagecreatefromjpeg($_FILES['REG_Image']['tmp_name']);
// Target dimensions
$max_width = 1014;
$max_height = 768;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
if($old_width > $max_height) {
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
}
Thanks.
You can use imagejpeg instead after
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width,$new_height, $old_width, $old_height);
imagejpeg($new, "/path/to/image.jpeg");
this will save the image to the new path that you have specified as image.jpeg. You can use imagepng as well if you want a PNG image as output.

Create a circle thumbnail from jpeg in PHP

Hi currently I built have function to create a thumbnail from an image and it does so, however I want it to be a circle thumbnail not a rectangle, how can I achieve this without using any external libraries just php built in methods? thank you
function createThumb( $imagepath, $thumbFile, $thumbWidth )
{
// load image and get image size
$img = imagecreatefromjpeg( "$imagepath" );
$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 );
// save thumbnail into a file in the temp directory below script or somewhere
imagejpeg( $tmp_img, $thumbFile );
}
CSS is a better way to do it actually .
.class-name {
border-radius : 30px;
}

PNG - preserving transparency

I'm trying to redesign my site so that my original square, tile-based rendering of images can be more of a cutout of the image... to get rid of that grid pattern.
Here's how it looked originally...
Here's a rough mock-up of what I'm going for:
So I resaved an image thumbnail with a transparent background... I just want the dog to show, and the square is transparent which will show the site's background underneath.
Yet when I render it on the page, it has this black background.
I've checked my CSS to see if there is some sort of img class, or class for the rendered comics... or even the bootstrap to see where there may be a background-color being assigned to black (and also searched for hex code 000000), but didn't find one...
Then I found that it had to do with the way my thumbnailing script was resampling the png... Since I'm getting a black background for the supposedly transparent image, I blame imagecreatetruecolor() which returns an image identifier representing a black image of the specified size..
I tried following Cheekysoft's question here about preserving transparency after resampling... but it didn't work... with his two main points being:
imagealphablending( $targetImage, false );
imagesavealpha( $targetImage, true );
I found if I put $img = imagecreatefrompng($image_file); before I resize/resample it, it displays transparently... which is what I want... but not after I resample it.
Thumbnailer.php code:
<?php
#Appreciation goes to digifuzz (http://www.digifuzz.net) for help on this
$image_file = $_GET['img']; //takes in full path of image
$MAX_WIDTH = $_GET['mw'];
$MAX_HEIGHT = $_GET['mh'];
global $img;
//Check for image
if(!$image_file || $image_file == "") {
die("NO FILE.");
}
//If no max width, set one
if(!$MAX_WIDTH || $MAX_WIDTH == "") {
$MAX_WIDTH="100";
}
//if no max height, set one
if(!$MAX_HEIGHT || $MAX_HEIGHT == "") {
$MAX_HEIGHT = "100";
}
$img = null;
//create image file from 'img' parameter string
if( preg_match('/\.jpg$/',$image_file) || preg_match('/\.jpeg$/',$image_file) ){
$img = imagecreatefromjpeg($image_file);
} else {
$img = imagecreatefrompng($image_file);
}
//if image successfully loaded...
if($img) {
//get image size and scale ratio
$width = imagesx($img);
$height = imagesy($img);
//takes min value of these two
$scale = min($MAX_WIDTH/$width, $MAX_HEIGHT/$height);
//if desired new image size is less than original, output new image
if($scale < 1) {
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//copy and resize old image to new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//replace actual image with new image
$img = $tmp_img;
}
}
//set the content type header
header('Content-Type: image/png', true);
imagealphablending( $img, false );
imagesavealpha( $img, true );
imagepng($img);
imagedestroy($img);
?>
Can anyone help?
Thanks!
You need to call imagealphablending() on your destination image BEFORE you resample/resize the image:
//copy and resize old image to new image
imagealphablending($tmp_img, false);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// ...
You placed alphablending and traparent code well below after creating image. Just place them before the your createresample line and transparent image with image that created by imagecreatefrompng.
imagealphablending( $tmp_img, false );
imagesavealpha( $tmp_img, true );
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
Or you can Try following
$img = ImageCreateFromPNG($image_file);
$tmp_img = imagecreatetruecolor($new_width,$new_height);
imagecolortransparent($tmp_img, imagecolorallocate($tmp_img, 0, 0, 0));
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

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;
}

Creat temporay thumb image in PHP

Hey, i am looking for a method to creat temporay thumb file in PHP. Is there any way not to store the image on the server or delete them right after. What I am looking for is a solution like this: http://www.dig2go.com/index.php?shopbilde=772&type=1&size=120
Could some one explain to me how the php code behind this works? For the moment are am using a php code I found on the net for creation of thumb nails:
function createThumb($pathToImage, $pathToThumb, $thumbWidth, $thumbHeight, $saveNameAndPath)
{
if(!file_exists($pathToImage))
return false;
else
{
//Load image and size
$img = imagecreatefromjpeg($pathToImage);
$width = imagesx($img);
$height = imagesy($img);
//Calculate the size of thumb
$new_width = $thumbWidth;
$new_height = $thumbHeight; //floor($height * ($thumbWidth / $width));
//Make the new thumb
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//Copy the old image and calculate the size
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//Save the thumb to jpg
imagejpeg($tmp_img, $saveNameAndPath);
return true;
}
}
function createThumb($pathToImage, $pathToThumb, $thumbWidth, $thumbHeight, $saveNameAndPath)
{
if(!file_exists($pathToImage))
return false;
else
{
//Load image and size
$img = imagecreatefromjpeg($pathToImage);
$width = imagesx($img);
$height = imagesy($img);
//Calculate the size of thumb
$new_width = $thumbWidth;
$new_height = $thumbHeight; //floor($height * ($thumbWidth / $width));
//Make the new thumb
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//Copy the old image and calculate the size
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// sets the header and creates the temporary thumbnail
// ideal for ajax requests / <img> elements
header("Content-type: image/jpeg");
imagejpeg($img);
return true;
}
}
You can use ini_set("memory_limit","12M"); to set memory limit in your script. You can extend it from 12 megabytes to maximum memory you have.
Generally 64M is good.

Categories