PHP - Duplicating $_FILES superglobal - php

I have a PHP function that I use regularly for working with images (resizing, watermarking, converting to grayscale, etc). I am happy with it and it works well. However, it is designed to work with the $_FILES superglobal, and accepts it as a parameter.
I've run into a situation where I have an existing directory of files on my server that I need to process in the same way as I do for files uploaded from a form into the $_FILES array.
Figuring it would be easiest to work with my existing function, I have been looking for a way to duplicate the $_FILES superglobal, so I can pass it to my script, but I am not finding the functions/properties I need to accomplish this. (Although, at a glance, the getimagesize and filesize functions looks like they may help).
Can anyone advise on what functions/properties I would need to duplicate the $_FILES array? (Or an alternate way to accomplish what I am trying to do?)
For reference's sake, the image function I use is here:
function resize_upload ($file, $dest, $maxw = 50, $maxh = 50, $grey = false, $wm = false, $mark = "a/i/watermark.png", $opa = 40) {
$allowext = array("gif", "jpg", "png", "jpeg", "bmp");
$fileext = strtolower(getExtension($file['name']));
if (!in_array($fileext,$allowext)) {
echo "Wrong file extension.";
exit();
}
list($width, $height, $imgcon) = getimagesize($file['tmp_name']);
if ($file['size'] && ($width > $maxw || $height > $maxh)) {
if($file['type'] == "image/pjpeg" || $file['type'] == "image/jpeg"){$newimg = imagecreatefromjpeg($file['tmp_name']);}
elseif($file['type'] == "image/x-png" || $file['type'] == "image/png"){$newimg = imagecreatefrompng($file['tmp_name']);}
elseif($file['type'] == "image/gif"){$newimg = imagecreatefromgif($file['tmp_name']);}
$ratio = $width/$height;
if ($ratio < 1) { // Width < Height
$newheight = $maxh;
$newwidth = $width * ($maxh/$height);
if ($newwidth > $maxw) {
$newheight = $newheight * ($maxw/$newwidth);
$newwidth = $maxw;
}
} elseif ($ratio == 1) { // Width = Height
if ($maxw < $maxh) {
$newheight = $maxw;
$newwidth = $maxw;
} elseif ($maxw == $maxh) {
$newheight = $maxh;
$newwidth = $maxw;
} elseif ($maxw > $maxh) {
$newheight = $maxh;
$newwidth = $maxh;
}
} elseif ($ratio > 1) { // Width > Height
$newwidth = $maxw;
$newheight = $height * ($maxw/$width);
if ($newheight > $maxh) {
$newwidth = $newwidth * ($maxh/$newheight);
$newheight = $maxh;
}
}
if (function_exists(imagecreatetruecolor)) {$resize = imagecreatetruecolor($newwidth, $newheight);}
if (($imgcon == IMAGETYPE_GIF)) {
$trnprt_indx = imagecolortransparent($newimg);
if ($trnprt_indx >= 0) {
$trnprt_color = imagecolorsforindex($newimg, $trnprt_indx);
$trnprt_indx = imagecolorallocate($resize, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
imagefill($resize, 0, 0, $trnprt_indx);
imagecolortransparent($resize, $trnprt_indx);
}
} elseif ($imgcon == IMAGETYPE_PNG) {
imagealphablending($resize, false);
$color = imagecolorallocatealpha($resize, 0, 0, 0, 127);
imagefill($resize, 0, 0, $color);
imagesavealpha($resize, true);
}
imagecopyresampled($resize, $newimg, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
if ($wm) {
$watermark = imagecreatefrompng($mark);
$wm_width = imagesx($watermark);
$wm_height = imagesy($watermark);
$destx = $newwidth - $wm_width - 5;
$desty = $newheight - $wm_height - 5;
imagecopymerge($resize, $watermark, $destx, $desty, 0, 0, $wm_width, $wm_height, $opa);
imagedestroy($watermark);
}
$filename = random_name().".".$fileext;
if ($grey) {imagefilter($resize, IMG_FILTER_GRAYSCALE);}
if($file['type'] == "image/pjpeg" || $file['type'] == "image/jpeg"){$new = imagejpeg($resize, $dest."/".$filename, 100);}
elseif($file['type'] == "image/x-png" || $file['type'] == "image/png"){$new = imagepng($resize, $dest."/".$filename, 0);}
elseif($file['type'] == "image/gif"){$new = imagegif($resize, $dest."/".$filename);}
imagedestroy($resize);
imagedestroy($newimg);
return $filename;
} elseif ($file['size']) {
$filename = random_name().".".getExtension($file['name']);
if ($grey) {
if($file['type'] == "image/pjpeg" || $file['type'] == "image/jpeg"){$newimg = imagecreatefromjpeg($file['tmp_name']);}
elseif($file['type'] == "image/x-png" || $file['type'] == "image/png"){$newimg = imagecreatefrompng($file['tmp_name']);}
elseif($file['type'] == "image/gif"){$newimg = imagecreatefromgif($file['tmp_name']);}
imagefilter($newimg, IMG_FILTER_GRAYSCALE);
if($file['type'] == "image/pjpeg" || $file['type'] == "image/jpeg"){imagejpeg($newimg, $dest."/".$filename);}
elseif($file['type'] == "image/x-png" || $file['type'] == "image/png"){imagepng($newimg, $dest."/".$filename);}
elseif($file['type'] == "image/gif"){imagegif($newimg, $dest."/".$filename);}
imagedestroy($newimg);
return $filename;
} else {
$upload = file_upload($file, $dest);
return $upload;
}
}
}

The $_FILES array contains a nested array for an uploaded file. This nested array has 5 keys. For each key I explain what it should contain, and what function to use:
name: the name of the file, use the basename() function for this entry
type: the mime type of the file, for images set to 'image/png', 'image/jpeg', etc
tmp_name: the path to the actual file, here you should set the path to your images
error: this indicates that an error occured with the upload, in your case you can set it to 0 for no error
size: the size of the file in bytes, so you can use the filesize() function for your image
An example:
$_FILES = array('image' => array(
'name' => basename('/path/to/image.png'),
'type' => 'image/png',
'tmp_name' => '/path/to/image.png',
'error' => 0,
'size' => filesize('/path/to/image.png')
));
If you want to process multiple files at once, you should be aware that the structure of the $_FILES array is different than what you would expect in this case, see this comment in the PHP docs.

Related

Error Resize image in Shared hosting (Cpanel)

I have a problem about resize image at hosting.
When i use function to resize image in Localhost, it's good.
But when i upload them to Cpanel. It's only work with small size picture. With bigger size(maybe 300kb), it doesn't work and doesn't
show any errors. How to fix it?
Please help me!
Command :
resize_image('max',"upload/tindang/".$Hinh,"upload/tindang/".$Hinh,600,600);
This is my function :
function resize_image_crop($image,$width,$height) {
$w = #imagesx($image); //current width
$h = #imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed
//try max width first...
$ratio = $width / $w;
$new_w = $width;
$new_h = $h * $ratio;
//if that created an image smaller than what we wanted, try the other way
if ($new_h < $height) {
$ratio = $height / $h;
$new_h = $height;
$new_w = $w * $ratio;
}
$image2 = imagecreatetruecolor ($new_w, $new_h);
imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
//check to see if cropping needs to happen
if (($new_h != $height) || ($new_w != $width)) {
$image3 = imagecreatetruecolor ($width, $height);
if ($new_h > $height) { //crop vertically
$extra = $new_h - $height;
$x = 0; //source x
$y = round($extra / 2); //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
} else {
$extra = $new_w - $width;
$x = round($extra / 2); //source x
$y = 0; //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
}
imagedestroy($image2);
return $image3;
} else {
return $image2;
}
}
function resize_image_max($image,$max_width,$max_height) {
$w = imagesx($image); //current width
$h = imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
// if (($w <= $max_width) && ($h <= $max_height)) { return $image; } //no resizing needed
//try max width first...
$ratio = $max_width / $w;
$new_w = $max_width;
$new_h = $h * $ratio;
//if that didn't work
if ($new_h > $max_height) {
$ratio = $max_height / $h;
$new_h = $max_height;
$new_w = $w * $ratio;
}
$new_image = imagecreatetruecolor ($new_w, $new_h);
imagecopyresampled($new_image,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
return $new_image;
}
function resize_image_force($image,$width,$height) {
$w = #imagesx($image); //current width
$h = #imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed
$image2 = imagecreatetruecolor ($width, $height);
imagecopyresampled($image2,$image, 0, 0, 0, 0, $width, $height, $w, $h);
return $image2;
}
function resize_image($method,$image_loc,$new_loc,$width,$height) {
if (!is_array(#$GLOBALS['errors'])) { $GLOBALS['errors'] = array(); }
if (!in_array($method,array('force','max','crop'))) { $GLOBALS['errors'][] = 'Invalid method selected.'; }
if (!$image_loc) { $GLOBALS['errors'][] = 'No source image location specified.'; }
else {
if ((substr(strtolower($image_loc),0,7) == 'http://') || (substr(strtolower($image_loc),0,7) == 'https://')) { /*don't check to see if file exists since it's not local*/ }
elseif (!file_exists($image_loc)) { $GLOBALS['errors'][] = 'Image source file does not exist.'; }
$extension = strtolower(substr($image_loc,strrpos($image_loc,'.')));
if (!in_array($extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid source file extension!'; }
}
if (!$new_loc) { $GLOBALS['errors'][] = 'No destination image location specified.'; }
else {
$new_extension = strtolower(substr($new_loc,strrpos($new_loc,'.')));
if (!in_array($new_extension,array('.jpg','.jpeg','.png','.gif','.bmp'))) { $GLOBALS['errors'][] = 'Invalid destination file extension!'; }
}
$width = abs(intval($width));
if (!$width) { $GLOBALS['errors'][] = 'No width specified!'; }
$height = abs(intval($height));
if (!$height) { $GLOBALS['errors'][] = 'No height specified!'; }
if (count($GLOBALS['errors']) > 0) { echo_errors(); return false; }
if (in_array($extension,array('.jpg','.jpeg'))) { $image = #imagecreatefromjpeg($image_loc); }
elseif ($extension == '.png') { $image = #imagecreatefrompng($image_loc); }
elseif ($extension == '.gif') { $image = #imagecreatefromgif($image_loc); }
elseif ($extension == '.bmp') { $image = #imagecreatefromwbmp($image_loc); }
if (!$image) { $GLOBALS['errors'][] = 'Image could not be generated!'; }
else {
$current_width = imagesx($image);
$current_height = imagesy($image);
if ((!$current_width) || (!$current_height)) { $GLOBALS['errors'][] = 'Generated image has invalid dimensions!'; }
}
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); echo_errors(); return false; }
if ($method == 'force') { $new_image = resize_image_force($image,$width,$height); }
elseif ($method == 'max') { $new_image = resize_image_max($image,$width,$height); }
elseif ($method == 'crop') { $new_image = resize_image_crop($image,$width,$height); }
if ((!$new_image) && (count($GLOBALS['errors'] == 0))) { $GLOBALS['errors'][] = 'New image could not be generated!'; }
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); echo_errors(); return false; }
$save_error = false;
if (in_array($extension,array('.jpg','.jpeg'))) { imagejpeg($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.png') { imagepng($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.gif') { imagegif($new_image,$new_loc) or ($save_error = true); }
elseif ($extension == '.bmp') { imagewbmp($new_image,$new_loc) or ($save_error = true); }
if ($save_error) { $GLOBALS['errors'][] = 'New image could not be saved!'; }
if (count($GLOBALS['errors']) > 0) { #imagedestroy($image); #imagedestroy($new_image); echo_errors(); return false; }
imagedestroy($image);
imagedestroy($new_image);
return true;
}

Image crop function not working in Wordpress

I have used this following function in my localhost which is working fine
// Image cropping
function cropImage($sourcePath, $thumbSize, $destination = null) {
$parts = explode('.', $sourcePath);
$ext = $parts[count($parts) - 1];
if ($ext == 'jpg' || $ext == 'jpeg') {
$format = 'jpg';
} else {
$format = 'png';
}
if ($format == 'jpg') {
$sourceImage = imagecreatefromjpeg($sourcePath);
}
if ($format == 'png') {
$sourceImage = imagecreatefrompng($sourcePath);
}
list($srcWidth, $srcHeight) = getimagesize($sourcePath);
// calculating the part of the image to use for thumbnail
if ($srcWidth > $srcHeight) {
$y = 0;
$x = ($srcWidth - $srcHeight) / 2;
$smallestSide = $srcHeight;
} else {
$x = 0;
$y = ($srcHeight - $srcWidth) / 2;
$smallestSide = $srcWidth;
}
$destinationImage = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
if ($destination == null) {
header('Content-Type: image/jpeg');
if ($format == 'jpg') {
imagejpeg($destinationImage, null, 100);
}
if ($format == 'png') {
imagejpeg($destinationImage);
}
if ($destination = null) {
}
} else {
if ($format == 'jpg') {
imagejpeg($destinationImage, $destination, 100);
}
if ($format == 'png') {
imagepng($destinationImage, $destination);
}
}
}
But i am using this in my wordpress theme and it is showing some errors
����JFIF����?I��^��l�i�����76����6m�0ib�~���X��KR����J��W�9��.�7wK~��J��)�J��)�.�������A�_�]�pw��#��'��{1M{���5���7�#X��|�w�#9W^�t�]������t}ms�l���%���W{���G��1T+8�2s���0a��3�XX� �yL��FrU��#�Y٦'���r���{g��簪�;c�[�0r0q�q���N9��G��{?�c�w�K�ӯE�|ެ�Td2���F�?!#�G�z>ЀP�����u۝�ᓒ����d��A8��9't��=���b���'#'ג}O��\����P�S�]���o�h�Zy$|�Ns�q��Y��t8f+�O�
I have used this code for showing the image
$docimg = $doctor_img['url'];
if ($docimg):
?>
<?php cropImage( $docimg, 200, null); ?>
Is there anything to change in this code. So that i can get the image src instead of wired characters
I have found a solution for this,but i cant understand what will happen if png file will come.
ob_start();
header( "Content-type: image/jpeg" );
cropImage( $docimg, 200, null);
$i = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>";
Because as you see, there is written for jpeg file only.
here is the working example
$parts = explode('.', $docimg);
$ext = $parts[count($parts) - 1];
if ($ext == 'jpg' || $ext == 'jpeg') {
$format = 'jpg';
} else {
$format = 'png';
}
ob_start();
header( "Content-type: image/".$format );
cropImage( $docimg, 200, null);

Resizing images php form

i have two type of image upload :
first high resolution :
$specialImages = count($_FILES['specialImg']['name']);
$specialMinwidth = 3000;
$specialMinheight = 2500;
$urlSpecialImages = array();
if ($specialImages) {
for ($i=1; $i<=$specialImages; $i++) {
if ($_FILES['specialImg']['name'][$i] != "") {
if ((($_FILES['specialImg']['type'][$i] == "image/pjpeg") ||
($_FILES['specialImg']['type'][$i] == "image/jpeg") ||
($_FILES['specialImg']['type'][$i] == "image/png")) &&
($_FILES['specialImg']['size'][$i] < $this->return_bytes(ini_get('post_max_size')))) {
list($width, $height, $type, $attr) = getimagesize($_FILES['specialImg']['tmp_name'][$i]);
if ($width >= $specialMinwidth && $height >= $specialMinheight) {
$urlSpecialImages[$i] = $_FILES['specialImg']['tmp_name'][$i];
}
else {
$this->errors[] = $this->module->l("L'image doit être au format minimum de 3000px x 2500px", 'addproduct');
}
second low resolution :
$images = count($_FILES['images']['name']);
$minwidth = 1500;
$minheight = 1500;
if ($images <= Configuration::get('JMARKETPLACE_MAX_IMAGES')) {
for ($i=1; $i<=Configuration::get('JMARKETPLACE_MAX_IMAGES'); $i++) {
if ($_FILES['images']['name'][$i] != "") {
if ((($_FILES['images']['type'][$i] == "image/pjpeg") ||
($_FILES['images']['type'][$i] == "image/jpeg") ||
($_FILES['images']['type'][$i] == "image/png")) &&
($_FILES['images']['size'][$i] < $this->return_bytes(ini_get('post_max_size')))) {
list($width, $height, $type, $attr) = getimagesize($_FILES['images']['tmp_name'][$i]);
if ($width == $minwidth && $height == $minheight) {
$url_images[$i] = $_FILES['images']['tmp_name'][$i];
}
else {
$this->errors[] = $this->module->l('The image format need to be 1500 x 1500 pixels', 'addproduct');
}
i want to use the special $specialImages uploaded and resize them to . 1500x1500 on images low resolution !
because i want to get both resolution by one upload ! how can i do that ?
Image resize function example:
function resizeImage($file = 'image.png', $maxwidth = 1366){
error_reporting(0);
$image_info = getimagesize($file);
$image_width = $image_info[0];
$image_height = $image_info[1];
$ratio = $image_width / $maxwidth;
$info = getimagesize($file);
if ($image_width > $maxwidth) {
// GoGoGo
$newwidth = $maxwidth;
$newheight = (int)($image_height / $ratio);
if ($info['mime'] == 'image/jpeg') {
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
echo imagejpeg($thumb,$file,90);
}
if ($info['mime'] == 'image/jpg') {
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($file);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
echo imagejpeg($thumb,$file,90);
}
if ($info['mime'] == 'image/png') {
$im = imagecreatefrompng($file);
$im_dest = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($im_dest, false);
imagecopyresampled($im_dest, $im, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
imagesavealpha($im_dest, true);
imagepng($im_dest, $file, 9);
}
if ($info['mime'] == 'image/gif') {
$im = imagecreatefromgif($file);
$im_dest = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($im_dest, false);
imagecopyresampled($im_dest, $im, 0, 0, 0, 0, $newwidth, $newheight, $image_width, $image_height);
imagesavealpha($im_dest, true);
imagegif($im_dest, $file);
}
}}
Use:
resizeImage('D:\tmp\11.png', 1366);

Image doesn't display

I have this code, I want to resize the picture, it manage to do the first one which 100x100 but not the others. I don't see why it doesn't work, it doesn't have any error. I'm a php newbie, doesn't really know what went wrong, but as you can see as the code does works for the 1st one but why doesn't work for the others?
<?php
function thumbnail($image, $width, $height) {
$image_properties = getimagesize($image);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$image_ratio = $image_width / $image_height;
$type = $image_properties["mime"];
if(!$width && !$height) {
$width = $image_width;
$height = $image_height;
}
if(!$width) {
$width = round($height * $image_ratio);
}
if(!$height) {
$height = round($width / $image_ratio);
}
if($type == "image/jpeg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($image);
} elseif($type == "image/png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($image);
} elseif($type == "image/gif") {
header('Content-type: image/gif');
$thumb = imagecreatefromgif($image);
}
else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
imagecopyresampled($temp_image, $thumb, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
$thumbnail = imagecreatetruecolor($width, $height);
imagecopyresampled($thumbnail, $temp_image, 0, 0, 0, 0, $width, $height, $width, $height);
if($type == "image/jpeg") {
imagejpeg($thumbnail);
}
elseif($type == "image/jpeg") {
imagepng($thumbnail);
}
elseif($type == "image/gif") {
imagegif($thumbnail);
}
imagedestroy($temp_image);
imagedestroy($thumbnail);
}
$pic_size = array();
// Adjust size
$pic_size['height'][0] = 100;
$pic_size['width'][0] = 100;
$pic_size['height'][1] = 200;
$pic_size['width'][1] = 200;
$pic_size['height'][2] = 300;
$pic_size['width'][2] = 300;
$pic_size['height'][3] = 400;
$pic_size['width'][3] = 400;
$pic_size['height'][4] = 500;
$pic_size['width'][4] = 500;
$total_pic_size= count($pic_size['height']);
$x = 0;
foreach(array_keys($pic_size['height']) as $x) {
thumbnail($_GET["img"], $pic_size['width'][$x], $pic_size['height'][$x]);
echo '<img src="index.php?w='.$pic_size['width'][$x].'&h='.$pic_size['height'][$x].'&img='.$_GET["img"].'" />';
$x++;
}
?>
You iterate only two times, because
$total_pic_size= count($pic_size);// is 2
Change that to:
$total_pic_size= count($pic_size['height']);
Or use foreach:
foreach(array_keys($pic_size['height']) as $x)
And don't use COUNT_RECURSIVE here, it will return wrong number again, counting in the width and height keys.
Also thumbnail function has header call in it, which cannot be called after echo, which in your case, is called after echo, in your loop. You should see the warning saying "Headers already sent".
You can save the image to file and echo image with file path as a source. Remove the header calls and let your thumbnail function save it and return the file name, for example:
imagejpeg($thumbnail, $filename);
return $filename;
and use the output as src of the echoed image.
Your $total_pic_size is always 2.
$total_pic_size = count( $pic_size['width'] );
This will give you the correct number of items and the loop should run not only once.
You should also change the loop-condition:
while ($x <= $total_pic_size) {
#Update 1
You can try something like this:
// ...
$pic_sizes[0]['height'] = 100;
$pic_sizes[0]['width'] = 100;
$pic_sizes[1]['height'] = 200;
$pic_sizes[1]['width'] = 200;
$pic_sizes[2]['height'] = 300;
$pic_sizes[2]['width'] = 300;
$pic_sizes[3]['height'] = 400;
$pic_sizes[3]['width'] = 400;
$pic_sizes[4]['height'] = 500;
$pic_sizes[4]['width'] = 500;
$img = $_GET["img"];
foreach ($pic_sizes as $pic_size) {
thumbnail($img, $pic_size['width'], $pic_size['height']);
echo '<img src="index.php?w='.$pic_size['width'].'&h='.$pic_size['height'].'&img='.$img.'" />';
}
#Update 2:
You already accepted another answere, but maybe this is also helpful for you. i found some more errors and logic-problems in your code... the code below works (without saving the thumbs).
<?php
function thumbnail($image, $width, $height) {
$image_properties = getimagesize($image);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$image_ratio = $image_width / $image_height;
$type = $image_properties["mime"];
if(!$width && !$height) {
$width = $image_width;
$height = $image_height;
}
if(!$width) {
$width = round($height * $image_ratio);
}
if(!$height) {
$height = round($width / $image_ratio);
}
if($type == "image/jpeg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($image);
} elseif($type == "image/png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($image);
} elseif($type == "image/gif") {
header('Content-type: image/gif');
$thumb = imagecreatefromgif($image);
}
else {
return false;
}
$temp_image = imagecreatetruecolor($width, $height);
imagecopyresampled($temp_image, $thumb, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
$thumbnail = imagecreatetruecolor($width, $height);
imagecopyresampled($thumbnail, $temp_image, 0, 0, 0, 0, $width, $height, $width, $height);
if($type == "image/jpeg") {
imagejpeg($thumbnail);
}
elseif($type == "image/png") {
imagepng($thumbnail);
}
elseif($type == "image/gif") {
imagegif($thumbnail);
}
imagedestroy($temp_image);
imagedestroy($thumbnail);
}
$img = $_GET["img"];
$gen = #$_GET["gen"];
$w = #$_GET["w"];
$h = #$_GET["h"];
if ( !$gen ) {
$pic_sizes = array();
// Adjust size
$pic_sizes[0]['height'] = 100;
$pic_sizes[0]['width'] = 100;
$pic_sizes[1]['height'] = 200;
$pic_sizes[1]['width'] = 200;
$pic_sizes[2]['height'] = 300;
$pic_sizes[2]['width'] = 300;
$pic_sizes[3]['height'] = 400;
$pic_sizes[3]['width'] = 400;
$pic_sizes[4]['height'] = 500;
$pic_sizes[4]['width'] = 500;
foreach ($pic_sizes as $pic_size) {
echo '<img src="'.$_SERVER['PHP_SELF'].'?w='.$pic_size['width'].'&h='.$pic_size['height'].'&img='.$img.'&gen=1" />';
}
} else {
thumbnail($img, $w, $h);
}

Php resize width fix

I have this function in PHP.
<?php
function zmensi_obrazok($max_dimension, $image_max_width, $image_max_height, $dir, $obrazok, $obrazok_tmp, $obrazok_size, $filename){
$postvars = array(
"image" => $obrazok,
"image_tmp" => $obrazok_tmp,
"image_size" => $obrazok_size,
"image_max_width" => $image_max_width,
"image_max_height" => $image_max_height
);
// Array of valid extensions.
$valid_exts = array("jpg","jpeg","gif","png");
// Select the extension from the file.
$ext = end(explode(".",strtolower($obrazok)));
// Check not larger than 175kb.
if($postvars["image_size"] <= 256000){
// Check is valid extension.
if(in_array($ext,$valid_exts)){
if($ext == "jpg" || $ext == "jpeg"){
$image = imagecreatefromjpeg($postvars["image_tmp"]);
}
else if($ext == "gif"){
$image = imagecreatefromgif($postvars["image_tmp"]);
}
else if($ext == "png"){
$image = imagecreatefrompng($postvars["image_tmp"]);
}
list($width,$height) = getimagesize($postvars["image_tmp"]);
if($postvars["image_max_width"] > $postvars["image_max_height"]){
if($postvars["image_max_width"] > $max_dimension){
$newwidth = $max_dimension;
}
else
{
$newwidth = $postvars["image_max_width"];
}
}
else
{
if($postvars["image_max_height"] > $max_dimension)
{
$newheight = $max_dimension;
}
else
{
$newheight = $postvars["image_max_height"];
}
}
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
imagejpeg($tmp,$filename,100);
return "fix";
imagedestroy($image);
imagedestroy($tmp);
}
}
}
?>
Now if I want to use it, and I upload image for example 500x300px and I have set max size to 205x205px it don't want to make resized picture proportion. It make something like 375x205 (height is still OK). Can somebody help how to fix it?
Just scale your image twice, once to match the width, once to match the height. To save on processing, get your scaling first, then do the resizing:
$max_w = 205;
$max_h = 205;
$img_w = ...;
$img_h = ...;
if ($img_w > $max_w) {
$img_h = $img_h * $max_w / $img_w;
$img_w = $max_w;
}
if ($img_h > $max_h) {
$img_w = $img_w * $max_h / $img_h;
$img_h = $max_h;
}
// $img_w and $img_h should now have your scaled down image complying with both restrictions.

Categories