Imagick making animated gifs not animated? - php

I'm sending imagick an image and when it is an animated gif it removes the animation and leaves on a single still. Is this because of the resize code? Or is it something inherent in the imagick library? Below is my code, what is wrong here?
if (isset($_FILES["image"])) {
$allowed_ext = array("jpg", "jpeg", "png", "gif");
$file_name = $_FILES["image"]["name"];
$file_ext = strtolower(end(explode(".", $file_name)));
$file_size = $_FILES["image"]["size"];
$file_tmp = $_FILES["image"]["tmp_name"];
// verify extension
if (in_array($file_ext, $allowed_ext) && $file_size < 2097152) {
// check if image needs scaling
$img = new imagick($file_tmp);
$img_size = $img->getImageGeometry();
$partyCommentErrors .= "<li>Width: ".$img_size["width"]." | Height: ".$img_size["height"]."</li>";
if ($img_size["width"] > 600 || $img_size["height"] > 600) {
// resize image
$img->resizeImage(600, 600, imagick::FILTER_LANCZOS, 0.9, true);
}
$img_size = $img->getImageGeometry();
$img->writeImage("imgs/commentpics/".$id.".".$file_ext);
// update database
$qry = "UPDATE comments SET thereisimg=1, imgtype='".$file_ext."', imgwidth='".$img_size["width"]."', imgheight='".$img_size["height"]."' WHERE id=$id";
mysqli_query($dblink, $qry);
} else {
$partyCommentErrors .= "<li>File type must be jpg, jpeg, png, or gif</li><li>File size must be less than 2 megabytes.</li>";
}
}

Because animated gifs are not stored as full images, but instead are stored as the differences between the frames of the animation, you need to call Imagick::coalesceImages to be able to modify the images contained in the Gif.
After modifying them, you then need to call Imagick::deconstructImages to generate the new set of differences between the frames, to be able to save them out as an animated Gif.
<?php
$imagick = new Imagick("original.gif");
$format = $imagick->getImageFormat();
if ($format == 'GIF') {
$imagick = $imagick->coalesceImages();
do {
$imagick->resizeImage(120, 120, Imagick::FILTER_BOX, 1);
} while ($imagick->nextImage());
$imagick = $imagick->deconstructImages();
$imagick->writeImages('new_120x120.gif', true);
// can be added some more gifs
$imagick = $imagick->coalesceImages();
do {
$imagick->resizeImage(100, 100, Imagick::FILTER_BOX, 1);
} while ($imagick->nextImage());
$imagick = $imagick->deconstructImages();
$imagick->writeImages('new_100x100.gif', true);
}
$imagick->clear();
$imagick->destroy();
Or, more briefly:
<?php
$image = new Imagick($file_src);
$image = $image->coalesceImages();
foreach ($image as $frame) {
$frame->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
$frame->thumbnailImage($size_w, $size_h);
$frame->setImagePage($size_w, $size_h, 0, 0);
}
$image = $image->deconstructImages();
$image->writeImages($file_dst, true);
?>

Related

How can I create custom thumbnails using php gd

i wanted to create a thumbnail with specific custom width & height. The function am using only create a thumbnail with a maximum set width/height.
How do i tweak the below function to give me a defined width/height e.g 50x50, 75x75, 100x100.
$original_photo = "photos/photo.extension";
$newcopy = "photos/thumbnails/photo.extension";
$copy_w = 50;
$copy_h = 50;
$extension = explode('.', 'photo.extension');
$extension = end($extension);
function create_thumbnail($original_photo, $newcopy, $copy_w, $copy_h, $extension) {
list($original_w, $original_h) = getimagesize($original_photo);
$scale_ratio = $original_w / $original_h;
if (($copy_w / $copy_h) > $scale_ratio) {
$copy_w = $copy_h * $scale_ratio;
} else {
$copy_h = $copy_w / $scale_ratio;
}
$img = '';
if ($extension == 'gif') {
$img = imagecreatefromgif($original_photo);
} elseif ($extension == 'png') {
$img = imagecreatefrompng($original_photo);
} else {
$img = imagecreatefromjpeg($original_photo);
}
$true_color = imagecreatetruecolor($copy_w, $copy_h);
imagecopyresampled($true_color, $img, 0, 0, 0, 0, $copy_w, $copy_h, $original_w, $original_h);
if (imagejpeg($true_color, $newcopy, 80) == true) {
return true;
} else {
return false;
}
}
Working with images in PHP/GD can be a pain. There are a lot of edge cases, particularly when transparent PNG/GIFs are manipulated.
If possible, I shamelessly recommend a library I wrote to handle things like this: SimpleImage 3.0
Using SimpleImage, you can achieve the desired effect with the following code:
// Load the image from image.jpg
$image = new \claviska\SimpleImage('image.jpg');
// Create a 50x50 thumbnail, convert to PNG, and write to thumbnail.png
$image->thumbnail(50, 50)->toFile('thumbnail.png', 'image/png');
See this page for more details on how the thumbnail method works and available arguments.

