Php resize width fix - php

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.

Related

PHP thumbnail with white background and not centralized

I have the following php script to create thumbnail after uploading an image. It is working properly, but it creates a black background and does not center the image if it is not the size you want, does anyone know how to leave the white background and center it?
How to fix it
https://imgur.com/a/uTrPadZ
if($_SERVER['REQUEST_METHOD']=='POST')
{
$filetmp = $_FILES["image"]["tmp_name"];
$filename = $_FILES["image"]["name"];
$filetype = $_FILES["image"]["type"];
$filesize = $_FILES["image"]["size"];
$fileinfo = getimagesize($_FILES["image"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../uploads/";
$filepath_thumb = "../thumbnail/";
if($filetmp == "")
{
echo "please select a photo";
}
else
{
if($filesize > 2097152)
{
echo "photo > 2mb";
}
else
{
if($filetype != "image/jpeg" && $filetype != "image/png" && $filetype != "image/gif")
{
echo "Please upload jpg / png / gif";
}
else
{
$final_image = rand(1000,1000000).$filename;
$filepath = $filepath.strtolower($final_image);
move_uploaded_file($filetmp,$filepath);
if($filetype == "image/jpeg")
{
$imagecreate = "imagecreatefromjpeg";
$imageformat = "imagejpeg";
}
if($filetype == "image/png")
{
$imagecreate = "imagecreatefrompng";
$imageformat = "imagepng";
}
if($filetype == "image/gif")
{
$imagecreate= "imagecreatefromgif";
$imageformat = "imagegif";
}
$new_width = "200";
$new_height = "200";
$filepath_thumb = $filepath_thumb.strtolower($final_image);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = $imagecreate($filepath); //photo folder
if($filewidth > $fileheight)
{
$thumb_w = $new_width;
$thumb_h = $fileheight*($new_height/$filewidth);
}
if($filewidth < $fileheight)
{
$thumb_w = $filewidth*($new_width/$fileheight);
$thumb_h = $new_height;
}
if($filewidth == $fileheight)
{
$thumb_w = $new_width;
$thumb_h = $new_height;
}
$dst_img = ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($image_p,$image,0,0,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
}
}
}
}
Black is the default background, you just have to set the background colour of the new image to white first.
//set background colour white before copying
$white = imagecolorallocate($image_p, 255, 255, 255);
imagefill($image_p, 0, 0, $white);
imagecopyresampled($image_p,$image,0,0,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
Also, $dst_img doesn't appear to be used.
Centering (untested, but simple enough math):
$xOffset = (imagesx($p_image)-$thumb_w) / 2;
$yOffset = (imagesy($p_image)-$thumb_h) / 2;
imagecopyresampled($image_p,$image,$offsetX,$offsetY,0,0,$thumb_w,$thumb_h,$filewidth,$fileheight);
If you know which dimension does not match the new thumbnail dimension this could be simplified.

Directory being deleted randomly by unknown script

I have set up a simple "Facebook" like timeline system for my friend to be able to upload statuses with images for his users to see. It seemed to all be working well although the file which stores the images keeps being deleted, and I can't seem to purposely cause the problem myself so I have no idea what is removing this directory?
I have added the upload/remove scripts below to see if anybody might be able to assist me here? I can't seem to find any part of the script which would delete the main image directory on its own?
PLEASE BARE IN MIND - This is still unfinished, and is nowhere near secure just yet, we are in testing phase and need to fix this problem before I can work on perfecting the system.
The main folder for storage of the images is post_images, this is the directory which is being deleted.
REMOVE DIR FUNCTION -
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
}
rmdir($dir);
}
DECLINE POSTS -
if(isset($_GET['decline_post'])){
$post_id = $conn->real_escape_string($_GET['decline_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
DELETE POST -
if(isset($_GET['delete_post'])){
$post_id = $conn->real_escape_string($_GET['delete_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
UPLOAD POST -
if(isset($_POST['new_post'])){
$post_status = $conn->real_escape_string($_POST['status']);
$user_id = $_SESSION['user_id'];
if(!empty($_FILES['images']['tmp_name'])){
$length = 9;
$search = true; // allow the loop to begin
while($search == true) {
$rand_image_folder = substr(str_shuffle("0123456789"), 0, $length);
if (!file_exists('../post_images/'.$rand_image_folder)) {
$search = false;
}
}
mkdir("../post_images/".$rand_image_folder);
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['images']['name'][$key];
$file_size = $_FILES['images']['size'][$key];
$file_tmp = $_FILES['images']['tmp_name'][$key];
$file_type = $_FILES['images']['type'][$key];
$check_file_type = substr($file_type, 0, strrpos( $file_type, '/'));
if($check_file_type !== 'image'){
header('Location: ../members_area.php?posterror=1');
}
$extensions = array("jpeg","jpg","png","JPEG","JPG","PNG");
$format = trim(substr($file_type, strrpos($file_type, '/') + 1));
if(in_array($format,$extensions) === false){
header('Location: ../members_area.php?posterror=1');
} else {
move_uploaded_file($file_tmp,"../post_images/".$rand_image_folder."/".$file_name);
$file = "../post_images/".$rand_image_folder."/".$file_name;
$cut_name = substr($file, strpos($file, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = "../post_images/".$rand_image_folder."/thb_".$cut_name;
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = '350';
$max_height = '250';
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
}
}
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','$rand_image_folder','0','$post_public')");
} else {
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','','0','$post_public')");
}
header('Location: ../members_area.php?posterror=2');
}

Resize images and fit each image into the square mantaining aspect ratio (backend)

I don't have any experience with PHP and images in general, but I have a need to resize all images into the square when they get uploaded.
Since I have multiple products and they have different pictures that comes in different sizes, I think that the best approach is to 'standardize' them during the upload by taking an image and 'fitting' it into the 800x800 white square while maintaining the aspect ratio (if longest size >800 then downsize, if longest size <800, then re-size).
My initial solution was created via JavaScript, where I tried to find the biggest picture and resize all other images according to it. Although, it is not very useful and can be faulty since if there is a delay in image load, images might not be loaded for JS to perform the operation, thus not showing images at all.
$product = getProductById($productid);
$filesArray = array();
if (isset($_GET['files']) && $productid > 0) {
$error = false;
$files = array();
$fileName = '';
$uploaddir = "../images/products/";
foreach ($_FILES as $file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$random_name = $widgets->randomFileName();
$randomFullFileName = $productid .'_'. $random_name . '.' . $ext;
//copy to location
//----------------
//HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
//----------------
if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
//save to database
$image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
if ($image_id > 0) {
echo 'Added new image';
} else {
echo 'Error, unable to add. <br> Please try again.';
}
} else {
echo 'Error, unable to add. <br> Please try again.';
}
}
}
Before: 600x300
After: 800x800 with white borders to fill-in the space
You can try this approach (tested). It will fit your images into an 800x800 square canvas while maintaining the aspect ratio of your images.
resize_image(): This function will maintain the aspect ratio of your image.
function resize_image($img,$maxwidth,$maxheight) {
//This function will return the specified dimension(width,height)
//dimension[0] - width
//dimension[1] - height
$dimension = array();
$imginfo = getimagesize($img);
$imgwidth = $imginfo[0];
$imgheight = $imginfo[1];
if($imgwidth > $maxwidth){
$ratio = $maxwidth/$imgwidth;
$newwidth = round($imgwidth*$ratio);
$newheight = round($imgheight*$ratio);
if($newheight > $maxheight){
$ratio = $maxheight/$newheight;
$dimension[] = round($newwidth*$ratio);
$dimension[] = round($newheight*$ratio);
return $dimension;
}else{
$dimension[] = $newwidth;
$dimension[] = $newheight;
return $dimension;
}
}elseif($imgheight > $maxheight){
$ratio = $maxheight/$imgheight;
$newwidth = round($imgwidth*$ratio);
$newheight = round($imgheight*$ratio);
if($newwidth > $maxwidth){
$ratio = $maxwidth/$newwidth;
$dimension[] = round($newwidth*$ratio);
$dimension[] = round($newheight*$ratio);
return $dimension;
}else{
$dimension[] = $newwidth;
$dimension[] = $newheight;
return $dimension;
}
}else{
$dimension[] = $imgwidth;
$dimension[] = $imgheight;
return $dimension;
}
}
And now comes your code,
$product = getProductById($productid);
$filesArray = array();
if (isset($_GET['files']) && $productid > 0) {
$error = false;
$files = array();
$fileName = '';
$uploaddir = "../images/products/";
foreach ($_FILES as $file) {
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$random_name = $widgets->randomFileName();
$randomFullFileName = $productid .'_'. $random_name . '.' . $ext;
//copy to location
//----------------
//HERE I NEED TO CREATE A 800x800px SQUARE and fit the image into it
// Create image from file
$image = null;
switch(strtolower($file['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($file['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($file['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($file['tmp_name']);
break;
default:
exit('Unsupported type: '.$file['type']);
}
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Get the new dimensions
$dimension = resize_image($file, 800, 800);
$new_width = $dimension[0];
$new_height = $dimension[1];
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
// Catch and save the image
$status = false;
switch(strtolower($file['type']))
{
case 'image/jpeg':
$status = imagejpeg($new, $uploaddir . $randomFullFileName, 90);
break;
case 'image/png':
$status = imagepng($new, $uploaddir . $randomFullFileName, 0);
break;
case 'image/gif':
$status = imagegif($new, $uploaddir . $randomFullFileName);
break;
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
//save to database
if($status){
$image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
if ($image_id > 0) {
echo 'Added new image';
} else {
echo 'Error, unable to add. <br> Please try again.';
}
}else{
echo 'Error, unable to add. <br> Please try again.';
}
//----------------
//if (move_uploaded_file($file['tmp_name'], $uploaddir . $randomFullFileName)) {
// //save to database
// $image_id = updateProduct('default_image', 'images/products/'.$randomFullFileName, $productid);
// if ($image_id > 0) {
// echo 'Added new image';
// } else {
// echo 'Error, unable to add. <br> Please try again.';
// }
//} else {
// echo 'Error, unable to add. <br> Please try again.';
//}
}
}
Original answer
How about imagine?
Insert this code before //save to database comment:
<?php
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box(800, 800);
$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine
->open($uploaddir . $randomFullFileName)
->thumbnail($size, $mode)
->save($uploaddir . $randomFullFileName);
New answer
As resize is not working like expected (thanks to #Pradeep Sanjaya), I would paste solution based on snippet from link:
/**
* Image resize
* #param string $input Full path to source image
* #param string $output Full path to result image
* #param int $width Width of result image
* #param int $height Height of result image
*/
function resizeImage($input, $output, $width, $height)
{
$imagine = new Imagine\Gd\Imagine();
$size = new Imagine\Image\Box($width, $height);
$mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$resizeimg = $imagine
->open($input)
->thumbnail($size, $mode);
$sizeR = $resizeimg->getSize();
$widthR = $sizeR->getWidth();
$heightR = $sizeR->getHeight();
$preserve = $imagine->create($size);
$startX = $startY = 0;
if ($widthR < $width) {
$startX = ($width - $widthR) / 2;
}
if ($heightR < $height) {
$startY = ($height - $heightR) / 2;
}
$preserve
->paste($resizeimg, new Imagine\Image\Point($startX, $startY))
->save($output);
}
And usage according to original question:
<?php
// placed after `save to database` comment
resizeImage(
$uploaddir . $randomFullFileNamem,
$uploaddir . $randomFullFileName,
800, 800
);

Unable to create thumb, image is black

Am uploading Multiple image from single input and create thumb form all uploaded image on fly But when i run code i get only black image but orginal image is same as uploaded
<?php
$newname = md5(rand() * time());
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
}
}
$orig_directory = "$desired_dir"; //Full image folder
$thumb_directory = "thumb/"; //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = #opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1){ //Check to make sure the folder opened
$allowed_types=array('jpg','jpeg','gif','png');
$file_type=array();
$ext='';
$title='';
$i=0;
while ($file_name = #readdir($dir_handle)) {
/* Skipping the system files: */
if($file_name=='.' || $file_name == '..') continue;
$file_type = explode('.',$file_name); //This gets the file name of the images
$ext = strtolower(array_pop($file_type));
/* Using the file name (withouth the extension) as a image title: */
$title = implode('.',$file_type);
$title = htmlspecialchars($title);
/* If the file extension is allowed: */
if(in_array($ext,$allowed_types)) {
/* If you would like to inpute images into a database, do your mysql query here */
/* The code past here is the code at the start of the tutorial */
/* Outputting each image: */
$nw = 100;
$nh = 100;
$source = "$desired_dir{$file_name}";
$stype = explode(".", $source);
$stype = $stype[count($stype)-1];
$dest = "thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = imagecreatetruecolor($nw, $nh);
$wm = $w/$nw;
$hm = $h/$nw;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} else {
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
imagejpeg($dimg,$dest,100);
}
}
/* Closing the directory */
#closedir($dir_handle);
}
?>
When i run code this how am getting out put file, don't know whats going on can some one help me find the error
Black thumb is created for all type image formate
When i remove the following code from above code it works what does this code does
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,0,$adjusted_width,$nw,$nh,$w,$h);
} else
Problem
The problem is located in the following line:
imagecopyresampled($dimg, $simg, -$int_width, 0, 0, 0, $adjusted_width, $nh, $w, $h);
Why are you using a negative value as destination's x? Your source image is actually put at the left of your target image, so your target image appears empty.
Solution
I invite you to use the following function to resize your image:
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
($targetHeight - $imgTargetHeight) / 2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
Implementation
<?php
$newname = md5(rand() * time());
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files']))
{
$errors = array ();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152000)
{
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors) == true)
{
if (is_dir($desired_dir) == false)
{
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false)
{
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
}
else
{ // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
}
else
{
print_r($errors);
}
}
if (empty($error))
{
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
}
$orig_directory = "$desired_dir"; //Full image folder
$thumb_directory = "thumb/"; //Thumbnail folder
/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = #opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1)
{ //Check to make sure the folder opened
$allowed_types = array ('jpg', 'jpeg', 'gif', 'png');
$file_type = array ();
$ext = '';
$title = '';
$i = 0;
while ($file_name = #readdir($dir_handle))
{
/* Skipping the system files: */
if ($file_name == '.' || $file_name == '..')
continue;
$file_type = explode('.', $file_name); //This gets the file name of the images
$ext = strtolower(array_pop($file_type));
/* Using the file name (withouth the extension) as a image title: */
$title = implode('.', $file_type);
$title = htmlspecialchars($title);
/* If the file extension is allowed: */
if (in_array($ext, $allowed_types))
{
/* If you would like to inpute images into a database, do your mysql query here */
/* The code past here is the code at the start of the tutorial */
/* Outputting each image: */
$nw = 100;
$nh = 100;
$source = "$desired_dir{$file_name}";
$stype = explode(".", $source);
$stype = $stype[count($stype) - 1];
$dest = "thumb/{$file_name}";
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($stype)
{
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
}
}
/* Closing the directory */
#closedir($dir_handle);
}
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
($targetHeight - $imgTargetHeight) / 2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
?>
<form method="post" enctype="multipart/form-data">
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input name="files[]" type="file"/><br/>
<input type="submit"/>
</form>
Note: I am saving as PNG, as if you want a 100x100 image using a non-square image (such as 800x600), and without breaking its aspect ratio, we should put transparency behind the unused space and JPEG do not support it.
This is my code for uploading multiple files and cropping and cropping them.
It uploads the image to a folder, then picks the image, crops it , re-uploads the cropped image and deletes the original image.
Am sure you can play around with this
This is the php code
if(isset($_POST['upload_gal']))
{
$fk_id = $_POST['fk_id'];
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_type=='image/jpeg'||$type=='image/gif'||$type=='image/bmp'||$type=='image/png')
{
$image_info = getimagesize($_FILES["files"]["tmp_name"][$key]);
$image_width = $image_info[0];
$image_height = $image_info[1];
$desired_dir="brand_images/";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0755); // Create directory if it does not exist
}
$locationing="brand_images/$file_name";
move_uploaded_file($file_tmp,$locationing);
$image = imagecreatefromstring(file_get_contents("brand_images/$file_name"));
$rand = rand(111,43943749739349343);
$filename = "brand_images/$rand-33$file_name";
if($image_width >= 840 && $image_height >= 680)
{
$thumb_width = 1200;
$thumb_height = 700;
}else{
$thumb_width = 800;
$thumb_height = 533;
}
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
move_uploaded_file($tmp_name, $filename);
mysql_query("INSERT INTO gallery VALUES('','brand_images/$rand-33$file_name','$fk_id')");
echo"<script>
window.location = document.URL.replace(/#$/, '');
</script>";
}
This is the html
<form action="" enctype="multipart/form-data" method="POST">
<h3 class="no_margin-top">Upload a new image</h3>
<hr>
<input type="hidden" name="fk_id" value="<?php echo $brand->brand_id ?>">
<input name="upload_gal" type="submit" class="btn btn-sm pull-right btn-success" value="Upload">
Upload image: <input type="file" name="files[]" multiple>
<p class="text-danger top-buffer">If image is larger than 800x533, the image would be cropped</p>
</form>
The following code will solve the problem by mapping to the correct imagecreatefrom* function or throw an exception with the invalid image type.
switch(strtolower($stype)) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
case 'jpeg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
default:
throw new \Exception('invalid image type :'.$stype);
break;
}
I think it's better to go for the mime type than the extension.
You'll do this:
function check_supported_type($type)
{
switch($type)
{
case "image/jpeg":
case "image/gif":
case "image/png":
return true;
default:
return false;
}
}
function GetMimeType($file)
{
//$type = mime_content_type($file); //deprecated
/* //file info -> normal method, but returns wrong values for ics files..
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$type = $filename.":".finfo_file($finfo, $filename);
finfo_close($finfo);
*/
$forbiddenChars = array('?', '*', ':', '|', ';', '<', '>');
if(strlen(str_replace($forbiddenChars, '', $file)) < strlen($file))
throw new \ArgumentException("Forbidden characters!");
$file = escapeshellarg($file);
ob_start();
$type = system("file --mime-type -b ".$file);
ob_clean();
return $type;
}
use it like this:
$file = "someimage.jpg";
$mime = GetMimeType($file);
if(check_supported_type($mime))
{
//do your image processing
}
hope this helps
EDIT:
Maybe you can take a look at my other answer: https://stackoverflow.com/a/26981319/3641016 there you'll see how to generate thumbs.
EDIT:
added the answer to your editet question:
replace:
$wm = $w/$nw;
$hm = $h/$nw;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $w / $hm;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} else {
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
with:
if($w > $h)
{
imagecopyresampled($dimg, $simg, 0,0, ($nw / $h * $w / 2 - $nw / 2),0, $nw,$nw, $h,$h);
}
else
{
imagecopyresampled($dimg, $simg, 0,0, 0,($nw / $w * $h / 2 - $nw / 2), $nw,$nw, $w,$w);
}
and everything should be ok. (if the thumb is quadratic)

PHP - Duplicating $_FILES superglobal

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.

Categories