I need to inquire that i am using PHP class to upload single image. below I have the class and PHP code to upload image. it is working fine for single image upload, and Now I want to upload multiple image using the same class, I used for loop for this purpose and it gives some error. please brief where i am doing wrong
HTML for multiple images
<input type="file" name="photo[]" placeholder="Photo">
code for multiple images
for($i=0;$i<$count;$i++ ) {
if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
$uploadImage = new UploadImage;
echo $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
}
}
Below code is for single image upload which is working fine.
HTML
<input type="file" name="photo" placeholder="Photo">
code
if(isset($_FILES['photo']['tmp_name']) && ($_FILES['photo']['tmp_name']!="")){
$uploadImage = new UploadImage;
$obj['image'] = $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
}
Class.php
<?php
class UploadImage {
public function upload($imageField, $imageFieldIndex = null, $strLargePath = null, $largeWidth = 0, $largeHeight = 0, $strThumbPath = null, $thumbWidth = 0, $thumbHeight = 0)
{
$noLarge = false;
$noThumb = false;
if(empty($strLargePath)) {
$noLarge = true;
}
if(empty($strThumbPath)) {
$noThumb = true;
}
echo $fileName = isset($imageFieldIndex) ? stripslashes($_FILES[$imageField]['name'][$imageFieldIndex]) : stripslashes($_FILES[$imageField]['name']);
$fileTempName = isset($imageFieldIndex) ? $_FILES[$imageField]['tmp_name'][$imageFieldIndex] : $_FILES[$imageField]['tmp_name'];
$extension = $this->getExtension($fileName);
$imageName = time().$imageFieldIndex.'.'.$extension;
if($noLarge == false) {
$this->resize($largeWidth, $largeHeight, $fileTempName, $imageName, $strLargePath);
}
if($noThumb == false) {
$this->resize($thumbWidth, $thumbHeight,$fileTempName, $imageName, $strThumbPath);
}
return $imageName;
}
private function getExtension($strInput)
{
$i = strrpos($strInput,".");
if (!$i){return null;}
$j = strlen($strInput) - $i;
$output = substr($strInput, $i + 1, $j);
return $output;
}
private function resize($newWidth, $newHeight, $imageTempName, $imageName, $savePath) {
$image = new ResizeImage;
$image->newWidth = $newWidth;
$image->newHeight = $newHeight;
$image->imageTempName = $imageTempName; // Full Path to the file
$image->ratio = true; // Keep Aspect Ratio?
// Name of the new image (optional) - If it's not set a new will be added automatically
$image->imageName = substr($imageName, 0, strrpos($imageName, '.'));
/* Path where the new image should be saved. If it's not set the script will output the image without saving it */
$image->savePath = $savePath;
$process = $image->resize();
if($process['result'] && $image->savePath)
{
//echo 'The new image ('.$process['new_file_path'].') has been saved.';
}
}
}
/*-------------------------------- Image resize Class -----------------------------------------*/
class ResizeImage {
var $imageTempName;
var $newWidth;
var $newHeight;
var $ratio;
var $imageName;
var $savePath;
function resize(){
if(!file_exists($this->imageTempName)){
exit("File ".$this->imageTempName." does not exist.");
}
$info = GetImageSize($this->imageTempName);
if(empty($info)){
exit("The file ".$this->imageTempName." doesn't seem to be an image.");
}
$width = $info[0];
$height = $info[1];
$mime = $info['mime'];
/* Keep Aspect Ratio? */
$this->ratio = true;
if($this->ratio){
$thumb = ($this->newWidth < $width && $this->newHeight < $height) ? true : false; // Thumbnail
$largeImage = ($this->newWidth >= $width || $this->newHeight >= $height) ? true : false; // Large Image
if($thumb){
if($this->newWidth > $this->newHeight){
$x = ($width / $this->newWidth);
$this->newHeight = ($height / $x);
}else {
$x = ($height / $this->newHeight);
$this->newWidth = ($width / $x);
}
}else if($largeImage){
if($this->newWidth >= $width){
$x = ($this->newWidth / $width);
$this->newHeight = ($height * $x);
}
else if($this->newHeight >= $height){
$x = ($this->newHeight / $height);
$this->newWidth = ($width * $x);
}
}
}
// What sort of image?
$type = substr(strrchr($mime, '/'), 1);
switch ($type){
case 'jpeg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
break;
case 'jpg':
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
break;
case 'png':
$image_create_func = 'ImageCreateFromPNG';
$image_save_func = 'ImagePNG';
$newImageExt = 'png';
break;
case 'bmp':
$image_create_func = 'ImageCreateFromBMP';
$image_save_func = 'ImageBMP';
$newImageExt = 'bmp';
break;
case 'gif':
$image_create_func = 'ImageCreateFromGIF';
$image_save_func = 'ImageGIF';
$newImageExt = 'gif';
break;
case 'vnd.wap.wbmp':
$image_create_func = 'ImageCreateFromWBMP';
$image_save_func = 'ImageWBMP';
$newImageExt = 'bmp';
break;
case 'xbm':
$image_create_func = 'ImageCreateFromXBM';
$image_save_func = 'ImageXBM';
$newImageExt = 'xbm';
break;
default:
$image_create_func = 'ImageCreateFromJPEG';
$image_save_func = 'ImageJPEG';
$newImageExt = 'jpg';
}
// New Image
$image_c = imagecreatetruecolor($this->newWidth, $this->newHeight);
$newImage = $image_create_func($this->imageTempName);
imagealphablending($image_c, false);
imagesavealpha($image_c,true);
$transparent = imagecolorallocatealpha($image_c, 255, 255, 255, 127);
imagefilledrectangle($image_c, 0, 0, $this->newWidth, $this->newHeight, $transparent);
ImageCopyResampled($image_c, $newImage, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height);
if($this->savePath)
{
if($this->imageName)
{
$new_name = $this->imageName.'.'.$newImageExt;
}
else
{
$new_name = $this->newImageName(basename($this->imageTempName)).'_resized.'.$newImageExt;
}
$save_path = $this->savePath.$new_name;
}
else
{
/* Show the image without saving it to a folder */
header("Content-Type: ".$mime);
$image_save_func($image_c);
$save_path = '';
}
$process = $image_save_func($image_c, $save_path);
return array('result' => $process, 'new_file_path' => $save_path);
}
function newImageName($filename)
{
$string = trim($filename);
$string = strtolower($string);
$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
$string = ereg_replace("[ \t\n\r]+", "_", $string);
$string = str_replace(" ", '_', $string);
$string = ereg_replace("[ _]+", "_", $string);
return $string;
}
}
?>
Add the image index to the upload function
for($i=0;$i<$count;$i++ ) {
if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
$uploadImage = new UploadImage;
echo $uploadImage->upload('photo', $i, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
//...................................^ here
}
}
I think this is the way it can be done.
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
And for the script you can upload multiple files using array.
Array
(
[0] => Array
(
[name] => foo.txt
[type] => text/plain
[tmp_name] => /tmp/phpYzdqkD
[error] => 0
[size] => 123
)
[1] => Array
(
[name] => bar.txt
[type] => text/plain
[tmp_name] => /tmp/phpeEwEWG
[error] => 0
[size] => 456
)
)
A quick function that would convert the $_FILES array to the cleaner (IMHO) array.
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
?>
Now I can do the following:
<?php
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
?>
Head over here for more explanation.
Related
With this script I can upload multiple images with animations or without.
Included many functions: resize, watermark, correct orientation, send data to ajax, etc...
<?php
define('FORUM_PATH', '/.../');
require_once (FORUM_PATH . '.../login.php');
$ipbMemberLoginApi = new apiMemberLogin();
$ipbMemberLoginApi->init();
$member = $ipbMemberLoginApi->getMember();
$id = ($member['member_id']);
$countFiles = count($_FILES['files']['name']);
$upload_location = "uploads/$id/" . date("ymd") . "/";
if (!is_dir($upload_location)) mkdir($upload_location, 0755, true);
$chars = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789';
$files_arr = array();
for ($i = 0;$i < $countFiles;$i++) {
$fileName = $_FILES['files']['name'][$i];
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$valid_ext = array("png", "jpeg", "jpg", "webp", "gif", "bmp");
if (in_array($ext, $valid_ext)) {
$imgName = $chars[mt_rand(1, 62) ] . substr(str_shuffle(uniqid()), 0, 6) . '.' . $ext;
$path = $upload_location . $imgName;
if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $path)) {
$abort = false;
$im = new Imagick();
try {
$im->pingImage($path);
}
catch(ImagickException $e) {
unlink($path);
$files_arr['BadIMG'][] = $fileName;
$abort = true;
}
if (!$abort) {
if ($ext == "gif") {
$file = file_get_contents($path);
$animated = preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', $file);
}
if ($animated != 1) {
//For non-animated pictures
$image = new Imagick($path);
$props = $image->getImageProperties('exif:Orientation', true);
$orientation = isset($props['exif:Orientation']) ? $props['exif:Orientation'] : null;
if ($orientation != 0) {
switch ($image->getImageOrientation()) {
case Imagick::ORIENTATION_TOPLEFT:
break;
case Imagick::ORIENTATION_TOPRIGHT:
$image->flopImage();
break;
case Imagick::ORIENTATION_BOTTOMRIGHT:
$image->rotateImage("#000", 180);
break;
case Imagick::ORIENTATION_BOTTOMLEFT:
$image->flopImage();
$image->rotateImage("#000", 180);
break;
case Imagick::ORIENTATION_LEFTTOP:
$image->flopImage();
$image->rotateImage("#000", -90);
break;
case Imagick::ORIENTATION_RIGHTTOP:
$image->rotateImage("#000", 90);
break;
case Imagick::ORIENTATION_RIGHTBOTTOM:
$image->flopImage();
$image->rotateImage("#000", 90);
break;
case Imagick::ORIENTATION_LEFTBOTTOM:
$image->rotateImage("#000", -90);
break;
default:
break;
}
$image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
$image->writeImage($path);
}
$im->readImage($path);
$max_width = 1024;
$max_height = 768;
$im->stripImage();
$im->resizeImage(min($im->getImageWidth(), $max_width), min($im->getImageHeight(), $max_height), imagick::FILTER_CATROM, 1, true);
$imWidth = $im->getImageWidth();
$imHeight = $im->getImageHeight();
if ($imWidth < 150 || $imHeight < 150) {
$watermark = new Imagick("noWatermark.png");
} elseif ($imWidth < 401 || $imHeight < 401) {
$watermark = new Imagick("watermark_small.png");
} else {
$watermark = new Imagick("watermark.png");
}
$margin_right = 2;
$margin_bottom = 2;
$x = $im->getImageWidth() - $watermark->getImageWidth() - $margin_right;
$y = $im->getImageHeight() - $watermark->getImageHeight() - $margin_bottom;
$im->compositeImage($watermark, Imagick::COMPOSITE_OVER, $x, $y);
$watermark->destroy();
file_put_contents($path, $im);
$files_arr['GoodIMG'][] = str_replace('uploads/', '', $path);
} else {
//For animated pictures
system("convert $path -coalesce -repage 0x0 -scale 800x\> -layers Optimize $path");
$imGif = new Imagick($path);
$max_size = 180;
$imGifWidth = $imGif->getImageWidth();
$imGifHeight = $imGif->getImageHeight();
if ($imGifWidth || $imGifHeight > 180) {
system("convert $path -coalesce null: watermark.png -gravity SouthEast -geometry +0+0 -layers composite -layers optimize $path");
}
$files_arr['GoodIMG'][] = str_replace('uploads/', '', $path);
}
}
}
}
}
header('Content-Type: application/json');
echo json_encode($files_arr);
die;
PHP Version 5.6.40
But have problem:
If I upload ($animated == 1).GIF together with ($animated != 1), this picture ($animated != 1) goes in function for resize animated pictures.
How to split animated picture from non-animated picture correctly if I upload together?
Added more details:
If try upload:
AAA.gif - animated
BBB.jpeg - non-animated
BBB.jpeg goes in function for resize animated pictures.
But, if try upload:
AAA.jpeg - non-animated
BBB.gif - animated
AAA.jpeg goes in function for resize non-animated pictures. This is a correct.
Solved
if ($ext == "gif") {
$file = file_get_contents($path);
$animated = preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', $file);
} else {
$animated = 0;
}
After you find an animated image and set $animated to 1, you only set $animated back to 0, when you find a non-animated gif image, but not if you find a non-animated non-gif image.
I have inherited a function which resizes images. It works well in most cases, but for some reason, in some cases the result of resizing the image is totally different than the image initially contained. The function is as follows:
function image_resize($source, $destination, $width, $height, $resizeMode='fit', $type = 'jpeg', $options = array()) {
$defaults = array(
'output' => 'file',
'isFile' => true,
'quality' => '100',
'preserveAnimation' => false,
'offsetTop' => 0,
'offsetLeft' => 0,
'offsetType' => 'percent'
);
foreach ($defaults as $k => $v) {
if (!isset($options[$k])) {
$options[$k] = $v;
}
}
if ($options['isFile']) {
$image_info = getimagesize($source);
$image = null;
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
case IMAGETYPE_BMP:
$image = imagecreatefromwbmp($source);
break;
default :
return false;
}
} else {
$image = imagecreatefromstring($source);
}
//we have an image resource
$iwidth = imagesx($image);
$iheight = imagesy($image);
//We need $width and $height for this call
if (QM::isAcceptableProfilePhotoSize($width, $height) == false)
{
throw new Exception("Size of ".$width."x".$height." is not supported");
}
//determine ratios
$wratio = $width / $iwidth;
$hratio = $height / $iheight;
$mratio = min(array($wratio, $hratio));
$rimage = null;
switch ($resizeMode) {
case 'fit':
$rimage = imagecreatetruecolor($iwidth * $mratio, $iheight * $mratio);
$image = imagecopyresampled($rimage, $image, 0, 0, 0, 0, $iwidth * $mratio, $iheight * $mratio, $iwidth, $iheight);
break;
case 'crop':
$rratio = $width / $height;
if ($rratio < 1) {
$nwidth = $iwidth;
$nheight = $iwidth * 1/$rratio;
if ($nheight>$iheight) {
$nwidth = $nwidth*$iheight/$nheight;
$nheight = $iheight;
}
} else {
$nwidth = $iheight*$rratio;
$nheight = $iheight;
if ($nwidth>$iwidth) {
$nheight = $nheight*$iwidth/$nwidth;
$nwidth = $iwidth;
}
}
switch ($options['offsetType']) {
case 'percent':
$sx = ($iwidth-$nwidth)*$options['offsetLeft']/100;
$sy = ($iheight-$nheight)*$options['offsetTop']/100;
break;
default :
return false;
}
$rimage = imagecreatetruecolor($width, $height);
$image = imagecopyresampled($rimage, $image, 0, 0, $sx, $sy, $width, $height, $nwidth, $nheight);
break;
default :
return false;
break;
}
if (!is_writeable(dirname($destination))) {
throw new Exception(getcwd(). "/" .dirname($destination)." is not writeable");
}
switch ($options['output']) {
case 'file':
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
return imagejpeg($rimage, $destination, $options['quality']);
case IMAGETYPE_PNG:
return imagepng($rimage, $destination, 0);
case IMAGETYPE_GIF:
return imagegif($rimage, $destination);
case IMAGETYPE_BMP:
return imagejpeg($rimage, $destination, $options['quality']);
default :
return false;
break;
}
return true;
break;
default :
return false;
break;
}
}
Example image causing the problem:
This image is successfully uploaded, but when I try to resize it, the resulting image is:
I call the function this way:
image_resize($ofile, $cfile, $width, $height, 'crop', 'jpeg');
Where $ofile is the original file, $cfile is the planned destination, $width is the desired width (90 in this case), $height is the desired height (90 in this case), 'crop' is the selected strategy and 'jpeg' is a certain $type value, which is unused in the function (as I have mentioned, I have inherited the code). Also, the only example where the problem could be reproduced is the attached image, which is a png, other png files are uploaded correctly, so I do not understand the cause of the issue and do not know how to solve it. Can anybody describe the cause of the problem? I have searched and experimented for a long while without achieving success.
i tried your "image_resize" function with your bird picture, and it works perfectly fine on my computer,
whether i set the source image to jpg or png, it works as expected :
However why not choosing "fit" instead of "crop" like so :
image_resize($ofile, $cfile, $width = 90, $height = 90, 'fit', 'jpeg');
Edit: based on other people's issues about getting black image after resizing PNG, this would be the correction:
function image_resize($source, $destination, $width, $height, $resizeMode='fit', $type = 'jpeg', $options = array()) {
$defaults = array(
'output' => 'file',
'isFile' => true,
'quality' => '100',
'preserveAnimation' => false,
'offsetTop' => 0,
'offsetLeft' => 0,
'offsetType' => 'percent'
);
foreach ($defaults as $k => $v) {
if (!isset($options[$k])) {
$options[$k] = $v;
}
}
if ($options['isFile']) {
$image_info = getimagesize($source);
$image = null;
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
case IMAGETYPE_BMP:
$image = imagecreatefromwbmp($source);
break;
default :
return false;
}
} else {
$image = imagecreatefromstring($source);
}
//we have an image resource
$iwidth = imagesx($image);
$iheight = imagesy($image);
//determine ratios
$wratio = $width / $iwidth;
$hratio = $height / $iheight;
$mratio = min(array($wratio, $hratio));
$rimage = null;
switch ($resizeMode) {
case 'fit':
$rimage = imagecreatetruecolor($iwidth * $mratio, $iheight * $mratio);
imagealphablending( $rimage, false );
imagesavealpha( $rimage, true );
$image = imagecopyresampled($rimage, $image, 0, 0, 0, 0, $iwidth * $mratio, $iheight * $mratio, $iwidth, $iheight);
break;
case 'crop':
$rratio = $width / $height;
if ($rratio < 1) {
$nwidth = $iwidth;
$nheight = $iwidth * 1/$rratio;
if ($nheight>$iheight) {
$nwidth = $nwidth*$iheight/$nheight;
$nheight = $iheight;
}
} else {
$nwidth = $iheight*$rratio;
$nheight = $iheight;
if ($nwidth>$iwidth) {
$nheight = $nheight*$iwidth/$nwidth;
$nwidth = $iwidth;
}
}
switch ($options['offsetType']) {
case 'percent':
$sx = ($iwidth-$nwidth)*$options['offsetLeft']/100;
$sy = ($iheight-$nheight)*$options['offsetTop']/100;
break;
default :
return false;
}
$rimage = imagecreatetruecolor($width, $height);
imagealphablending( $rimage, false );
imagesavealpha( $rimage, true );
$image = imagecopyresampled($rimage, $image, 0, 0, $sx, $sy, $width, $height, $nwidth, $nheight);
break;
default :
return false;
break;
}
if (!is_writeable(dirname($destination))) {
throw new Exception(getcwd(). "/" .dirname($destination)." is not writeable");
}
switch ($options['output']) {
case 'file':
switch ($image_info[2]) {
case IMAGETYPE_JPEG:
return imagejpeg($rimage, $destination, $options['quality']);
case IMAGETYPE_PNG:
return imagepng($rimage, $destination, 0);
case IMAGETYPE_GIF:
return imagegif($rimage, $destination);
case IMAGETYPE_BMP:
return imagejpeg($rimage, $destination, $options['quality']);
default :
return false;
break;
}
return true;
break;
default :
return false;
break;
}
}
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 am working on php function that would put watermark on image. I´ve got it working but i need to scale this watermark so the height of the watermark will be 1/3 of the original image. I can do that, but when i put it into my code it just doesnt work, because the parameter of imagecopymerge must be resource, which i dont know what means.
define('WATERMARK_OVERLAY_IMAGE', 'watermark.png');
define('WATERMARK_OVERLAY_OPACITY', 100);
define('WATERMARK_OUTPUT_QUALITY', 100);
function create_watermark($source_file_path, $output_file_path)
{
list($source_width, $source_height, $source_type) = getimagesize($source_file_path);
if ($source_type === NULL) {
return false;
}
switch ($source_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_file_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_file_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_file_path);
break;
default:
return false;
}
$overlay_gd_image = imagecreatefrompng(WATERMARK_OVERLAY_IMAGE);
$overlay_width = imagesx($overlay_gd_image);
$overlay_height = imagesy($overlay_gd_image);
//THIS PART IS WHAT SHOULD RESIZE THE WATERMARK
$source_width = imagesx($source_gd_image);
$source_height = imagesy($source_gd_image);
$percent = $source_height/3/$overlay_height;
// Get new sizes
$new_overlay_width = $overlay_width * $percent;
$new_overlay_height = $overlay_height * $percent;
// Load
$overlay_gd_image_resized = imagecreatetruecolor($new_overlay_width, $new_overlay_height);
// Resize
$overlay_gd_image_complet = imagecopyresized($overlay_gd_image_resized, $overlay_gd_image, 0, 0, 0, 0, $new_overlay_width, $new_overlay_height, $overlay_width, $overlay_height);
//ALIGN BOTTOM, RIGHT
if (isset($_POST['kde']) && $_POST['kde'] == 'pravo') {
imagecopymerge(
$source_gd_image,
$overlay_gd_image_complet,
$source_width - $new_overlay_width,
$source_height - $new_overlay_height,
0,
0,
$new_overlay_width,
$new_overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
if (isset($_POST['kde']) && $_POST['kde'] == 'levo') {
//ALIGN BOTTOM, LEFT
imagecopymerge(
$source_gd_image,
$overlay_gd_image,
0,
$source_height - $overlay_height,
0,
0,
$overlay_width,
$overlay_height,
WATERMARK_OVERLAY_OPACITY
);
}
imagejpeg($source_gd_image, $output_file_path, WATERMARK_OUTPUT_QUALITY);
imagedestroy($source_gd_image);
imagedestroy($overlay_gd_image);
imagedestroy($overlay_gd_image_resized);
}
/*
* Uploaded file processing function
*/
define('UPLOADED_IMAGE_DESTINATION', 'originals/');
define('PROCESSED_IMAGE_DESTINATION', 'images/');
function process_image_upload($Field)
{
$temp_file_path = $_FILES[$Field]['tmp_name'];
/*$temp_file_name = $_FILES[$Field]['name'];*/
$temp_file_name = md5(uniqid(rand(), true)) . '.jpg';
list(, , $temp_type) = getimagesize($temp_file_path);
if ($temp_type === NULL) {
return false;
}
switch ($temp_type) {
case IMAGETYPE_GIF:
break;
case IMAGETYPE_JPEG:
break;
case IMAGETYPE_PNG:
break;
default:
return false;
}
$uploaded_file_path = UPLOADED_IMAGE_DESTINATION . $temp_file_name;
$processed_file_path = PROCESSED_IMAGE_DESTINATION . preg_replace('/\\.[^\\.]+$/', '.jpg', $temp_file_name);
move_uploaded_file($temp_file_path, $uploaded_file_path);
$result = create_watermark($uploaded_file_path, $processed_file_path);
if ($result === false) {
return false;
} else {
return array($uploaded_file_path, $processed_file_path);
}
}
$result = process_image_upload('File1');
if ($result === false) {
echo '<br>An error occurred during file processing.';
} else {
/*echo '<br>Original image saved as ' . $result[0] . '';*/
echo '<br>Odkaz na obrazek je zde';
echo '<br><img src="' . $result[1] . '" width="500px">';
echo '<br><div class="fb-share-button" data-href="' . $result[1] . '" data-type="button"></div>';
}
I'm having a black area at my output imagecopyresized() thumbnail image.
My code:
function thumbImage($src){
/* thumb */
list($height, $width) = getimagesize($src);
$rel_difference_thumb = array('width'=>0, 'height'=>0);
if($width > 79) { $rel_difference_thumb['width'] = ($width-79)/79; }
if($height > 105) { $rel_difference_thumb['height'] = ($height-105)/105; }
asort($rel_difference_thumb);
$newwidth_thumb = $width/(1+end($rel_difference_thumb));
$newheight_thumb = $height/(1+end($rel_difference_thumb));
$newwidth_thumb = round($newwidth_thumb);
$newheight_thumb = round($newheight_thumb);
$jpeg_quality_thumb = 90;
$thumbloc = 'images/users/privAlbum/thumb/'.$USER . md5(uniqid()) . '.jpg';
switch(exif_imagetype($src)) {
case IMAGETYPE_GIF:
$img_r_thumb = imagecreatefromgif($src);
break;
case IMAGETYPE_JPEG:
$img_r_thumb = imagecreatefromjpeg($src);
break;
case IMAGETYPE_PNG:
$img_r_thumb = imagecreatefrompng($src);
break;
default:
echo json_encode(array('error' => 'Ingen bild!'));
exit(0);
break;
}
$dst_r_thumb = ImageCreateTrueColor( $newwidth_thumb, $newheight_thumb );
imagecopyresized($dst_r_thumb, $img_r_thumb, 0, 0, 0, 0, $newwidth_thumb , $newheight_thumb, $width, $height);
if( imagejpeg($dst_r_thumb,$thumbloc,$jpeg_quality_thumb) ) {
return true;
}
imagedestroy($img_r_thumb);
}
Why is this happening? How can I fix this?
list($height, $width) = getimagesize($src); should be list($width, $height) = getimagesize($src);
as said on the manual on getimagesize :
Returns an array with 7 elements:
Index 0 and 1 contains respectively
the width and the height of the image.