Why is my image rotating when resizing uploaded image in PHP? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php resizing image on upload rotates the image when i don't want it to
I have created my first ever upload code and was testing it, the image resizes and uploads fine. The only issue I have is that it rotates.
Here is the code:
$errors = array();
$message = "";
if(isset($_POST["test"])){
$name = rand(1,999999) . $_FILES["uploadfile"]["name"];
$temp_name = $_FILES["uploadfile"]["tmp_name"];
$size = $_FILES["uploadfile"]["size"];
$extension = strtolower(end(explode('.', $_FILES['uploadfile']['name'])));
$path = "testupload/" . $name;
$info = getimagesize($temp_name);
$originalwidth = $info[0];
$originalheight = $info[1];
$mime = $info["mime"];
$acceptedHeight = 750;
$acceptedWidth = 0;
$acceptedMimes = array('image/jpeg','image/png','image/gif');
$acceptedfileSize = 4102314;
$acceptedExtensions = array('jpg','jpeg','gif','png');
echo $size;
// check mimetype
if(!in_array($mime, $acceptedMimes)){$errors[] = "mime type not allowed - The file you have just uploaded was a: " . $extension . " file!";}
if(!$errors){if($size > $acceptedfileSize){$errors[] = "filesize is to big - Your file size of this file is: " . $size;}}
if(!$errors){if(!in_array($extension, $acceptedExtensions)){$errors[] = "File extension not allowed - The file you have just uploaded was a: " . $extension . " file!";}}
if(!$errors){
// create the image from the temp file.
if ($extension === 'png'){
$orig = imagecreatefrompng($temp_name);
}elseif ($extension === 'jpeg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'jpg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'gif'){
$orig = imagecreatefromgif($temp_name);
}
// work out the new dimensions.
if ($acceptedHeight === 0){
$newWidth = $acceptedWidth;
$newHeight = ($originalheight / $originalwidth) * $acceptedWidth;
}else if ($acceptedWidth === 0){
$newWidth = ($originalwidth / $originalheight) * $acceptedHeight;
$newHeight = $acceptedHeight;
}else{
$newWidth = $acceptedWidth;
$newHeight = $acceptedHeight;
}
$originalwidth = imagesx($orig);
$originalheight = imagesy($orig);
// make ssure they are valid.
if ($newWidth < 1){ $newWidth = 1; }else{ $newWidth = round($newWidth ); }
if ($newHeight < 1){ $newHeight = 1; }else{ $newHeight = round($newHeight); }
// don't bother copying the image if its alreay the right size.
if ($originalwidth!== $newWidth || $originalheight !== $newHeight){
// create a new image and copy the origional on to it at the new size.
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $orig, 0,0,0,0, $newWidth, $newHeight, $originalwidth, $originalheight);
}else{
// phps copy on write means this won't cause any harm.
$new = $orig;
}
// save the image.
if ($extension === 'jpeg' || $extension === 'jpg'){
imagejpeg($new, $path, 100);
}else if ($save_ext === 'gif'){
imagegif($new, $path);
}else{
imagepng($new, $path, round(9 - (100 / (100 / 9))));
}
$message = $path;
Can someone please let me know what is going on?

Check the original image is actually in the orientation you expect. I work with images all day and the majority of the time it's Windows Photo Viewer showing the image in a certain orientation (reading an orientation change in the EXIF) but if you open it up in Photoshop it's different.

I tested your code with two images: one was landscape (width > height), the other was portrait (height > width). The code works.
The problem seems to be what #Tavocado said: newer cameras have a sensor to detect the orientation of the camera when the photo was taken, and they store that info in the photo. Also, newer photo viewing software reads that info back from the photo and rotates it before displaying the image. So you all the time see the image with the right orientation (sky up, earth down). However PHP functions (and the rest of the world) don't use that information and display the image as is was taken. That means that you will have to rotate yourself portrait images.
Just load your images in the browser (drag the file on the address bar) you you will see how the image is really stored in the file, without any automatic rotation.

The problem is that the image has embedded EXIF data, probably from the device that took the photo.
Investigate whether your images have embedded rotation information, using exif_read_data, and then auto-correct the rotation with a function like this.

Related

Efficient and fast image uploading

I've been playing around with a new website that will allow members to upload some content and images. I've knocked up the code html, php & mysql (with the help of google) and it now all works but not fast.
It could be my code is inefficient or my hosting company is restricting the uploading speed ... or both. I am very new to developing websites!
Using small size images <300kb is not an issue, but as soon as I use 6mb ones its can take up to 5minutes to upload the images even though I am reducing there size before upload. I've tested without database inserts so I know its the images part thats causing the issue.
Before I start looking at implementing DropBox to store the images ... has anyone come across this problem before that could recommend a different approach?
Code html snippet:
<form name="add-form" action="includes/new_post.php" method="post" enctype="multipart/form-data">
<input id='id_question_pic' name="upfile1[]" type="file" tabindex="3" multiple accept='image/*' max-uploads=6 />
Code in php:
//put all the uploaded images into an array
$files=array();
$fdata=$_FILES['upfile1'];
for($i=0;$i<count($fdata['name']);++$i){
$files[]=array(
'name' =>$fdata['name'][$i],
'type' => $fdata['type'][$i],
'tmp_name'=>$fdata['tmp_name'][$i],
'error' => $fdata['error'][$i],
'size' => $fdata['size'][$i]
);
}
//move to the correct directory, with unique file names
$directory = 'C:\Inetpub\vhosts\mydomain\form_uploads\\'; //use local server path (hosting company)
$dbimagepath = 'form_uploads/';
$result = true;
foreach ($files as $file) {
if ($file['error'] == 0) {
$filename = $file['name'];
if (strlen($filename) > 20) {$filename = substr($filename, strlen($filename) - 8);}
$filename = mt_rand() . '_' . $filename;
//ensure the filename is unique//
while (#getimagesize($directory . $filename)){$filename = mt_rand() . $filename;}
$fullpath = $directory . $filename;
if (exif_imagetype($file['tmp_name'])== 2){
$image = imagecreatefromstring(file_get_contents($file['tmp_name']));
//ORIGINAL DIMENTIONS
list( $width , $height ) = getimagesize($file['tmp_name']);
//ORIGINAL SCALE
$xscale=$width/600;
$yscale=$height/600;
//NEW DIMENSIONS WITH SAME SCALE
if ($yscale > $xscale)
{
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
}
else
{
$new_width = round($width * (1/$xscale));
$new_height = round($height * (1/$xscale));
}
//NEW IMAGE RESOURCE
if(!($imageResized = imagecreatetruecolor($new_width, $new_height)))
{//error handling}
//RESIZE IMAGE
if(! imagecopyresampled($imageResized, $image , 0 , 0 , 0 , 0 , $new_width , $new_height , $width , $height))
{//error handling}
$image = $imageResized;
$exif = exif_read_data($file['tmp_name']);
if (!empty($exif['Orientation']) || !$exif['Orientation']===null){
switch($exif['Orientation'])
{
case 3: // 180 rotate left
$image=imagerotate($image, 180, -1);
break;
case 6: // 90 rotate right
$image=imagerotate($image, -90, -1);
break;
case 8: // 90 rotate left
$image=imagerotate($image, 90, -1);
break;
default:
break;
}
}
if (imagejpeg($image, $fullpath, 80)){
//call function to update the database
}
imagedestroy($image);
}
else
{$result = false;}
}
}
Take a look at 3rd party solutions that are build to solve your particular problem.
Uploadcare for example.
With it you can have fast reliable uploads even without access to your host's filesystem and upload speed is limited only by your visitor's internet connectivity.

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

Image function that allows images to be cropped and resized in PHP without using so much memory [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've used this code for a while now for a few sites I've built which is great for galleries but it uses up a lot of memory and I keep getting memory allocation errors within the error log. Is there anything that can be changed to make this script better?
<?php
// Smart Image Resizer 1.4.1
// Resizes images, intelligently sharpens, crops based on width:height ratios, color fills
// transparent GIFs and PNGs, and caches variations for optimal performance
// Created by: Joe Lencioni (http://shiftingpixel.com)
// Date: August 6, 2008
// Based on: http://veryraw.com/history/2005/03/image-resizing-with-php/
/////////////////////
// LICENSE
/////////////////////
// I love to hear when my work is being used, so if you decide to use this, feel encouraged
// to send me an email. Smart Image Resizer is released under a Creative Commons
// Attribution-Share Alike 3.0 United States license
// (http://creativecommons.org/licenses/by-sa/3.0/us/). All I ask is that you include a link
// back to Shifting Pixel (either this page or shiftingpixel.com), but don’t worry about
// including a big link on each page if you don’t want to–one will do just nicely. Feel
// free to contact me to discuss any specifics (joe#shiftingpixel.com).
/////////////////////
// REQUIREMENTS
/////////////////////
// PHP and GD
/////////////////////
// PARAMETERS
/////////////////////
// Parameters need to be passed in through the URL's query string:
// image absolute path of local image starting with "/" (e.g. /images/toast.jpg)
// width maximum width of final image in pixels (e.g. 700)
// height maximum height of final image in pixels (e.g. 700)
// color (optional) background hex color for filling transparent PNGs (e.g. 900 or 16a942)
// cropratio (optional) ratio of width to height to crop final image (e.g. 1:1 or 3:2)
// nocache (optional) does not read image from the cache
// quality (optional, 0-100, default: 90) quality of output image
/////////////////////
// EXAMPLES
/////////////////////
// Resizing a JPEG:
// <img src="/image.php/image-name.jpg?width=100&height=100&image=/path/to/image.jpg" alt="Don't forget your alt text" />
// Resizing and cropping a JPEG into a square:
// <img src="/image.php/image-name.jpg?width=100&height=100&cropratio=1:1&image=/path/to/image.jpg" alt="Don't forget your alt text" />
// Matting a PNG with #990000:
// <img src="/image.php/image-name.png?color=900&image=/path/to/image.png" alt="Don't forget your alt text" />
/////////////////////
// CODE STARTS HERE
/////////////////////
if (!isset($_GET['image']))
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: no image was specified';
exit();
}
define('MEMORY_TO_ALLOCATE', '100M');
define('DEFAULT_QUALITY', 90);
define('CURRENT_DIR', dirname(__FILE__));
define('CACHE_DIR_NAME', '/imagecache/');
define('CACHE_DIR', CURRENT_DIR . CACHE_DIR_NAME);
define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
// Images must be local files, so for convenience we strip the domain if it's there
$image = preg_replace('/^(s?f|ht)tps?:\/\/[^\/]+/i', '', (string) $_GET['image']);
// For security, directories cannot contain ':', images cannot contain '..' or '<', and
// images must start with '/'
if ($image{0} != '/' || strpos(dirname($image), ':') || preg_match('/(\.\.|<|>)/', $image))
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: malformed image path. Image paths must begin with \'/\'';
exit();
}
// If the image doesn't exist, or we haven't been told what it is, there's nothing
// that we can do
if (!$image)
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: no image was specified';
exit();
}
// Strip the possible trailing slash off the document root
$docRoot = preg_replace('/\/$/', '', DOCUMENT_ROOT);
if (!file_exists($docRoot . $image))
{
header('HTTP/1.1 404 Not Found');
echo 'Error: image does not exist: ' . $docRoot . $image;
exit();
}
// Get the size and MIME type of the requested image
$size = GetImageSize($docRoot . $image);
$mime = $size['mime'];
// Make sure that the requested file is actually an image
if (substr($mime, 0, 6) != 'image/')
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: requested file is not an accepted type: ' . $docRoot . $image;
exit();
}
$width = $size[0];
$height = $size[1];
$maxWidth = (isset($_GET['width'])) ? (int) $_GET['width'] : 0;
$maxHeight = (isset($_GET['height'])) ? (int) $_GET['height'] : 0;
if (isset($_GET['color']))
$color = preg_replace('/[^0-9a-fA-F]/', '', (string) $_GET['color']);
else
$color = FALSE;
// If either a max width or max height are not specified, we default to something
// large so the unspecified dimension isn't a constraint on our resized image.
// If neither are specified but the color is, we aren't going to be resizing at
// all, just coloring.
if (!$maxWidth && $maxHeight)
{
$maxWidth = 99999999999999;
}
elseif ($maxWidth && !$maxHeight)
{
$maxHeight = 99999999999999;
}
elseif ($color && !$maxWidth && !$maxHeight)
{
$maxWidth = $width;
$maxHeight = $height;
}
// If we don't have a max width or max height, OR the image is smaller than both
// we do not want to resize it, so we simply output the original image and exit
if ((!$maxWidth && !$maxHeight) || (!$color && $maxWidth >= $width && $maxHeight >= $height))
{
$data = file_get_contents($docRoot . '/' . $image);
$lastModifiedString = gmdate('D, d M Y H:i:s', filemtime($docRoot . '/' . $image)) . ' GMT';
$etag = md5($data);
doConditionalGet($etag, $lastModifiedString);
header("Content-type: $mime");
header('Content-Length: ' . strlen($data));
echo $data;
exit();
}
// Ratio cropping
$offsetX = 0;
$offsetY = 0;
if (isset($_GET['cropratio']))
{
$cropRatio = explode(':', (string) $_GET['cropratio']);
if (count($cropRatio) == 2)
{
$ratioComputed = $width / $height;
$cropRatioComputed = (float) $cropRatio[0] / (float) $cropRatio[1];
if ($ratioComputed < $cropRatioComputed)
{ // Image is too tall so we will crop the top and bottom
$origHeight = $height;
$height = $width / $cropRatioComputed;
$offsetY = ($origHeight - $height) / 2;
}
else if ($ratioComputed > $cropRatioComputed)
{ // Image is too wide so we will crop off the left and right sides
$origWidth = $width;
$width = $height * $cropRatioComputed;
$offsetX = ($origWidth - $width) / 2;
}
}
}
// Setting up the ratios needed for resizing. We will compare these below to determine how to
// resize the image (based on height or based on width)
$xRatio = $maxWidth / $width;
$yRatio = $maxHeight / $height;
if ($xRatio * $height < $maxHeight)
{ // Resize the image based on width
$tnHeight = ceil($xRatio * $height);
$tnWidth = $maxWidth;
}
else // Resize the image based on height
{
$tnWidth = ceil($yRatio * $width);
$tnHeight = $maxHeight;
}
// Determine the quality of the output image
$quality = (isset($_GET['quality'])) ? (int) $_GET['quality'] : DEFAULT_QUALITY;
// Before we actually do any crazy resizing of the image, we want to make sure that we
// haven't already done this one at these dimensions. To the cache!
// Note, cache must be world-readable
// We store our cached image filenames as a hash of the dimensions and the original filename
$resizedImageSource = $tnWidth . 'x' . $tnHeight . 'x' . $quality;
if ($color)
$resizedImageSource .= 'x' . $color;
if (isset($_GET['cropratio']))
$resizedImageSource .= 'x' . (string) $_GET['cropratio'];
$resizedImageSource .= '-' . $image;
$resizedImage = md5($resizedImageSource);
$resized = CACHE_DIR . $resizedImage;
// Check the modified times of the cached file and the original file.
// If the original file is older than the cached file, then we simply serve up the cached file
if (!isset($_GET['nocache']) && file_exists($resized))
{
$imageModified = filemtime($docRoot . $image);
$thumbModified = filemtime($resized);
if($imageModified < $thumbModified) {
$data = file_get_contents($resized);
$lastModifiedString = gmdate('D, d M Y H:i:s', $thumbModified) . ' GMT';
$etag = md5($data);
doConditionalGet($etag, $lastModifiedString);
header("Content-type: $mime");
header('Content-Length: ' . strlen($data));
echo $data;
exit();
}
}
// We don't want to run out of memory
ini_set('memory_limit', MEMORY_TO_ALLOCATE);
// Set up a blank canvas for our resized image (destination)
$dst = imagecreatetruecolor($tnWidth, $tnHeight);
// Set up the appropriate image handling functions based on the original image's mime type
switch ($size['mime'])
{
case 'image/gif':
// We will be converting GIFs to PNGs to avoid transparency issues when resizing GIFs
// This is maybe not the ideal solution, but IE6 can suck it
$creationFunction = 'ImageCreateFromGif';
$outputFunction = 'ImagePng';
$mime = 'image/png'; // We need to convert GIFs to PNGs
$doSharpen = FALSE;
$quality = round(10 - ($quality / 10)); // We are converting the GIF to a PNG and PNG needs a compression level of 0 (no compression) through 9
break;
case 'image/x-png':
case 'image/png':
$creationFunction = 'ImageCreateFromPng';
$outputFunction = 'ImagePng';
$doSharpen = FALSE;
$quality = round(10 - ($quality / 10)); // PNG needs a compression level of 0 (no compression) through 9
break;
default:
$creationFunction = 'ImageCreateFromJpeg';
$outputFunction = 'ImageJpeg';
$doSharpen = TRUE;
break;
}
// Read in the original image
$src = $creationFunction($docRoot . $image);
if (in_array($size['mime'], array('image/gif', 'image/png')))
{
if (!$color)
{
// If this is a GIF or a PNG, we need to set up transparency
imagealphablending($dst, false);
imagesavealpha($dst, true);
}
else
{
// Fill the background with the specified color for matting purposes
if ($color[0] == '#')
$color = substr($color, 1);
$background = FALSE;
if (strlen($color) == 6)
$background = imagecolorallocate($dst, hexdec($color[0].$color[1]), hexdec($color[2].$color[3]), hexdec($color[4].$color[5]));
else if (strlen($color) == 3)
$background = imagecolorallocate($dst, hexdec($color[0].$color[0]), hexdec($color[1].$color[1]), hexdec($color[2].$color[2]));
if ($background)
imagefill($dst, 0, 0, $background);
}
}
// Resample the original image into the resized canvas we set up earlier
ImageCopyResampled($dst, $src, 0, 0, $offsetX, $offsetY, $tnWidth, $tnHeight, $width, $height);
if ($doSharpen)
{
// Sharpen the image based on two things:
// (1) the difference between the original size and the final size
// (2) the final size
$sharpness = findSharp($width, $tnWidth);
$sharpenMatrix = array(
array(-1, -2, -1),
array(-2, $sharpness + 12, -2),
array(-1, -2, -1)
);
$divisor = $sharpness;
$offset = 0;
imageconvolution($dst, $sharpenMatrix, $divisor, $offset);
}
// Make sure the cache exists. If it doesn't, then create it
if (!file_exists(CACHE_DIR))
mkdir(CACHE_DIR, 0755);
// Make sure we can read and write the cache directory
if (!is_readable(CACHE_DIR))
{
header('HTTP/1.1 500 Internal Server Error');
echo 'Error: the cache directory is not readable';
exit();
}
else if (!is_writable(CACHE_DIR))
{
header('HTTP/1.1 500 Internal Server Error');
echo 'Error: the cache directory is not writable';
exit();
}
// Write the resized image to the cache
$outputFunction($dst, $resized, $quality);
// Put the data of the resized image into a variable
ob_start();
$outputFunction($dst, null, $quality);
$data = ob_get_contents();
ob_end_clean();
// Clean up the memory
ImageDestroy($src);
ImageDestroy($dst);
// See if the browser already has the image
$lastModifiedString = gmdate('D, d M Y H:i:s', filemtime($resized)) . ' GMT';
$etag = md5($data);
doConditionalGet($etag, $lastModifiedString);
// Send the image to the browser with some delicious headers
header("Content-type: $mime");
header('Content-Length: ' . strlen($data));
echo $data;
function findSharp($orig, $final) // function from Ryan Rud (http://adryrun.com)
{
$final = $final * (750.0 / $orig);
$a = 52;
$b = -0.27810650887573124;
$c = .00047337278106508946;
$result = $a + $b * $final + $c * $final * $final;
return max(round($result), 0);
} // findSharp()
function doConditionalGet($etag, $lastModified)
{
header("Last-Modified: $lastModified");
header("ETag: \"{$etag}\"");
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) :
false;
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?
stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :
false;
if (!$if_modified_since && !$if_none_match)
return;
if ($if_none_match && $if_none_match != $etag && $if_none_match != '"' . $etag . '"')
return; // etag is there but doesn't match
if ($if_modified_since && $if_modified_since != $lastModified)
return; // if-modified-since is there but doesn't match
// Nothing has changed since their last request - serve a 304 and exit
header('HTTP/1.1 304 Not Modified');
exit();
} // doConditionalGet()
// old pond
// a frog jumps
// the sound of water
// —Matsuo Basho
?>
If your server has imagemagick installed, it can be done like this:
exec("convert $filename -quality 60 -resize x100 -gravity center -crop 100x100+0+0 +repage $newfilename");
else:
Resize & Crop with GD2
Hope it helps
Yes, you can switch to using the IMagick extension, which is much better at memory handling. As I've described in an old question, GD uses memory proportional to the image size and holds it in memory entirely uncompressed.

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

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