How can I resize an image resource in PHP? - php

I have a script that creates an image whose height depends on the depth of a recursive tree. Precalculating the height of the image would be a pain, because I would need to run a recursive function twice. Thus, I wonder if it is possible to resize the image from inside my only recursive function. Long story short, I need to resize an image resource, is it possible? For instance, how can I make the following code work? Thanks!
//Create the image
$image = imagecreatetruecolor(800, 100);
//Change the image height from 100 to 1000 pixels
imagecopyresized($image, $image, 0, 0, 0, 0, 800, 1000, 800, 100);
//Set the header
header('Content-Type: image/png');
//Output the image
imagepng($image);
//Destroy the image
imagedestroy($image);

Your code is almost perfect, except you aren't giving it the source image to work with. You need $source = imagecreatefrompng("someimage.png");, and then in your imagecopyresize set the source image argument to $source.

Related

Convert any type of an image to PNG and add to PNG

I am trying to create an employee poster for a website that I develop. My goal is to take an image from a directory on the server of any file type (.png, .gif, .jpeg, etc.) and copy it onto another generate imaged that will then be outputted to the browser.
The problem is that I use:
$final_image = imagecreatefrompng("large_background.png");
for making the final image and for some reason if I add profile images with the type jpeg's, gif's, etc, (any type that isn't a jpeg) it doesn't work. The images never show up in the output. However, if I use png's it does work.
To solve this problem I tried converting the image to a png and then creating a png from it as shown in the code below. Unfortunately it doesn't work. Profile images still do not show up on the background.
// get image from database
$image_from_database = could be a .png, .jpeg, .gif, etc.
// get the image from the profile images directory
$path = "profile_images/".$image_from_database;
// create a png out of the image
$image = imagecreatefrompng(imagepng($path));
// add the $image to my larger $final_image (which is a png)
imagecopy($final_image, $image, $x, $y, 0,0, $height, $width);
imagepng($final_image, $ouput_url);
...
Can anybody tell me why this won't work? My profile images do not show up in the output of the final image.
My questions,
Is this line imagecreatefrompng(imagepng(...)); even possible? Essentially I want to convert an image of any type into a png and then create a png from it.
I'm just running a few local tests... The following works:
$src = imagecreatefromgif('test.gif');
$dest = imagecreatefrompng('test.png');
imagecopy($dest, $src, 0, 0, 0, 0, 100, 100);
header('Content-Type: image/png');
imagepng($dest);
imagedestroy($src);
imagedestroy($dest);
So does this:
$src = imagecreatefromstring(file_get_contents('test.gif'));
If you're still having trouble after trying the latter example, please update your question. The actual images you're using would be helpful, in addition to a functional code example.
After you read an image with a imagecreatefrom* function, it doesn't matter what format the original was.
imagecreatefrom* functions return an image resource. When the image is loaded you are using internal representation of the images and not PNG, JPEG or GIF images.
If the images are successfully loaded imagecopy should have no problems with them.
This code uses images in different formats and works without a problem:
$img = imagecreatefrompng('bg.png');
$png_img = imagecreatefrompng('img.png');
$jpeg_img = imagecreatefromjpeg('img.jpeg');
$gif_img = imagecreatefromgif('img.gif');
/* or use this, so you don't need to figure out which imagecreatefrom* function to use
$img = imagecreatefromstring(file_get_contents('bg.png'));
$png_img = imagecreatefromstring(file_get_contents('img.png'));
$jpeg_img = imagecreatefromstring(file_get_contents('img.jpeg'));
$gif_img = imagecreatefromstring(file_get_contents('img.gif'));
*/
imagecopyresampled($img, $png_img, 10, 10, 0,0, 100, 100, 200, 200);
imagecopyresampled($img, $jpeg_img, 120, 10, 0,0, 100, 100, 200, 200);
imagecopyresampled($img, $gif_img, 230, 10, 0,0, 100, 100, 200, 200);
header('Content-Type: image/png');
imagepng($img);
Your example
$image = imagecreatefrompng(imagepng($path));
is wrong.
imagepng is used to output an image resource as a PNG image. If you provide a path as a second argument a PNG image file is created, otherwise it's printed to the output like echo does.
What imagepng actually returns is a boolean, indicating, if the output was successful.
You are then passing that boolean to imagecreatefrompng which expects a filepath. This is obviously wrong.
I suspect you have a problem with loading images.
imagecreatefrom* functions return FALSE on failure and you should check, if you have any problems with that.
Maybe your image paths are relative to doc root and your working directory is different.
Or you have permission problem.
Or your images are just missing.
It's impossible to tell from your question.

imagecopyresized() returning black thumbnails

I posted earlier about another resizing script not working and I got a little farther with this script which does things a little differently.
I got a little farther, only now there is a new problem. The first three lines of the code successfully place three identical files in the target directory with the file and it's two thumbnail files named accordingly. I then want to load the thumbnails, which are still full-size, and resize them but the script stops at imagecreatefromjpeg() and I can't seem to figure out why because $src has a value.
I thought that I could possibly remove that line and replace $source with $src in my imagecopyresized() function, and that gets me even closer. But it then returns a thumbnail of the target size, but the thumbnail is black.
move_uploaded_file($tmpFilePath, $newFilePath);
copy($newFilePath, $thumb500);
copy($newFilePath, $thumb200);
function thumbImage($src, $dest, $newheight) {
list($width, $height) = getimagesize($src);
$newwidth = $width * ($newheight / $height);
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
header('Content-type: image/jpeg');
$source = imagecreatefromjpeg($src);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb, $dest);
}
thumbImage($thumb500, $thumb500, 500);
thumbImage($thumb200, $thumb200, 200);
I feel as if this must be a common issue. Any suggestions anyone?
For me the supplied code block works if I use a JPEG image as source.
The problem may be that you use a PNG image that uses transparency. As JPEG can not handle transparencies, the transparent background colour will be filled. Maybe that is the problem. If not, please provide a sample image that has the problematic behaviour.
5
imagecopyresized takes an image resource as its second parameter, not a file name. You'll need to load the file first. If you know the file type, you can use imagecreatefromFILETYPE to load it. For example, if it's a JPEG, use imagecreatefromjpeg and pass that the file name - this will return an image resource.
If you don't know the file type, all is not lost. You can read the file in as a string and use imagecreatefromstring (which detects file types automatically) to load it as follows:
{$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));
}
enter code here

