Efficient and fast image uploading - php

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.

Related

how to upload image directly on subdomain which is hosted on another server?

I am trying to upload my image directly to my subdomain which is hosted on another server
currently I am using this code to upload image in test.com to demo.test.com
$uploadDirectory = "//demo.test.com/";
i use this code to upload my image
$productname="sdf";
$member_id="123";
$uploadDirectory = "//demo.test.com/";
$randomNumber = rand(0, 99999);
$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
$photo_name = $productname.'-'.md5($randomNumber.$member_id);
{
if( $ratio > 1) {
$width = 500;
$height = 500/$ratio;
}
else {
$width = 500*$ratio;
$height = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width,$height);
$fileName3 = $uploadDirectory.$photo_name . '-500x500' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName3); // adjust format as needed
imagedestroy($dst);
}
What is the question ?
The subdomain is usually in the domain layer. This layer must not contains infrastructure logic (call to remote data provider). You shouldn't implement the upload in the Domain layer.
To upload your image, you have to call an interface (method : uploadImage) in the domain layer and implement it in the infrastructure (providers) layer.
see https://en.wikipedia.org/wiki/Single-responsibility_principle
and https://en.wikipedia.org/wiki/Dependency_inversion_principle

PHP EXIF Process IFD TAG Remote Integer Overflow

