Compress and RESCALE uploaded image - php

I have a function that uploads files up to 8MB but now I also want to compress or at least rescale larger images, so my output image won't be any bigger than 100-200 KB and 1000x1000px resolution. How can I implement compress and rescale (proportional) in my function?
function uploadFile($file, $file_restrictions = '', $user_id, $sub_folder = '') {
global $path_app;
$new_file_name = generateRandomString(20);
if($sub_folder != '') {
if(!file_exists('media/'.$user_id.'/'.$sub_folder.'/')) {
mkdir('media/'.$user_id.'/'.$sub_folder, 0777);
}
$sub_folder = $sub_folder.'/';
}
else {
$sub_folder = '';
}
$uploadDir = 'media/'.$user_id.'/'.$sub_folder;
$uploadDirO = 'media/'.$user_id.'/'.$sub_folder;
$finalDir = $path_app.'/media/'.$user_id.'/'.$sub_folder;
$fileExt = explode(".", basename($file['name']));
$uploadExt = $fileExt[count($fileExt) - 1];
$uploadName = $new_file_name.'_cache.'.$uploadExt;
$uploadDir = $uploadDir.$uploadName;
$restriction_ok = true;
if(!empty($file_restrictions)) {
if(strpos($file_restrictions, $uploadExt) === false) {
$restriction_ok = false;
}
}
if($restriction_ok == false) {
return '';
}
else {
if(move_uploaded_file($file['tmp_name'], $uploadDir)) {
$image_info = getimagesize($uploadDir);
$image_width = $image_info[0];
$image_height = $image_info[1];
if($file['size'] > 8000000) {
unlink($uploadDir);
return '';
}
else {
$finalUploadName = $new_file_name.'.'.$uploadExt;
rename($uploadDirO.$uploadName, $uploadDirO.$finalUploadName);
return $finalDir.$finalUploadName;
}
}
else {
return '';
}
}
}

For the rescaling I use a function like this:
function dimensions($width,$height,$maxWidth,$maxHeight)
// given maximum dimensions this tries to fill that as best as possible
{
// get new sizes
if ($width > $maxWidth) {
$height = Round($maxWidth*$height/$width);
$width = $maxWidth;
}
if ($height > $maxHeight) {
$width = Round($maxHeight*$width/$height);
$height = $maxHeight;
}
// return array with new size
return array('width' => $width,'height' => $height);
}
The compression is done by a PHP function:
// set limits
$maxWidth = 1000;
$maxHeight = 1000;
// read source
$source = imagecreatefromjpeg($originalImageFile);
// get the possible dimensions of destination and extract
$dims = dimensions(imagesx($source),imagesy($source),$maxWidth,$maxHeight);
// prepare destination
$dest = imagecreatetruecolor($dims['width'],$dims['height']);
// copy in high-quality
imagecopyresampled($dest,$source,0,0,0,0,
$width,$height,imagesx($source),imagesy($source));
// save file
imagejpeg($dest,$destinationImageFile,85);
// clear both copies from memory
imagedestroy($source);
imagedestroy($dest);
You will have to supply $originalImageFile and $destinationImageFile. This stuff comes from a class I use, so I edited it quite a lot, but the basic functionality is there. I left out any error checking, so you still need to add that. Note that the 85 in imagejpeg() denotes the amount of compression.

you can use a simple one line solution through imagemagic library the command will like this
$image="path to image";
$res="option to resize"; i.e 25% small , 50% small or anything else
exec("convert ".$image." -resize ".$res." ".$image);
with this you can rotate resize and many other image customization

Take a look on imagecopyresampled(), There is also a example that how to implement it, For compression take a look on imagejpeg() the third parameter helps to set quality of the image, 100 means (best quality, biggest file) and if you skip the last option then default quality is 75 which is good and compress it.

Related

How can I create custom thumbnails using php gd

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

php imagecopyresized() making full black thumbnail