Can i change image file size with php?

I made a small function to upload images then show them on my website.
My question is now, can I change the file size of a image, on same time as I upload it?
Take facebook as example. Even large images has a size on like 65kb.
If so, witch function should I use?
Thanks,
use the imagecopyresampled function:
$source_image = imagecreatefromjpeg("youtimagejpg");
$src_w= imagesx($source_image);
$src_h= imagesy($source_image);
$dest_image = imagecreatetruecolor(100, 100); //targeted width and height
imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, 100, 100, $source_w, $source_h);
imagejpeg($dest_image,NULL,80);
//Replace null by the path if you want to save on the server, otherwise the image will be sent to the client intead.
If you want to reduce the size of the image without resizing it; use the imagejpeg function (with a low quality factor)
There are next ways to change image size:
Convert to another image format.
Save image with lossy compression (http://en.wikipedia.org/wiki/Lossy_compression)
Resample image with another width & height (http://php.net/manual/en/function.imagecopyresampled.php)

PHP GD imagecreatefromstring discards transparency

I've been trying to get transparency to work with my application (which dynamically resizes images before storing them) and I think I've finally narrowed down the problem after much misdirection about imagealphablending and imagesavealpha. The source image is never loaded with proper transparency!
// With this line, the output image has no transparency (where it should be
// transparent, colors bleed out randomly or it's completely black, depending
// on the image)
$img = imagecreatefromstring($fileData);
// With this line, it works as expected.
$img = imagecreatefrompng($fileName);
// Blah blah blah, lots of image resize code into $img2 goes here; I finally
// tried just outputting $img instead.
header('Content-Type: image/png');
imagealphablending($img, FALSE);
imagesavealpha($img, TRUE);
imagepng($img);
imagedestroy($img);
It would be some serious architectural difficulty to load the image from a file; this code is being used with a JSON API that gets queried from an iPhone app, and it's easier in this case (and more consistent) to upload images as base64-encoded strings in the POST data. Do I absolutely need to somehow store the image as a file (just so that PHP can load it into memory again)? Is there maybe a way to create a Stream from $fileData that can be passed to imagecreatefrompng?
you can use this code :
$new = imagecreatetruecolor($width, $height);
// preserve transparency
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
imagepng($new);
imagedestroy($new);
It will make a transparent image for you. Good Luck !
Blech, this turned out to ultimately be due to a totally separate GD call which was validating the image uploads. I forgot to add imagealphablending and imagesavealpha to THAT code, and it was creating a new image that then got passed to the resizing code. Which should probably be changed anyway. Thanks very much to goldenparrot for the excellent method of converting a string into a filename.
Do I absolutely need to somehow store the image as a file (just so that PHP can load it into memory again)?
No.
Documentation says:
You can use data:// protocol from php v5.2.0
Example:
// prints "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');

Merge images in PHP - GIF and JPG

I am trying to merge two images - a GIF image with a smaller JPG image. The output should be GIF.
The issue is that GIF image colors remain correct, but the colors of the JPG image are altered.
The GIF image has only 256 colors (8-bit), but is there a way to make the merged image to be a true-color resource which later can be converted to a 8-bit GIF for output?
Issue solved.
I updated the code. Here is the solution which works fine:
<?php
header('Content-Type: image/gif');
$gif_address = 'file.gif';
$jpg_address = 'file.jpg';
$image1 = imagecreatefromgif($gif_address);
$image2 = imagecreatefromjpeg($jpg_address);
$merged_image = imagecreatetruecolor(800, 800);
imagecopymerge($merged_image, $image1, 0, 0, 0, 0, 800, 800, 100);
imagecopymerge($merged_image, $image2, 0, 0, 0, 0, 500, 500, 100);
imagegif($merged_image);
imagedestroy($image1);
imagedestroy($image2);
imagedestroy($merged_image);
?>
From your explanation (some code would help), i would hazard a guess you are merging the jpeg onto the gif. Id say the easiest way is to use imageCreateTrueColor to create a new image the size you need then use imagecopy to copy the GIF into this new image. Merge the jpg onto this and then at a later date you can covert the true colour image to a gif.
If im missing something a bit of example code of what you are currently doing might help.

Categories