Background:
I have been working on an issue whereby a file upload form will only accept certain images, it is not a problem with image size(dimensions) or with size(filesize) but I think i've found it's to do with image bit depth, as the PHP script resizes the image and applies a static (semi-transparant) watermark file to the image and saves the result.
I have gone through a long process today and yesterday working with this as the error that occurs is the server stating "Connection reset by server" . Which I think I've narrowed down to the server not having enough free memory to complete the image resource manipulations.
Issue:
Then, after all that, this error comes up on file upload submission:
IPS detected for "WEB PHP EXIF Process IFD TAG Remote Integer Overflow -2 (CVE-20/Buffer Over Flow"
Some googling only tells me that it's a securty vulnerabiliy for PHP < 4.2 or so, and doesn't relate to actually what's going on.
I have looked through my code and am very sure that
My query is to try and shed some light on what this error statement means (and how I can go about correcting it)?
Notes:
PHP 5.6.16
No PHP EXIF functions run on the page.
I can't see anywhere on the page that would cause an integer overflow (running to infinity, I guess)
Page does use imagecopy, imagealphablending and imagesavealpha But this error notice seems to appear before the script runs on the uploaded file.
This error only occurs on some uploaded images and not on others.
I have found no Apache error logs relating to this
I have no PHP errors recorded.
Code:
As I think the issue may occur somehow before the page loads I'm not sure how useful this code block will be but, take a look:
(also please note that I am aware this page is 5 years old and isn't the smartest programming, i have fixed it up in parts but am aware it can probably be further tidied)
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
///first set out variables.
$goodImage = 0;
$maxfilesize = (int)$_POST['MAX_FILE_SIZE'];
$gallery = (int)$_POST['galfolderid']
if (empty($gallery)) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value has not been set.";
}
elseif (!is_numeric($gallery)) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value is not a numeric value.";
}
elseif (!is_dir($_SERVER['DOCUMENT_ROOT']."/images/gallery/" . $gallery )) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value, while being a number, is not a valid numeric value.";
}
if(!empty($_SESSION['message'])) {
header("Location:editgallery.php?gallery=".$galleryid);
exit;
}
for($count=0;$count<5;$count++) {
if ($_FILES['image']['error'][$count] == 0) {
clearstatcache();
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$imageType = finfo_file($finfo, $_FILES['image']['tmp_name'][$count]);
finfo_close($finfo);
unset($finfo);
if (strtolower($imageType) == "image/png") {
$imgtype = "PNG";
$original = imagecreatefrompng($_FILES['image']['tmp_name'][$count]);
} elseif (strtolower($imageType) == "image/jpeg" || strtolower($imageType) == "image/jpg") {
$imgtype = "JPG";
$original = imagecreatefromjpeg($_FILES['image']['tmp_name'][$count]);
} else {
//not a JPG or PNG type... set error.
$_SESSION['message'] = "Image " . ($count+1) . " does not appear to be a valid .JPG or .PNG file. ";
error_log($_SESSION['message']);
header("Location:editgallery.php");
exit;
}
unlink($_FILES['image']['tmp_name'][$count]);
$edgePadding = (int)$_POST['WMedge'][$count]; //integer
$watermarkScale = $_POST['WMscale'][$count]; //float
$h_position = $_POST['Hpos'][$count]; //text array
$v_position = $_POST['Vpos'][$count]; //text array
$Hoz = $h_position[0];
$Vez = $v_position[0];
if (!isset($watermarkScale) || empty($watermarkScale) || !is_numeric($watermarkScale)) {
$watermarkScale = 1.0;
}
elseif($watermarkScale > 2.0) {
$watermarkScale = 2.0;
}
elseif($watermarkScale < 0.5) {
$watermarkScale = 0.5;
}
if ((!isset($edgePadding) || empty($edgePadding) || !is_numeric($edgePadding)) && $edgePadding !== "0") {
$edgePadding = 5;
}
// be sure that the other options we need have some kind of value
if ($_FILES['image']['size'][$count] > $maxfilesize) {
$_SESSION['message'] .= "Image file ".($count+1)." appears to be too big. There is a limit of 2Mb on the
size of the image you can upload. Please click 'Back' on your browser and resubmit a valid image.";
error_log($_SESSION['message']);
//file too big.
}
//target name is the number of images in the LARGE gallery,
///cycle through imagenames to find the first "clear" image number.
$newimagename = 1;
clearstatcache();
/***
NOTE: Only possible place an integer oveflow might occur I think
***/
while (file_exists($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/S/" . $newimagename . ".jpg")) {
$newimagename++;
}
///newimagename is the new filename of the image.
$target_name = $newimagename . ".jpg";
$target = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/L/" . $target_name;
$targetSmall = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/S/" . $target_name;
//targetSM is used below to make the thumbnail image. for the SMALL gallery.
//full target directory and name.
// file upload success
// now file need resizing before the watermark is applied.
// resize new dimensions (Large- 800px)
$originalImageSize[0] = imagesx($original);
$originalImageSize[1] = imagesy($original);
/***
* Resize new dimensions for small thumbnail.
***/
if ($originalImageSize[0] > 133) {
$percent = 133 / $originalImageSize[0];
} else {
$percent = 1;
}
$newThumbHeight = $originalImageSize[1] * $percent;
$newThumbWidth = $originalImageSize[0] * $percent;
// Resample
$imageThumbFinal = imagecreatetruecolor($newThumbWidth, $newThumbHeight);
imagecopyresampled($imageThumbFinal, $original, 0, 0, 0, 0, $newThumbWidth, $newThumbHeight, $originalImageSize[0], $originalImageSize[1]);
// Output
imagejpeg($imageThumbFinal, $targetSmall, 80);
imagedestroy($imageThumbFinal);
unset($imageThumbFinal, $percent,$newThumbWidth,$newThumbHeight);
/***
* End Thumbnail generation.
*/
/***
* Resize main sized image (max 800px wide)
***/
if ($originalImageSize[0] > 800) {
$percent = 800 / $originalImageSize[0];
} else {
$percent = 1;
}
$newPictureHeight = $originalImageSize[1] * $percent;
$newPictureWidth = $originalImageSize[0] * $percent;
// Resample main image to reduce max size.
$imageCleanFinal = imagecreatetruecolor($newPictureWidth, $newPictureHeight);
imagecopyresampled($imageCleanFinal, $original, 0, 0, 0, 0, $newPictureWidth, $newPictureHeight, $originalImageSize[0], $originalImageSize[1]);
/***
* Now resize the watermark and save onto the final image.
***/
//full target directory and name.
$watermark = $_SERVER['DOCUMENT_ROOT'] . "/images/watermark2.png";
$wmTarget = substr($watermark, 0, -3) . "tmp"; //image/watermark2.tmp is resized.
$sourceWaterImage = imagecreatefrompng($watermark);
$waterMarkWidth = imagesx($sourceWaterImage);
$waterMarkHeight = imagesy($sourceWaterImage);
$destinationHeight = $waterMarkHeight * $watermarkScale;
$destinationWidth = $waterMarkWidth * $watermarkScale;
$destinationHeight = floor($destinationHeight);
$destinationWidth = floor($destinationWidth);
$destinationWatermarkImage = imagecreatetruecolor($destinationWidth, $destinationHeight);
imagealphablending($destinationWatermarkImage, FALSE);
imagesavealpha($destinationWatermarkImage, TRUE);
imagecopyresampled($destinationWatermarkImage, $sourceWaterImage, 0, 0, 0, 0, $destinationWidth,
$destinationHeight, $waterMarkWidth, $waterMarkHeight);
imagedestroy($sourceWaterImage);
unset($sourceWaterImage);
clearstatcache();
/***
* Set watermark location on final image.
***/
$differenceX = $newPictureWidth - $destinationWidth;
$differenceY = $newPictureHeight - $destinationHeight;
switch ($Hoz) {
// find the X coord for placement
case 'left':
$placementX = $edgePadding;
break;
case 'center':
$placementX = round($differenceX / 2);
break;
case 'right':
$placementX = $newPictureWidth - ($destinationWidth + $edgePadding);
break;
default:
$placementX = 0;
break;
}
switch ($Vez) {
// find the Y coord for placement
case 'top':
$placementY = $edgePadding;
break;
case 'middle':
$placementY = round($differenceY / 2);
break;
case 'bottom':
$placementY = $newPictureHeight - ($destinationHeight + $edgePadding);
break;
default:
$placementY = 0;
break;
}
/***
* Finish set Watermark location
***/
imagecopy($imageCleanFinal,
$destinationWatermarkImage,
$placementX,
$placementY,
0,
0,
$destinationWidth,
$destinationHeight);
imagejpeg($imageCleanFinal, $target, 80);
/***
* Image final save
***/
// Output
imagejpeg($imageCleanFinal, $target, 80);
imagedestroy($imageCleanFinal);
imagedestroy($destinationWatermarkImage);
unset($imageCleanFinal, $percent);
unlink($wmTarget);
$output[$goodImage]['targetName'] = $target_name;
$output[$goodImage]['targetAddr'] = $target;
$goodImage++;
} elseif (!isset($_FILES['image']['name'][$count]) || ($_FILES['image']['error'][$count] != 0 && $_FILES['image']['error'][$count] != 4)) {
//error in file upload.
$_SESSION['message'] .= " There is a file upload error number " . $_FILES['image']['error'][$count] . ". for image ".($count+1).".
Please try resubmitting a valid image.";
error_log($_SESSION['message']);
}
}
if (empty($_SESSION['message'])){
$_SESSION['message'] = $goodImage." New Image(s) Uploaded";
}
// display resulting image for download
header("Location:editgallery.php?special=yes&gallery=".$galleryid);
exit;
Server Details:
Apache 2.4
WebHostManger & CPanel (combined) version 54.0.19
PHP 5.6 using Mod suPHP 0.7.2
2 core 2.2GHz (so x2) intel with
1896Mb/2097Mb physical memory (used/available)
+4095Mb memory Swap File. (~6010Mb total)

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

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.

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.

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

Categories