PNG files won't upload

I have the following script that I use to upload pictures; This file works with every other file extension except for PNG files. Is there any reason?
This is my script;
// initialization
$result_final = "";
$counter = 0;
// List of our known photo types
$known_photo_types = array(
'image/pjpeg' => 'jpg',
'image/jpeg' => 'jpg',
'image/gif' => 'gif',
'image/bmp' => 'bmp',
'image/x-png' => 'png');
// GD Function Suffix List
$gd_function_suffix = array(
'image/pjpeg' => 'JPEG',
'image/jpeg' => 'JPEG',
'image/gif' => 'GIF',
'image/bmp' => 'WBMP',
'image/x-png' => 'PNG');
// Fetch the photo array sent by preupload.php
$photos_uploaded = $_FILES['photo_filename'];
// Fetch the photo caption array
$photo_caption = $_POST['photo_caption'];
while( $counter <= count($_FILES['photo_filename']['tmp_name']) )
{
if($photos_uploaded['size'][$counter] > 0)
{
if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types))
{
$result_final .= "File ".($counter+1)." is not a photo!<br />";
}else{
mysql_query( "INSERT INTO database(`filename`, `caption`, `category`, `id`) VALUES('0', '".addslashes($caption[$counter])."', '".addslashes($_POST['category'])."', '".addslashes($_POST['id'])."')" );
$new_id = mysql_insert_id();
$filetype = $photos_uploaded['type'][$counter];
$extention = $known_photo_types[$filetype];
$filename = $new_id.".".$extention;
#mysql_query( "UPDATE database SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" );
// Store the orignal file
copy($photos_uploaded['tmp_name'][$counter], $images_dir2."/".$filename);
// Let's get the original image size
$size = GetImageSize( $images_dir2."/".$filename );
// .................................................................................
// Lets resize the image if its width is greater than 500 pixels
// Resized image settings
if ($size[0] > '1'){
$Config_width_wide = 800; // width of wide image
$Config_height_wide = 800; // height of wide image
$Config_width_tall = 800; // width of tall image
$Config_height_tall = 800; // height of tall image
// The Code
if($size[0] > $size[1]){
$image_width = $Config_width_wide;
$image_height = (int)($Config_width_wide * $size[1] / $size[0]);
if($image_height > $Config_height_wide){
$image_height = $Config_height_wide;
$image_width = (int)($Config_height_wide * $size[0] / $size[1]);
}
}else{
$image_width = (int)($Config_height_tall * $size[0] / $size[1]);
$image_height = $Config_height_tall;
if($image_width > $Config_width_tall){
$image_width = $Config_width_tall;
$image_height = (int)($Config_width_tall * $size[1] / $size[0]);
}
}
// Build image with GD 2.x.x, you can use the other described methods too
$function_suffix = $gd_function_suffix[$filetype];
$function_to_read = "ImageCreateFrom".$function_suffix;
$function_to_write = "Image".$function_suffix;
// Read the source file
$source_handle = $function_to_read ( $images_dir2."/".$filename );
if($source_handle){
// Let's create a blank image for the image
$destination_handle = ImageCreateTrueColor ( $image_width, $image_height );
// Now we resize it
ImageCopyResampled( $destination_handle, $source_handle, 0, 0, 0, 0, $image_width, $image_height, $size[0], $size[1] );
}
// Store the orignal file
copy($photos_uploaded['tmp_name'][$counter], $images_dir2."/".$filename);
// Let's save the image
if ($extension == 'png') {
$function_to_write( $destination_handle, $images_dir2."/".$filename, 9 );
} else {
$function_to_write( $destination_handle, $images_dir2."/".$filename, 90 );
}
ImageDestroy($destination_handle );
}
}
}
$counter++;
}
} else exit('<p>Error: ' .
mysql_error() . '</p>');
Thats my code and everything works fine when I upload a jpeg or gif file but when I upload a png file, it doesn't work. I don't get no error neither. Please, what could be the error?
Merely change it to:
image/png
png is an officially recognized mime type, it should be just image/png. the x- prefix is for experimental/unofficial types. You could trivially verify what you're getting with var_dump($_FILES).
Your upload handling code also needs updates. You do not check for successful uploads, and simply assume they succeeded. NEVER assume success.
if($_FILES['photo_filename']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['photo_filename']['error']);
}
addslashes() is utterly useless pointless garbage. It does NOTHING to protect you against sql injection attacks. If you insist on continuing to use the deprecated mysql_*() functions, then at least use the proper mysql_real_escape_string().

