So I have a function that turns a jpeg into a png image resizes it then saves it. Then a bit later i come back to it and use the image in a rotate function. I keep getting errors though. It says uploads/image.png isnt a valid PNG file. The weird thing is that it only does then on php edited png files. If i delete image.png and download a png from the internet name is image.png is works fine as long as i dont run it through the first resize script.
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$imagecreated = imagecreatefromjpeg($filename);
$this->image = $imagecreated;
$extention = pathinfo($filename, PATHINFO_EXTENSION);
$basename = basename($filename, ".".$extention);
$newname = "uploads/".$basename;
imagepng($imagecreated, $newname.".png", 0);
// ....???
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height,
$this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
Then i save the file with just a simple
imagepng(etc etc);
I go to the uploads folder and it looks fine. its resized and everything. I also noticed photoshop wont open the edited png either.
Also the line of code that produces the error is here..
$image = imagecreatefrompng('uploads/image.png');
Possible fix is to add a NULL for your filters parameter (the last parameter in imagepng)
ie.
imagepng($image,$file_location,0,NULL);
I can't say this should be needed, but I read a similar case where someone noted they had to do this, may be dependant on the version of libpng or gd lib.
Related
I'm having a hard time to make my web-application work properly. I have been trying to make my avatar not feel pushed and make it resize automatically when uploaded. I'm not the best with PHP hence why I can't do this on my own. I would appreciate if someone could help me out. That's the code of the file that is the avatar.
Best regards!
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
You'll require to store Uploaded Picture on your webserver
For that:
You'll Require:
move_uploaded_file()
and for resizing purpose you can use:
imagecopyresampled()
as follows:
function resizeIMG($o_img // original image
, $target_image // Resized New Image
, $newWidth, $newHeight){
// Get Original Dimensions as follows:
$original_width=imagesx($o_image); //Returns width of image
$original_height=imagesy($o_image); //Returns height of image
$tmp = imagecreatetruecolor($newWidth, $newHeight); // Create New temp. image with new dimensions
imagecopyresampled($tmp_img, $o_img, 0, 0, 0, 0, $newWidth, $newHeight, $original_width, $original_height); // Resize original image to temporary Image
imagejpeg($tmp, $target_image, $quality); // Copy temp Image to Target File for JPG images
imagedestroy($tmp); // Destroy Temporary Image.
/* Use
imagepng() instead of imagejpeg() for PNG images
imagegif() instead of imagejpeg() for GIF images
*/
}
For all these functions mentioned you'll need to enable gd_drivers for your php. By simply removing ; before line extension=php_gd2.dll if you're using windows or See this for others.
Or you can Use image_magick for php.
also do have a look at: Resize images in PHP without using third-party libraries?
hope it helps.. cheers :).
I'm attempting to add a function to my site where users can set their profile picture as an image from an external url, instead of saving it to their pc, then uploading it to my server.
This is what I've come up with so far:
$filename = $inputs['image_url'];
if(getimagesize($filename)){
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = 100;
$new_height = 100;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
//a check needs to be done here $image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$filename = "profile_pictures/". md5( uniqid(rand(),true) ).".jpg";
imagejpeg($image_p,$filename,100);
}else{
echo 'This is not an image';
}
The code can download .jpg images fine, but I want to support other filetypes too.
I need to somehow check the file type of the image so I can save other images with different filetypes...
if($extension=="jpg" || $extension=="jpeg"){
$image = imagecreatefromjpeg($filename);
}else if($extension=="png"){
image = imagecreatefrompng($filename);
}else{
$image = imagecreatefromgif($filename);
}
Does anyone know of a function that would allow me to do this?
Thanks in advance for any replies.
Most straight forward and for GD compatiblity checking you can just create it from string:
$image = imagecreatefromstring(file_get_contents($filename));
If this fails to load, you know that you can not process that image.
But see as well getimagesize, it inspects the filetype as well, not only width and height:
list($width, $height, $type) = getimagesize($filename);
The third element, $type, then is any of these IMAGETYPE_XXX constants:
Value Constant
1 IMAGETYPE_GIF
2 IMAGETYPE_JPEG
3 IMAGETYPE_PNG
4 IMAGETYPE_SWF
5 IMAGETYPE_PSD
6 IMAGETYPE_BMP
7 IMAGETYPE_TIFF_II (intel byte order)
8 IMAGETYPE_TIFF_MM (motorola byte order)
9 IMAGETYPE_JPC
10 IMAGETYPE_JP2
11 IMAGETYPE_JPX
12 IMAGETYPE_JB2
13 IMAGETYPE_SWC
14 IMAGETYPE_IFF
15 IMAGETYPE_WBMP
16 IMAGETYPE_XBM
17 IMAGETYPE_ICO
From exif_imagetype. If you combine both, you could first check if the type is okay to load for you and you then check if you can load it.
Splfileinfo::getextension.php might be just what you need.
Edit : I misread, you only want to check the extension of a string. There isn't built-in function for that in PHP, you can simply use a regexp :
$ext = substr(strrchr($fileName,'.'),1);
You can try of of this
$fileExtention = pathinfo ( $filename, PATHINFO_EXTENSION );
Or
$fileExtention = image_type_to_extension(exif_imagetype($filename));
Finally i would advice you use something like http://phpthumb.sourceforge.net/ is has more than what you need to manipulate images
I have this code that I have tried creating and don't know what I am doing wrong.
// SET ERROR FLAG
$error = false;
// MAKE SURE FILE IS AN IMAGE
if (!list($width, $height) = getimagesize($_FILES['avatar']['tmp_name'])) {
$error = true;
}
// MAKE SURE FILE COMES FROM FORM
if (!is_uploaded_file($_FILES['avatar']['tmp_name'])) {
$error = true;
}
// MAKE SURE FILESIZE IS NOT OVER 1MB
if (filesize($_FILES['avatar']['tmp_name']) > 1048576) {
$error = true;
}
// TARGER TO SAVE FILE AND CHANGE FILENAME AND FILE TYPE
$target = 'images/avatars/' . md5($user['id']) . '.gif';
// IMAGE RATIO AND RESIZING
$imgRatio = $width / $height;
if ($imgRatio > 1) {
$newWidth = 200;
$newHeight = 200 / $imgRatio;
} else {
$newWidth = 200 * $imgRatio;
$newHeight = 200;
}
$imgResized = imagecreatetruecolor($newWidth, $newHeight);
$newImg = imagecreatefromgif($_FILES['avatar']['tmp_name']);
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// SUCCESSFULL IMAGE UPLOAD
if (!$error && move_uploaded_file($newImg, $target)) {
echo '<p>Your avatar was uploaded successfully.</p>';
// ERROR UPLOADING IMAGE
} else {
echo '<p>There was an error uploading your avatar.</p>';
}
It always fails I cannot get the resizing to work, even a link to a good tutorial will suffice,
Happy new year!!
I think the problem is that you use GD to open the temporary image file:
$newImg = imagecreatefromgif($_FILES['avatar']['tmp_name']);
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
And then you try to move the temporary avatar file with move_uploaded_file without freeing GD resource and also discarding all the work done with GD (the resizing I mean, and I can add here you have to use resample instaead of resize method).
if (!$error && move_uploaded_file($newImg, $target)) {
The code moves the temporary uploaded file (currently opened by GD and however not physically altered by your GD work, so not resized) to the $target path.
Edit. Now I see more errors with your code. You cannot do:
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
Because imagecopyresized do not returns anything but true or false. It simply copy one portion of a source image to a different destination resource. It do not return a resource itself!
Finally. The correct workflow to the what you want to do is:
Check the uploaded file if it's ok for you (and you do it good, it seems).
Create a $img GD resource opening the uploaded file with imagecopyresized.
Create an empty destination resource $newImg with imagecreatetruecolor.
Resize or resample using imagecopyresized or imagecopyresampled to copy source image to destination resource.
Save destination resource into a GIF file using imagegif.
Discard temporary source uploaded image.
You can learn more googling something like php gd resize uploaded images. Tons of tutorial will be one click far from you.
The code itself looks alright, however there could be a number reasons why it fails. Some debug output would be helpful. Some general pointers:
check that the path for the tmp_name is set and readable
check your php settings for post_max_size, it may be set very low or not set at all.
in your code you are only handling gif type images (imagecreatefromgif), you may need to check for the filetype prior to reading from the image resource
check that GD is properly installed in your php installation (phpinfo(); in a php script or php -i from command line should display it as acticated)
That being sad, add some error messages to your output so we can help further.
I have a very simple PHP script which creates "favicon.ico" form jpg/gif/png uploaded file.
Here is a part of function:
$file = 'cache/'.$e .'/'. basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$im = imagecreatefromjpeg($file);
list($width, $height) = getimagesize($file);
$image_p = imagecreatetruecolor("16", "16");
imagecopyresampled($image_p, $im, 0, 0, 0, 0, "16", "16", $width, $height);
$num = rand (1,99999);
$output = $num."-favicon.ico";
imagepng($image_p,'dl/'.$output);
imagedestroy ($im);
unlink ($file);
echo 'success';
}
And script works fine! In Chrome, Opera and Firefox generated favicon displays good, as it should do.
But in Interent Explorer 8 - it simply doesn't show up.
Thank you for any help!
You can't just save it as a PNG with the ico extension... I'm guessing Chrome/Opera/Firefox can't read the file, so they decide to open up the file and find out what the actual format is rather than depending on the file extension, while IE doesn't.
However, you will need to find a different solution to save it as an ICO as GD can't do that on its own, you can either try ImageMagick or after a quick Google phpThumb seems to be able to do it (not tried).
I have a bunch of high quality PNG files. I want to use PHP to convert them to JPG because of it's smaller file sizes while maintaining quality. I want to display the JPG files on the web.
Does PHP have functions/libraries to do this? Is the quality/compression any good?
Do this to convert safely a PNG to JPG with the transparency in white.
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
Be careful of what you want to convert. JPG doesn't support alpha-transparency while PNG does. You will lose that information.
To convert, you may use the following function:
// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
$image = imagecreatefrompng($originalFile);
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
}
This function uses the imagecreatefrompng() and the imagejpeg() functions from the GD library.
This is a small example that will convert 'image.png' to 'image.jpg' at 70% image quality:
<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70);
imagedestroy($image);
?>
Hope that helps
<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {
$explode = explode(".", $imageName);
$filetype = $explode[1];
if ($filetype == 'jpg') {
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'png') {
$srcImg = imagecreatefrompng("$imageDirectory/$imageName");
} else
if ($filetype == 'gif') {
$srcImg = imagecreatefromgif("$imageDirectory/$imageName");
}
$origWidth = imagesx($srcImg);
$origHeight = imagesy($srcImg);
$ratio = $origWidth / $thumbWidth;
$thumbHeight = $origHeight / $ratio;
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);
if ($filetype == 'jpg') {
imagejpeg($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
imagejpeg($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'png') {
imagepng($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'gif') {
imagegif($thumbImg, "$thumbDirectory/$imageName");
}
}
?>
This is a very good thumbnail script =)
Here's an example:
$path = The path to the folder where the original picture is.
$name = The filename of the file you want to make a thumbnail of.
$thumbpath = The path to the directory where you want the thumbnail to be saved into.
$maxwidth = the maximum width of the thumbnail in PX eg. 100 (wich will be 100px).
createThumbnail($path, $name, $thumbpath, $maxwidth);
You might want to look into Image Magick, usually considered the de facto standard library for image processing. Does require an extra php module to be installed though, not sure if any/which are available in a default installation.
HTH.
PHP has some image processing functions along with the imagecreatefrompng and imagejpeg function. The first will create an internal representation of a PNG image file while the second is used to save that representation as JPEG image file.
See this list of php image libraries. Basically it's GD or Imagemagick.
I know it's not an exact answer to the OP, but as answers have already be given...
Do you really need to do this in PHP ?
What I mean is : if you need to convert a lot of images, doing it in PHP might not be the best way : you'll be confronted to memory_limit, max_execution_time, ...
I would also say GD might not get you the best quality/size ratio ; but not sure about that (if you do a comparison between GD and other solutions, I am very interested by the results ;-) )
Another approach, not using PHP, would be to use Image Magick via the command line (and not as a PHP extension like other people suggested)
You'd have to write a shell-script that goes through all .png files, and gives them to either
convert to create a new .jpg file for each .png file
or mogrify to directly work on the original file and override it.
As a sidenote : if you are doing this directly on your production server, you could put some sleep time between bunches of conversions, to let it cool down a bit sometimes ^^
I've use the shell script + convert/mogrify a few times (having them run for something like 10 hours one time), and they do the job really well :-)