So, I have this class that's half-working.
Somehow I'm not being able to copy a re-sized sample of the uploaded image, only a black "square" with the "correct" dimensions (screw the dimensions, as long as the thumb comes up clear. one step at the time).
I'm sorry for the WOT but it's driving me cray-cray.
Thanks in advance.
<?php
class Upload {
#function from http://stackoverflow.com/a/10666106/587811
public function resize_values($origWidth,$origHeight,$maxWidth = 200,$maxHeight = 200){
#check for longest side, we'll be seeing that to the max value above
if($origHeight > $origWidth){ #if height is more than width
$newWidth = ($maxHeight * $origWidth) / $origHeight;
$retval = array(width => $newWidth, height => $maxHeight);
}
else{
$newHeight= ($maxWidth * $origHeight) / $origWidth;
$retval = array(width => $origWidth, height => $newHeight);
}
return $retval;
}
public function image($picurl, $file, $path="images/uploaded/") {
echo "function chamada!";
if ($picurl) {
$picFileName=rand(1,9999).$_SESSION['id'];
$picExt=substr(strstr($picurl,'.'),1,3);
$picExt=strtolower($picExt);
$allowed = array("jpg","png","gif","bmp");
if (in_array($picExt,$allowed)) {
if (getimagesize($file)) {
$picNewName=str_replace(" ","_",$picFileName.'.'.$picExt);
$picWhereTo=$path.$picNewName;
$copy=move_uploaded_file($file, $picWhereTo);
if ($copy) {
list($width, $height) = getimagesize($picWhereTo);
$size = $this->resize_values($width,$height,250,250);
$thumb = imagecreatetruecolor($size['width'],$size['height']);
imagealphablending($thumb, false);
$source = imagecreatefromjpeg($picWhereTo);
imagecopyresized($thumb,$source,0,0,0,0,$size['width'],$size['height'],$width,$height);
$picNewName=$picFileName.'_thumb.'.$picExt;
imagejpeg($thumb,$path.$picNewName);
$picinfo['where']=$picWhereTo;
$picinfo['name']=$picNewName;
return $picinfo;
}
else return false;
}
else return false;
}
else return false;
}
}
}
?>
I've ran into a similar problem like this. This has to do with png's with transparency.
Give this a shot after you create $thumb using imagecreatetruecolor();
imagealphablending($thumb, false);
I'm not entirely certain this is the solution - but I think its along the right track. Your true color supports alpha blending - and it is blending in the background from the jpeg - and it might be confused by the lack of information.
If this doesn't work, please describe the exact image format you are uploading so we can try it out and see what happens.
Change your
$source = imagecreatefromjpeg($file);
to
$source = imagecreatefromjpeg($picWhereTo);
And this is how you call the function
$objoflclass->image($_FILES['img']['name'],$_FILES['img']['tmp_name'],'');
where $_FILES['img'] is the name of the image upload field and i believe from this u can understand what was the problem

Thumbnail generation time

Idea
I have a function that checks to see if a thumbnail exists in cache folder for a particular image. If it does, it returns the path to that thumbnail. If it does not, it goes ahead and generates the thumbnail for the image, saves it in the cache folder and returns the path to it instead.
Problem
Let's say I have 10 images but only 7 of them have their thumbnails in the cache folder. Therefore, the function goes to generation of thumbnails for the rest 3 images. But while it does that, all I see is a blank, white loading page. The idea is to display the thumbnails that are already generated and then generate the ones that do not exist.
Code
$images = array(
"http://i49.tinypic.com/4t9a9w.jpg",
"http://i.imgur.com/p2S1n.jpg",
"http://i49.tinypic.com/l9tow.jpg",
"http://i45.tinypic.com/10di4q1.jpg",
"http://i.imgur.com/PnefW.jpg",
"http://i.imgur.com/EqakI.jpg",
"http://i46.tinypic.com/102tl09.jpg",
"http://i47.tinypic.com/2rnx6ic.jpg",
"http://i50.tinypic.com/2ykc2gn.jpg",
"http://i50.tinypic.com/2eewr3p.jpg"
);
function get_name($source) {
$name = explode("/", $source);
$name = end($name);
return $name;
}
function get_thumbnail($image) {
$image_name = get_name($image);
if(file_exists("cache/{$image_name}")) {
return "cache/{$image_name}";
} else {
list($width, $height) = getimagesize($image);
$thumb = imagecreatefromjpeg($image);
if($width > $height) {
$y = 0;
$x = ($width - $height) / 2;
$smallest_side = $height;
} else {
$x = 0;
$y = ($height - $width) / 2;
$smallest_side = $width;
}
$thumb_size = 200;
$thumb_image = imagecreatetruecolor($thumb_size, $thumb_size);
imagecopyresampled($thumb_image, $thumb, 0, 0, $x, $y, $thumb_size, $thumb_size, $smallest_side, $smallest_side);
imagejpeg($thumb_image, "cache/{$image_name}");
return "cache/{$image_name}";
}
}
foreach($images as $image) {
echo "<img src='" . get_thumbnail($image) . "' />";
}
To elaborate on #DCoder's comment, what you could do is;
If the thumb exists in the cache, return the URL just as you do now. This will make sure that thumbs that are in the cache will load quickly.
If the thumb does not exist in the cache, return an URL similar to /cache/generatethumb.php?http://i49.tinypic.com/4t9a9w.jpg where the script generatethumb.php generates the thumbnail, saves it in the cache and returns the thumbnail. Next time, it will be in the cache and the URL won't go through the PHP script.

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