How can I allow other image formats to be uploaded

This is the code that uploads users logo's I was wondering if anyone could help me.
I want to be able to allow users to upload .png and .gif files too.
Sorry if this is a simple fix but I am very new to php.
<?
//edit logo
function resize_image ($image) {
$imgsize = getimagesize($image);
//check for gallery type to determine thumbnail size
$size_x = 150;
$ratio = 150 / $imgsize[0];
$size_y = $imgsize[1] * $ratio;
$srcimage = ImageCreateFromjpeg ($image);
$newimage = ImageCreateTrueColor($size_x,$size_y);
//$newimage = imagecreate ($size_x, $size_y);
imagecopyresized ($newimage, $srcimage, 0, 0, 0, 0, $size_x, $size_y,
imagesx($srcimage), imagesy($srcimage));
return $newimage;
}
$myrepairer = new repairer;
//resize and upload image
$file = $_FILES['logo']['tmp_name'];
$file_name = $_FILES['logo']['name'];
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.jpg')) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.jpg');
unlink('logos/'.$_REQUEST['id'].'.jpg');
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.jpg');
}
$resultmessage = '<div align="center" class="GreenText">Logo Updated</div>';
You can just get the file extension and use it instead of '.jpg'.
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
So, it'll be something like:
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.'.$ext)) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.'.$ext);
unlink('logos/'.$_REQUEST['id'].'.'.$ext);
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.'.$ext);

How can I convert all images to jpg?

