Related
I use following code to upload, rename, compress, create thumbnail everything works fine, And recently i noticed while creating thumb it creates fresh copy of thumb images for previously uploaded images also(create thumbnail for uploaded and uploading images too)
Problem:
When form is submitted it crates thumb for uploading image and uploaded images(image file that are present in older).
how do i solve this problem
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
if
(move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['tmp_name'][$key], 0);
}
} else {
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key + 1) . ' = $row[0];';
eval($codestr);
} else {
$codestr = '$file' . ($key + 1) . ' = NULL;';
eval($codestr);
}
}
}
$orig_directory = "$desired_dir";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$dir_handle = opendir($orig_directory);
if ($dir_handle > 1) {
$allowed_types = array('jpg', 'jpeg', 'gif', 'png');
$file_type = array();
$ext = '';
$title = '';
$i = 0;
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..') {
continue;
}
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
if (in_array($ext, $allowed_types)) {
$nw = 125;
$nh = 90;
$source = "$desired_dir{$file_name}";
$stype1 = explode(".", $source);
$stype = $stype1[count($stype1) - 1];
$dest = "$_SERVER[DOCUMENT_ROOT]/upload/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);
compress($source, "$desired_dir/" . $file_name, 50);
}
}closedir($dir_handle);
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file1, PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file2, PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file3, PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file4, PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: /post/price_plan.php');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$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);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
Bounty Edit
if there is any good and faster function to do please.
all i need is to upload, rename, compress, create thumbnail and save name to DB
The code is need much more optimization. you are iterating the file folder again every time instead of looping the just uploaded files.
$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$file = [];
$nw = 125;
$nh = 90;
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
$file_name_with_ext = $file_name . $sExt;
$source = = $desired_dir . $file_name_with_ext ;
if(!move_uploaded_file($file_tmp, $source)) {
echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
$file[] = NULL;
}else{
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch ($sExt) {
case '.gif':
$simg = imagecreatefromgif($source);
break;
case '.jpg':
$simg = imagecreatefromjpeg($source);
break;
case '.png':
$simg = imagecreatefrompng($source);
break;
}
$dest = $thumb_directory. $file_name_with_ext ;
$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
// imagewebp($dimg, $dest);
compress($source, "$desired_dir" . $file_name_with_ext , 50);
compress($dest, $dest , 50);
$file[] = $file_name_with_ext ;
}
}else{
// TODO: error handling
}
}
}
$stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
. " VALUES (:im1, :im2, :im3, :im4)");
$stmt->bindParam(':im1', $file[0], PDO::PARAM_STR, 100);
$stmt->bindParam(':im2', $file[1], PDO::PARAM_STR, 100);
$stmt->bindParam(':im3', $file[2], PDO::PARAM_STR, 100);
$stmt->bindParam(':im4', $file[3], PDO::PARAM_STR, 100);
if ($stmt->execute()) {
header('Location: https://google.com');
}exit;
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
$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);
}
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
return $targetImg;
}
?>
As part of your question you asked if there was "any good and faster function to do please."
https://github.com/delboy1978uk/image
Try this! (install via Composer or just require each of the classes in if you just drop the code in yourself)
<?php
use Del\Image;
$image = new Image('/path/to/your.jpg'); //or gif , etc
// Or...
$image = new Image();
$image->load('/path/to/my.png');
You'll then have all of these commands at your disposal:
$image->crop($width, $height, 'center'); // Crops the image, also accepts left or right as 3rd arg
$image->destroy(); // remove loaded image in the class. Frees up any memory
$image->getHeader(); // returns image/jpeg or equivalent
$image->getHeight(); // returns height in pixels
$image->getWidth(); // returns width in pixels
$image->output(); // output to browser
$image->output(true); // passing true returns raw image data string
$image->resize($width, $height); // resize to the given dimensions
$image->resizeAndCrop($width, $height); // resize to the given dimensions, cropping top/bottom or sides
$image->save(); // Save the image
$image->save('/path/to/save.jpg', $permissions, $compression); // Save as a different image
$image->scale(50); // Scale image to a percentage
Loop through your POSTed uploads, load them up, save the original, resize the image, and save the thumbnail. Existing images shouldn't be touched.
There are plenty bad php-programming-habits in that code (e.g. use of eval and general data-flow).
To break it down: The script first validates the uploaded files and moves them to a temp directory. Then it calculates thumbnails for all files in the temp directory.
To change that we use an array which contains the filenames of uploading images.
// ...
$file_type = array();
$ext = '';
$title = '';
$i = 0;
// First change:
$validFileNames = array_column($uploadedFiles, 0);
while ($file_name = readdir($dir_handle)) {
if ($file_name == '.' || $file_name == '..' || !in_array($file_name, $validFileNames)) {
continue;
}
// Nothing changed beyond this point
$file_type = \explode('.', $file_name);
$ext = strtolower(array_pop($file_type));
$title1 = implode('.', $file_type);
$title = htmlspecialchars($title1);
// ...
}
array_column($uploadedFiles, 0) reads the index 0 of every entry in $uploadedFiles, which contains the filename. So $validFileNames contains only filenames of uploading images.
We then check for every file in the temp-directory if its name is included in $uploadedFiles. If not then it was not uploading and can be ignored.
As for the request of a more general optimization:
<?php
$desired_dir = $_SERVER['DOCUMENT_ROOT'].'/upload/file/';
if (!empty($_POST)) {
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $uploadedFileName) {
$errors = array();
$destFilename = md5(uniqid('uploads', true).time());
$uploadedSize = $_FILES['files']['size'][$key];
$uploadedTmpName = $uploadedFileName;
$uploadedType = $_FILES['files']['type'][$key];
$sExt = null;
if ($uploadedType == 'image/gif') {
$sExt = '.gif';
} elseif ($uploadedType == 'image/jpeg' || $uploadedType == 'image/pjpeg') {
$sExt = '.jpg';
} elseif ($uploadedType == 'image/png' || $uploadedType == 'image/x-png') {
$sExt = '.png';
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = 'Image types alowed are (.gif, .jpg, .png) only!';
}
if ($uploadedSize > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
if (!empty($errors)) {
// Todo: Error handling of $errors
continue;
}
if (is_dir($desired_dir) == false) {
mkdir($desired_dir, 0700);
}
$destFilePath = "$desired_dir/".$destFilename.$sExt;
if (!move_uploaded_file($uploadedTmpName, $destFilePath)) {
echo "Couldn't upload file ".$uploadedTmpName;
}
$nw = 125;
$nh = 90;
$source = $destFilePath;
$stype1 = explode('.', $source);
$stype = $stype1[count($stype1) - 1];
$dest = $_SERVER['DOCUMENT_ROOT'].'/upload/thumb/'.$destFilename.$sExt;
$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);
compress($source, "$desired_dir/".$file_name, 50);
$uploadedFiles[] = $destFilePath;
}
$stmt = $conn->prepare('INSERT INTO allpostdata(im1, im2, im3, im4)'
.' VALUES (?, ?, ?, ?)');
if ($stmt->execute($uploadedFiles)) {
header('Location: /post/price_plan.php');
}
}
exit;
}
I used the following code to upload an image to a folder. My folder name is ADS. Please help me to upload that image to my ADS directory.
root - localhost/dc/upload.php
(the code is in this location)
The image should be added to the folder in location localhost/dc/ADS
if (isset($_POST["submit"])) {
if (is_array($_FILES)) {
$file = $_FILES['myImage']['tmp_name'];
$source_properties = getimagesize($file);
$image_type = $source_properties[2];
if ($image_type == IMAGETYPE_JPEG ) {
$image_resource_id = imagecreatefromjpeg($file);
echo $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
echo imagejpeg($target_layer,$_FILES['myImage']['name']);
} elseif ($image_type == IMAGETYPE_GIF ) {
$image_resource_id = imagecreatefromgif($file);
echo$target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
echo imagegif($target_layer,$_FILES['myImage']['name'] );
} elseif ($image_type == IMAGETYPE_PNG ) {
$image_resource_id = imagecreatefrompng($file);
echo$target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
echo imagepng($target_layer,$_FILES['myImage']['name']);
}
}
}
function fn_resize($image_resource_id,$width,$height)
{
$target_width =540;
$target_height =400;
$target_layer=imagecreatetruecolor($target_width,$target_height);
imagecopyresampled($target_layer,$image_resource_id,0,0,0,0,$target_width,$target_height, $width,$height);
return $target_layer;
}
When I use this code the image is displayed as in the Image1. I need it be like in Image2 without any change to the image and also I need to have a text or image watermark on the image as in the Image3.
The PHP functions imagepng imagegif and imagejpeg all have an argument to pass a file name to. I refactored your code to show this.
<?php
if (isset($_POST["submit"])) {
if (is_array($_FILES)) {
$file = $_FILES['myImage']['tmp_name'];
$source_properties = getimagesize($file);
$image_type = $source_properties[2];
if ($image_type == IMAGETYPE_JPEG) {
$image_resource_id = imagecreatefromjpeg($file);
echo $target_layer = fn_resize($image_resource_id, $source_properties[0], $source_properties[1]);
imagejpeg($target_layer, "localhost/dc/ADS/" . $_FILES['myImage']['name']);
}
elseif($image_type == IMAGETYPE_GIF) {
$image_resource_id = imagecreatefromgif($file);
echo$target_layer = fn_resize($image_resource_id, $source_properties[0], $source_properties[1]);
imagegif($target_layer, "localhost/dc/ADS/" . $_FILES['myImage']['name']);
}
elseif($image_type == IMAGETYPE_PNG) {
$image_resource_id = imagecreatefrompng($file);
echo$target_layer = fn_resize($image_resource_id, $source_properties[0], $source_properties[1]);
imagepng($target_layer, "localhost/dc/ADS/" . $_FILES['myImage']['name']);
}
}
}
function fn_resize($image_resource_id, $width, $height) {
$target_width = 540;
$target_height = 400;
$target_layer = imagecreatetruecolor($target_width, $target_height);
imagecopyresampled($target_layer, $image_resource_id, 0, 0, 0, 0, $target_width, $target_height, $width, $height);
return $target_layer;
}
What is wrong with my code I need to resize image when upload in variable $new_width and $new_height is dimension for image. I think it's problem in $newname variable because it is working before when I added :D
<meta charset="utf-8" />
<?php
include 'config.php';
mysqli_set_charset($db, 'utf8');
$id = $_COOKIE["id"];
if (isset($_POST["action"])){
$newname = substr(md5(rand() * time()), 5,10);
$folder = "image/";
$folder2 = "image/thumb/";
$filetmp = $_FILES["filep"]["tmp_name"];
$filename = $_FILES["filep"]["name"];
$filetype = $_FILES["filep"]["type"];
$filesize = $_FILES["filep"]["size"];
$fileinfo = getimagesize($_FILES["filep"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "$folder".$newname.$filename;
$filepath_thumb = "$folder".$filename;
if($filetmp == ""){
echo "Upload image";
}
else {
if($filesize > 2097152){
echo "Less then 2 mb";
}
else{
if($filetype != "image/jpeg" && $filetype != "image/png"
&& $filetype != "image/gif" && $filetype != "image/jpg"){
echo ".jpeg, .jpg, .gif, .png";
}
else{
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";
}
if($filetype == "image/jpg"){
$imagecreate= "imagecreatefromjpg";
$imageformat = "imagejpg";
}
$new_width = "200";
$new_height = "150";
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = $imagecreate($filepath); //photo folder
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $filewidth, $fileheight);
$imageformat($image_p, $filepath_thumb);//thumb folder
$res = mysqli_query($db, "UPDATE Imager SET Cover='".$newname.$filename."' WHERE IDImg ='$id'");
if($res) {
echo "Good.";
}
else {
echo "Not Good.";
}
}
}
}
}
header( "Refresh:2; url=img.php", true, 303);
?>
I would suggest you use a library like Imagine - it will make this process much simpler.
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)
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.