PHP GD - Merge multiple images in tiled layout - php

I'm working on a class that takes an array of images by src and merges them into a single tiled image, similar to the following image;
The only issue is the images provided to the class aren't of set dimensions like in the image above.
The following state of the class creates a vertically stacked list of the images without gaps (an example shown below), and calculates the required height of the export image automatically (calculated in $total_height).
I imagine gaps are inevitable in the final output one way or another due to the infinite variation in image dimensions, but I'm not sure where to start in incorporating tiling horizontally as well as vertically.
class BoardCreator {
private $_img_type;
private $_img_urls = array();
public function __construct($img_export_type, array $img_urls) {
$this->_img_type = $img_export_type; // File format for exported image
$this->_img_urls = $img_urls; // Array of image URLs
}
public function GenerateBoard() {
/*
* Arrays to hydrate with loaded image properties & resources
*/
$images = array(); // Image resources
$width = array(); // Image widths
$height = array(); // Image heights
$total_height = 0; // Total height required for the board
/*
* Load in each image, and store its width & height
*/
for ($i=0; $i < count($this->_img_urls); $i++) {
switch (exif_imagetype($this->_img_urls[$i])) {
case IMAGETYPE_JPEG :
$images[$i] = imagecreatefromjpeg($this->_img_urls[$i]);
break;
case IMAGETYPE_PNG :
$images[$i] = imagecreatefrompng($this->_img_urls[$i]);
break;
case IMAGETYPE_GIF :
$images[$i] = imagecreatefromgif($this->_img_urls[$i]);
break;
// default w/ error required
}
// Store the image's dimensions
list($width[$i], $height[$i]) = getimagesize($this->_img_urls[$i]);
// Add this image's height to the required canvas height
$total_height = $total_height + $height[$i];
}
/*
* Create a new "canvas" image with specified dimensions
*/
$canvas_image = imagecreatetruecolor($width[0], $total_height);
/*
* Copy each image into the "canvas" image generated above
*/
$current_x = 0;
$current_y = 0;
for ($i=0; $i < count($images); $i++) {
imagecopy(
$canvas_image, // destination image
$images[$i], // source image
0, // x co-ordinate of destination
$current_y, // y co-ordinate of destination
0, // x co-ordinate of source
0, // y co-ordinate of source
$width[$i], // source img width
$height[$i] // source img height
);
$current_y = $current_y + $height[$i];
}
/*
* Save the resulting image in the format specified at initiation
*/
switch ($this->_img_type) {
case "jpg" :
$images[$i] = imagejpeg($canvas_image, "../board_exports/test.jpg");
break;
case "png" :
$images[$i] = imagepng($canvas_image, "../board_exports/test.png");
break;
case "gif" :
$images[$i] = imagegif($canvas_image, "../board_exports/test.gif");
break;
default :
// Create an error to handle here
die("Error in BoardCreator.php (Method GenerateBoard() )");
break;
}
/*
* Release the created image from memory
*/
imagedestroy($canvas_image);
/*
* Loop through and release each loaded image
*/
for ($i=0; $i < count($this->_img_urls); $i++) {
imagedestroy($images[$i]);
}
}

i made this code to help you.
1.- to fix "the infinite variation in image dimensions" i make thumbnails of images with this function:
function generate_image_thumbnail($source_image_path, $thumbnail_image_path,$THUMBNAIL_IMAGE_MAX_WIDTH,$THUMBNAIL_IMAGE_MAX_HEIGHT)
{
$condicion = GetImageSize($source_image_path); // image format?
if($condicion[2] == 1) //gif
$original = imagecreatefromgif("$source_image_path");
if($condicion[2] == 2) //jpg
$original = imagecreatefromjpeg("$source_image_path");
if($condicion[2] == 3) // png
$original = imagecreatefrompng("$source_image_path");
$thumb = imagecreatetruecolor($THUMBNAIL_IMAGE_MAX_WIDTH,$THUMBNAIL_IMAGE_MAX_HEIGHT);
$ancho = imagesx($original);
$alto = imagesy($original);
imagecopyresampled($thumb,$original,0,0,0,0,$THUMBNAIL_IMAGE_MAX_WIDTH,$THUMBNAIL_IMAGE_MAX_HEIGHT,$ancho,$alto);
imagejpeg($thumb,$thumbnail_image_path,90);
return true;
}
2.- create an image to paste the thumbnails
$size_image=460;
$img_disp = imagecreatetruecolor($size_image,$size_image);
$backcolor = imagecolorallocate($img_disp,0,0,0);
imagefill($img_disp,0,0,$backcolor);
3.- start to paste the thumbnails
//$THUMBNAIL_IMAGE=150;
$images_by_side = round($size_image/$THUMBNAIL_IMAGE); // round(460/150)=3 3 images by side
$separator = $size_image%$THUMBNAIL_IMAGE; //150*3=450... so 10px in total of space
$space_btwen_images=$separator/($images_by_side+1); //10px / 3 of total images + 1 =2,5
$total_image = pow($images_by_side , 2 ); //total images to paste (images by side)^2.. 3^2=9
//some math calculations to make more nice the output image
$dst_x=$space_btwen_images;
$cont_imgs=0;
for($x=0;$x<$total_image;$x++) {
if($cont_imgs == $images_by_side){
$dst_x=$dst_x+$THUMBNAIL_IMAGE+$space_btwen_images;
$cont_imgs=0;
}
$dst_y=$cont_imgs*$THUMBNAIL_IMAGE+($space_btwen_images * ($cont_imgs+1));
$cont_imgs++;
$thumb_image=$img_tmb_dir.$arr_img[$x]; //image to paste
$condicion = GetImageSize($thumb_image); // image format?
if($condicion[2] == 1) // gif
$image_to_copy = imagecreatefromgif("$thumb_image");
if($condicion[2] == 2) // jpg
$image_to_copy = imagecreatefromjpeg("$thumb_image");
if($condicion[2] == 3) // png
$image_to_copy = imagecreatefrompng("$thumb_image");
echo "dst_x=".$dst_x."; dst_y=".$dst_y.";<br>";
//output to check the destinations of the images to paste
/*
dst_x=2.5; dst_y=2.5;
dst_x=2.5; dst_y=155;
dst_x=2.5; dst_y=307.5;
dst_x=155; dst_y=2.5;
dst_x=155; dst_y=155;
dst_x=155; dst_y=307.5;
dst_x=307.5; dst_y=2.5;
dst_x=307.5; dst_y=155;
dst_x=307.5; dst_y=307.5;
*/
imagecopy($img_disp, $image_to_copy, $dst_x, $dst_y, 0, 0, $THUMBNAIL_IMAGE, $THUMBNAIL_IMAGE);
}
imagejpeg($img_disp, "test3.jpg",90);
imageDestroy($img_disp);
echo '<img src="test3.jpg"/>';
4.-
with my images (150 x 150) and $size_image=460; will return
and $size_image=610 will return

Related

change colors in an animated gif in php

Is there any working example how to read an animated gif, change color of any pixel in any frame of it using GD library or ImageMagick and save it as an animated gif again?
I have been googling for it for 2 days and I did not found answer anywhere.
Edit:
I have almost perfect solution. But some transparent (animated) gifs do not retain its transparency correctly (only part of the transparency is corrupted).
Source:
One of the wrong images: http://commons.wikimedia.org/wiki/File:Animation30.gif
GifFrameExtractor class: https://github.com/Sybio/GifFrameExtractor
GIFEncoder class: http://www.phpclasses.org/package/3163-PHP-Generate-GIF-animations-from-a-set-of-GIF-images.html
require_once('GIFEncoder.class.php');
require_once('GifFrameExtractor-master/src/GifFrameExtractor/GifFrameExtractor.php');
$gifFilePath = "input.gif";
// check this is an animated GIF
if (!\GifFrameExtractor\GifFrameExtractor::isAnimatedGif($gifFilePath)) {
\die('not an namiated image');
}
$gfe = new \GifFrameExtractor\GifFrameExtractor();
$gfe->extract($gifFilePath);
// frames as a GD source
$frameImages = $gfe->getFrameImages();
$frameDurations = $gfe->getFrameDurations();
// color used as a transparent color, if any
$tColor = array('red' => -1,'green'=>-1,'blue'=>-1);
foreach($frameImages as $i => $gdSource) {
// do something with gdSource
colorize($gdSource);
if($i == 0) {
//get the color used as transparent
// should be for any frame the same
$tColor = getTransparentColor($gdSource);
}
//GIFEncoder works only with binary data or files
//It cant work with gd source
//Therfore i output the gd source to stdout, catch it
//and use it as binary data.
//It could be memory consuming, so you might write the
//frames as a file and then use them instead of binary data.
\ob_start(); // catch output
\imagegif($gdSource); // write binary data to output
$frameImages[$i] = \ob_get_contents(); //replace GD source by the binary data
\ob_end_clean();
}
// create animated gif
$gif = new \GIFEncoder(
$frameImages, //binary data (or path to images on file system)
$frameDurations,
0, // infinite loop
2, // dont know what is this for (number 0-3 or -1 to ignore)
$tColor['red'], $tColor['green'], $tColor['blue'],
'bin' // or 'url' if $frameImages is array of paths to images on file system
);
// write image to file system
\FWrite ( \FOpen ( "output.gif", "wb" ), $gif->GetAnimation ( ) );
// send image to browser
//Header ( 'Content-type:image/gif' );
//echo $gif->GetAnimation ( );
//helpful function
/**
* Make grayscale color
* #param $color array('red'=>,'green'=>,'blue'=>);
* #return array('red'=>,'green'=>,'blue'=>);
*/
function transformColor($color) {
$gst = $color['red']*0.15+$color['green']*0.5+$color['blue']*0.35;
$color['red'] = $color['green'] = $color['blue'] = $gst;
return $color;
}
//helpful function
/**
* Get the transparent color from GD resource.
* If no tranpsarent color, all returned RGB values are -1
* #param $rs GD resource
* #return array('red'=>,'green'=>,'blue'=>)
*/
function getTransparentColor($rs) {
$transparentIndex = \ImageColorTransparent($rs);
$transparentColor = NULL;
if ($transparentIndex >= 0 && $transparentIndex < \ImageColorsTotal($rs)) {
$transparentColor = #\ImageColorsForIndex($rs, $transparentIndex);
}
return $transparentColor ? $transparentColor : array('red' => -1,'green'=>-1,'blue'=>-1);
}
// transform the GD resource with transparency
// there is probably problem,because if I save frames alone, they have the problem with transparency described above
function colorize($rs) {
assert('gd' === \get_resource_type($rs));
// you might want to create copy of the source here
// (instead of resource alias)
$bild = $rs;
//width
$x = \imagesx($bild);
// height
$y = \imagesy($bild);
$transparentIndex = \ImageColorTransparent($rs);
$transparentColor = NULL;
if ($transparentIndex >= 0 && $transparentIndex < \ImageColorsTotal($bild)) {
$transparentColor = #\ImageColorsForIndex($rs, $transparentIndex);
}
\ImageSaveAlpha($bild, TRUE);
\ImageAlphaBlending($bild, FALSE);
$transparentNewIndex = NULL;
$transparentNewColor = NULL;
if (!empty($transparentColor)) {
$transparentIndexNew = \ImageColorAllocate($bild, 255, 0, 255);
\ImageColorTransparent($bild, $transparentIndexNew);
$transparentColorNew = #ImageColorsForIndex($bild, transparentIndexNew);
}
// transform pixels
for ($i = 0; $i < $y; $i++) {
for ($j = 0; $j < $x; $j++) {
$index = \imagecolorat($rs, $j, $i);
$color = \imagecolorsforindex($rs, $index);
if ($index === $transparentIndex) {
$col = $transparentIndexNew;
} else {
$rgb = transformColor($color);
//TODO: we have a problem here, if $rgb ~= $transparentColorNew,
// then this pixel will be transparent and not the desired color
$col = \imagecolorresolvealpha($bild, $rgb['red'], $rgb['green'], $rgb['blue'], intval($color['alpha']));
if($col == $transparentIndexNew) {
//TODO: fix the color not to be transparent
// it do not die with the example gif
//die('This might be a problem, but not the problem describlet above this example');
}
}
\imagesetpixel($bild, $j, $i, $col);
}
}
return $bild;
}
I believe that an animated GIF has multiple frames, so the algorithm for this would be to read the gif as multiple frames, change the pixel colours in each frame, and then save it again. Are you able to load an animated gif in GD?
Perhaps this library can help you to write the GIF image back: http://www.phpclasses.org/package/3163-PHP-Generate-GIF-animations-from-a-set-of-GIF-images.html
$file = "yourImage.gif";
$im = imagecreatefromgif ($file);
$index = imagecolorclosest ( $im, 255,255,255 ); // get your color (rgb)
imagecolorset($im,$index,92,92,92); // set new color (rgb)
$file= "yourResult.gif";
imagegif($im, $file); // save image as gif
imagedestroy($im);
I'm not sure if this works with a animated gif.

Resize image before uploading PHP

I have no idea how to resize image in PHP, my code is:
for ($index = 1; $index <= 2; $index++) {
if (!empty($_FILES["pic$index"]["name"])) {
$ext = substr($_FILES["pic$index"]["name"], strrpos($_FILES["pic$index"]["name"], '.') + 1);
$dir = "../gallery/$mkdir";
HERE I NEED THE RESIZE OF THE TMP FILE OF IMAGE
move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext");
}
}
$mkdir = the name of the gallery's folder (there are many galleries).
$dir = where the pics will be placed.
$ext = the type of the image (png, gif or jpg).
foreach loop runs two times because you can upload two pics.
This script is working good, I just need to do resize and I dont have an idea how to do it..
Here is the code I'm using to resize images.
In my case I give to the function the original file name and then the thumbnail file name.
You can adapt it for your case very easily.
public static function GenerateThumbnail($im_filename,$th_filename,$max_width,$max_height,$quality = 0.75)
{
// The original image must exist
if(is_file($im_filename))
{
// Let's create the directory if needed
$th_path = dirname($th_filename);
if(!is_dir($th_path))
mkdir($th_path, 0777, true);
// If the thumb does not aleady exists
if(!is_file($th_filename))
{
// Get Image size info
list($width_orig, $height_orig, $image_type) = #getimagesize($im_filename);
if(!$width_orig)
return 2;
switch($image_type)
{
case 1: $src_im = #imagecreatefromgif($im_filename); break;
case 2: $src_im = #imagecreatefromjpeg($im_filename); break;
case 3: $src_im = #imagecreatefrompng($im_filename); break;
}
if(!$src_im)
return 3;
$aspect_ratio = (float) $height_orig / $width_orig;
$thumb_height = $max_height;
$thumb_width = round($thumb_height / $aspect_ratio);
if($thumb_width > $max_width)
{
$thumb_width = $max_width;
$thumb_height = round($thumb_width * $aspect_ratio);
}
$width = $thumb_width;
$height = $thumb_height;
$dst_img = #imagecreatetruecolor($width, $height);
if(!$dst_img)
return 4;
$success = #imagecopyresampled($dst_img,$src_im,0,0,0,0,$width,$height,$width_orig,$height_orig);
if(!$success)
return 4;
switch ($image_type)
{
case 1: $success = #imagegif($dst_img,$th_filename); break;
case 2: $success = #imagejpeg($dst_img,$th_filename,intval($quality*100)); break;
case 3: $success = #imagepng($dst_img,$th_filename,intval($quality*9)); break;
}
if(!$success)
return 4;
}
return 0;
}
return 1;
}
The return codes are just here to differentiate between different types of errors.
By looking back at that code, I don't like the "magic number" trick. I'm gonna have to change that (by exceptions for example).
if (!empty($_FILES["pic$index"]["name"])) {
$ext = substr($_FILES["pic$index"]["name"], strrpos($_FILES["pic$index"]["name"], '.') + 1);
$dir = "../gallery/$mkdir";
// Move it
if(move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext.tmp"))
{
// Resize it
GenerateThumbnail("$dir/img-$index.$ext.tmp","$dir/img-$index.$ext",600,800,0.80);
// Delete full size
unlink("$dir/img-$index.$ext.tmp");
}
}
Use move_uploaded_file to move it (recommanded) and then you can resize it and send it to it's final destination. You might not even need the ".tmp", you can use.
// Move it
if(move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext"))
// Resize it
GenerateThumbnail("$dir/img-$index.$ext","$dir/img-$index.$ext",600,800);
Keep in mind that the picture you are dealing with is already uploaded on the server. You actualy want to resize picture before storing it in "safe place".
$_FILES["pic$index"]["tmp_name"] is probably /tmp/somepicturesname

Rails + AMcharts (with export image php script) - PHP script converted to controller?

This one might be a little confusing. I'm using AMCharts with rails. Amcharts comes with a PHP script to export images called "export.php"
I'm trying to figure out how to take the code in export.php and put it into a controller.
Here is the code:
<?php
// amcharts.com export to image utility
// set image type (gif/png/jpeg)
$imgtype = 'jpeg';
// set image quality (from 0 to 100, not applicable to gif)
$imgquality = 100;
// get data from $_POST or $_GET ?
$data = &$_POST;
// get image dimensions
$width = (int) $data['width'];
$height = (int) $data['height'];
// create image object
$img = imagecreatetruecolor($width, $height);
// populate image with pixels
for ($y = 0; $y < $height; $y++) {
// innitialize
$x = 0;
// get row data
$row = explode(',', $data['r'.$y]);
// place row pixels
$cnt = sizeof($row);
for ($r = 0; $r < $cnt; $r++) {
// get pixel(s) data
$pixel = explode(':', $row[$r]);
// get color
$pixel[0] = str_pad($pixel[0], 6, '0', STR_PAD_LEFT);
$cr = hexdec(substr($pixel[0], 0, 2));
$cg = hexdec(substr($pixel[0], 2, 2));
$cb = hexdec(substr($pixel[0], 4, 2));
// allocate color
$color = imagecolorallocate($img, $cr, $cg, $cb);
// place repeating pixels
$repeat = isset($pixel[1]) ? (int) $pixel[1] : 1;
for ($c = 0; $c < $repeat; $c++) {
// place pixel
imagesetpixel($img, $x, $y, $color);
// iterate column
$x++;
}
}
}
// set proper content type
header('Content-type: image/'.$imgtype);
header('Content-Disposition: attachment; filename="chart.'.$imgtype.'"');
// stream image
$function = 'image'.$imgtype;
if ($imgtype == 'gif') {
$function($img);
}
else {
$function($img, null, $imgquality);
}
// destroy
imagedestroy($img);
?>
There are some versions in existence in a thread I found here: http://www.amcharts.com/forum/viewtopic.php?id=341
But I have a feeling the PHP code above has changed since then - because neither implementation worked for me.
What this code more or less dose is grabs the informations, that were sent to the script (POST).
The informations include the height and width of the picture and the RGB values of every pixel. The script draws every pixel and sends the images at the end to the client.
You can use Rmagick's method to draw a pixel. This will give you the same result.
The incomming post data looks like this:
height = number -> cast to int
width = number -> cast to int
// first row with a repeating part of R:G:B,R:G:B,... (n = width)
r0 = 255:0:0,150:120:0,77:88:99,...
r1 = ...
.
.
r100 = ... -> the row count is the height - 1
Actually, I found a discussion about speeding up pixel by pixel drawing.
So apparently I was running into other errors which made me think the already existing code didnt work. However, the code on the thread I linked to in the original question does in fact work!

Choosing a thumbnail from an external link

I am trying to build a script that retrieves a list of thumbnail images from an external link, much like Facebook does when you share a link and can choose the thumbnail image that is associated with that post.
My script currently works like this:
file_get_contents on the URL
preg_match_all to match any <img src="" in the contents
Works out the full URL to each image and stores it in an array
If there are < 10 images it loops through and uses getimagesize to find width and height
If there are > 10 images it loops through and uses fread and imagecreatefromstring to find width and height (for speed)
Once all width and heights are worked out it loops through and only adds the images to a new array that have a minimum width and height (so only larger images are shown, smaller images are less likely to be descriptive of the URL)
Each image has its new dimensions worked out (scaled down proportionally) and are returned...
<img src="'.$image[0].'" width="'.$image[1].'" height="'.$image[2].'"><br><br>
At the moment this works fine, but there are a number of problems I can potentially have:
SPEED! If the URL has many images on the page it will take considerably longer to process
MEMORY! Using getimagesize or fread & imagecreatefromstring will store the whole image in memory, any large images on the page could eat up the server's memory and kill my script (and server)
One solution I have found is being able to retrieve the image width and height from the header of the image without having to download the whole image, though I have only found some code to do this for JPG's (it would need to support GIF & PNG).
Can anyone make any suggestions to help me with either problem mentioned above, or perhaps you can suggest another way of doing this I am open to ideas... Thanks!
** Edit: Code below:
// Example images array
$images = array('http://blah.com/1.jpg', 'http://blah.com/2.jpg');
// Find the image sizes
$image_sizes = $this->image_sizes($images);
// Find the images that meet the minimum size
for ($i = 0; $i < count($image_sizes); $i++) {
if ($image_sizes[$i][0] >= $min || $image_sizes[$i][1] >= $min) {
// Scale down the original image size
$dimensions = $this->resize_dimensions($scale_width, $scale_height, $image_sizes[$i][0], $image_sizes[$i][1]);
$img[] = array($images[$i], $dimensions['width'], $dimensions['height']);
}
}
// Output the images
foreach ($img as $image) echo '<img src="'.$image[0].'" width="'.$image[1].'" height="'.$image[2].'"><br><br>';
/**
* Retrieves the image sizes
* Uses the getimagesize() function or the filesystem for speed increases
*/
public function image_sizes($images) {
$out = array();
if (count($images) < 10) {
foreach ($images as $image) {
list($width, $height) = #getimagesize($image);
if (is_numeric($width) && is_numeric($height)) {
$out[] = array($width, $height);
}
else {
$out[] = array(0, 0);
}
}
}
else {
foreach ($images as $image) {
$handle = #fopen($image, "rb");
$contents = "";
if ($handle) {
while(true) {
$data = fread($handle, 8192);
if (strlen($data) == 0) break;
$contents .= $data;
}
fclose($handle);
$im = #imagecreatefromstring($contents);
if ($im) {
$out[] = array(imagesx($im), imagesy($im));
}
else {
$out[] = array(0, 0);
}
#imagedestroy($im);
}
else {
$out[] = array(0, 0);
}
}
}
return $out;
}
/**
* Calculates restricted dimensions with a maximum of $goal_width by $goal_height
*/
public function resize_dimensions($goal_width, $goal_height, $width, $height) {
$return = array('width' => $width, 'height' => $height);
// If the ratio > goal ratio and the width > goal width resize down to goal width
if ($width/$height > $goal_width/$goal_height && $width > $goal_width) {
$return['width'] = floor($goal_width);
$return['height'] = floor($goal_width/$width * $height);
}
// Otherwise, if the height > goal, resize down to goal height
else if ($height > $goal_height) {
$return['width'] = floor($goal_height/$height * $width);
$return['height'] = floor($goal_height);
}
return $return;
}
getimagesize reads only header, but imagecreatefromstring reads whole image. Image read by GD, ImageMagick or GraphicsMagic is stored as bitmap so it consumes widthheight(3 or 4) bytes, and there's nothing you can do about it.
The best possible solution for your problem is to make curl multi-request (see http://ru.php.net/manual/en/function.curl-multi-select.php ), and then one by one process recieved images with GD or any other library. And to make memory consumption a bit lower, you can store image files on disk, not in memory.
The only idea that comes to mind for your current approach (which is impressive) is to check the HTML for existing width and height attributes and skip the file read process altogether if they exist.

how to modify this php script to handle png and gif uploads

I have the following script (it looks long, but well commented). Problem is, i get errors when i try to upload a png or gif image. What can i do to adjust this (easy if possible) so that it can either work with png's and gif's or convert them before trying to work with them.
This is the error that i recieve
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
Aparently the first part of the script is working, saving the original upload, but how should i go about this?
$idir = "images/"; // Path To Images Directory
$tdir = "images/"; // Path To Thumbnails Directory
$twidth = "125"; // Maximum Width For Thumbnail Images
$theight = "100"; // Maximum Height For Thumbnail Images
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$simg = imagecreatefromjpeg("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}
Any guidance here is greatly appreciated.
Well, imagecreatefromjpeg() can only create images from... jpegs. There are sister functions for creating images from other file types, namely imagecreatefrompng() and imagecreatefromgif().
I've added to your code. Give it a try. Make sure you see the changes, as I put a die() in there in case of an invalid image, which may not be what you want:
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$cfunction = 'imagecreatefromjpeg';
if ($_FILES['imagefile']['type'] == "image/png") {
$cfunction = 'imagecreatefrompng';
} else if ($_FILES['imagefile']['type'] == "image/gif") {
$cfunction = 'imagecreatefromgif';
} else {
die("Invalid image format.");
}
$simg = $cfunction("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}

Categories