I have script:
<?php
include('db.php');
session_start();
$session_id = '1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if (strlen($name)) {
list($txt, $ext) = explode(".", $name);
if (in_array($ext, $valid_formats)) {
if ($size < (1024 * 1024)) { // Image size max 1 MB
$actual_image_name = time() . $session_id . "." . $ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if (move_uploaded_file($tmp, $path . $actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/" . $actual_image_name . "' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} else {
echo "Please select image..!";
}
exit;
}
?>
Is possible convert all images (png, gif etc) to jpg with 100% quality? If yes, how? I would like allow to upload png and gif, but this script should convert this files to jpg. Is possible this with PHP?
Try this code: originalImage is the path of... the original image... outputImage is self explaining enough. Quality is a number from 0 to 100 setting the output jpg quality (0 - worst, 100 - best)
function convertImage($originalImage, $outputImage, $quality)
{
// jpg, png, gif or bmp?
$exploded = explode('.',$originalImage);
$ext = $exploded[count($exploded) - 1];
if (preg_match('/jpg|jpeg/i',$ext))
$imageTmp=imagecreatefromjpeg($originalImage);
else if (preg_match('/png/i',$ext))
$imageTmp=imagecreatefrompng($originalImage);
else if (preg_match('/gif/i',$ext))
$imageTmp=imagecreatefromgif($originalImage);
else if (preg_match('/bmp/i',$ext))
$imageTmp=imagecreatefrombmp($originalImage);
else
return 0;
// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);
return 1;
}
Try using Imagick setImageFormat, for me it provides the best image quality
http://php.net/manual/en/imagick.setimageformat.php
$im = new imagick($image);
// convert to png
$im->setImageFormat('png');
//write image on server
$im->writeImage($image .".png");
$im->clear();
$im->destroy();
Davide Berra's answer is great, so I improved the file type detection a little, using exif_imagetype() instead of relying on the file extension:
/**
* Auxiliar function to convert images to JPG
*/
function convertImage($originalImage, $outputImage, $quality) {
switch (exif_imagetype($originalImage)) {
case IMAGETYPE_PNG:
$imageTmp=imagecreatefrompng($originalImage);
break;
case IMAGETYPE_JPEG:
$imageTmp=imagecreatefromjpeg($originalImage);
break;
case IMAGETYPE_GIF:
$imageTmp=imagecreatefromgif($originalImage);
break;
case IMAGETYPE_BMP:
$imageTmp=imagecreatefrombmp($originalImage);
break;
// Defaults to JPG
default:
$imageTmp=imagecreatefromjpeg($originalImage);
break;
}
// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);
return 1;
}
You must have php_exif extension enabled to use this.
A small code to convert image.png to image.jpg at desired image quality:
<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70); // 0 = worst / smaller file, 100 = better / bigger file
imagedestroy($image);
?>
a small fix to davide's answer, the correct function for converting from BMP is "imagecreatefromwbmp" instead of imagecreatefrombmp (missing "w")
also you should consider that png may be transparent, here is a way to fill it with white BG (jpeg can't apply alpha data).
function convertImage($originalImage, $outputImage, $quality){
// jpg, png, gif or bmp?
$exploded = explode('.',$originalImage);
$ext = $exploded[count($exploded) - 1];
if (preg_match('/jpg|jpeg/i',$ext)){$imageTmp=imagecreatefromjpeg($originalImage);}
else if (preg_match('/png/i',$ext)){$imageTmp=imagecreatefrompng($originalImage);}
else if (preg_match('/gif/i',$ext)){$imageTmp=imagecreatefromgif($originalImage);}
else if (preg_match('/bmp/i',$ext)){$imageTmp=imagecreatefromwbmp($originalImage);}
else { return false;}
// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);
return true;
}
From PhpTools:
/**
* #param string $source (accepted jpg, gif & png filenames)
* #param string $destination
* #param int $quality [0-100]
* #throws \Exception
*/
public function convertToJpeg($source, $destination, $quality = 100) {
if ($quality < 0 || $quality > 100) {
throw new \Exception("Param 'quality' out of range.");
}
if (!file_exists($source)) {
throw new \Exception("Image file not found.");
}
$ext = pathinfo($source, PATHINFO_EXTENSION);
if (preg_match('/jpg|jpeg/i', $ext)) {
$image = imagecreatefromjpeg($source);
} else if (preg_match('/png/i', $ext)) {
$image = imagecreatefrompng($source);
} else if (preg_match('/gif/i', $ext)) {
$image = imagecreatefromgif($source);
} else {
throw new \Exception("Image isn't recognized.");
}
$result = imagejpeg($image, $destination, $quality);
if (!$result) {
throw new \Exception("Saving to file exception.");
}
imagedestroy($image);
}

PHP: Making thumbnail, why do i get these errors?

When i made this function:
function makeThumbnail($type, $name, $size, $tmp_name, $thumbSize) {
//make sure this directory is writable!
$path_thumbs = "uploaded_files/";
//the new width of the resized image, in pixels.
$img_thumb_width = $thumbSize; //
$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
//List of allowed extensions if extlimit = yes
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");
//the image -> variables
$file_type = $type;
$file_name = $name;
$file_size = $size;
$file_tmp = $tmp_name;
//check if you have selected a file.
echo $file_tmp."<br>";
echo $file_name."<br>";
echo $file_type."<br>";
echo $file_size."<br>";
if(!is_uploaded_file($file_tmp)){
echo "Error: Please select a file to upload!. <br>--back";
exit(); //exit the script and don't process the rest of it!
}
//check the file's extension
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
//uh-oh! the file extension is not allowed!
if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
echo "Wrong file extension. <br>--back";
exit();
}
//so, whats the file's extension?
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//create a random file name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//the new width variable
$ThumbWidth = $img_thumb_width;
/////////////////////////////////
// CREATE THE THUMBNAIL //
////////////////////////////////
//keep image type
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//list the width and height and keep the height ratio.
list($width, $height) = getimagesize($file_tmp);
//calculate the image ratio
$imgratio=$width/$height;
if ($imgratio>1){
$newwidth = $ThumbWidth;
$newheight = $ThumbWidth/$imgratio;
}else{
$newheight = $ThumbWidth;
$newwidth = $ThumbWidth*$imgratio;
}
//function for resize image.
if (function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($newwidth,$newheight);
}else{
die("Error: Please make sure you have GD library ver 2+");
}
//the resizing is going on here!
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//finally, save the image
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
//ok copy the finished file to the thumbnail directory
// move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
/*
Don't want to copy it to a separate directory?
Want to just display the image to the user?
Follow the following steps:
2. Uncomment this code:
/*
/* UNCOMMENT THIS IF YOU WANT */
echo "OK THUMB " . $thumbSize;
exit();
//*/
//and you should be set!
//success message, redirect to main page.
$msg = urlencode("$title was uploaded! Upload More?");
}
Then it stopped working, but outside a function, it works good.
As you can see i added "echo $file...." because i wanted to see if they have value, and they do have the right values.
I just get the error Error: Please select a file to upload.
This function is running after an normal upload image script(full size).
When i call the function i do:
makeThumbnail($_FILES[$fieldname]['type'], $_FILES[$fieldname]['name'], $_FILES[$fieldname]['size'], $_FILES[$fieldname]['tmp_name'], 100);
At my other file where its not in a function, theres no difference only that the variables is:
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
But it should work, I cant find anything wrong, but it doesnt and i keep getting that error. If i remove the is_uploaded_file function, i get a bunch of another errors.
Make sure you are not using move_uploaded_file() before calling the function.
I use timthumb to process the image into a thumbnail when it outputs it to screen, instead of when it's uploaded.
It means you only have one file and not one master size and one thumb size. TimThumb reduces the size of the file on serverside so it appears nice and smooth on the browserside. Have a look at it: TimThumb Link

Categories