Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 无法创建拇指,图像为黑色_Php_Image_Thumbnails - Fatal编程技术网

Php 无法创建拇指,图像为黑色

Php 无法创建拇指,图像为黑色,php,image,thumbnails,Php,Image,Thumbnails,我正在从单个输入上传多个图像,并动态创建所有上传图像的拇指表单,但是当我运行代码时,我只得到黑色图像,但原始图像与上传的图像相同 <?php $newname = md5(rand() * time()); $file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null; $file2 = isset($_FILES['files']['name'][1]) ? $_FILES['f

我正在从单个输入上传多个图像,并动态创建所有上传图像的拇指表单,但是当我运行代码时,我只得到黑色图像,但原始图像与上传的图像相同

    <?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);

}
?>

我认为使用mime类型比使用扩展更好

您将执行以下操作:

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;
}
希望这有帮助

编辑:

也许你可以看看我的另一个答案:在这里你会看到如何生成拇指

编辑:

添加了对editet问题的答案:

替换:

$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);
}
与:


一切都会好起来的。(如果拇指是二次的)

我认为使用mime类型比使用扩展更好

您将执行以下操作:

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;
}
希望这有帮助

编辑:

也许你可以看看我的另一个答案:在这里你会看到如何生成拇指

编辑:

添加了对editet问题的答案:

替换:

$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);
}
与:


一切都会好起来的。(如果拇指是二次的)

这是我上传多个文件并裁剪它们的代码

它将图像上载到文件夹,然后拾取图像,对其进行裁剪,重新上载裁剪后的图像并删除原始图像

我相信你可以玩这个

这是php代码

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>";
        }
if(isset($\u POST['upload\u gal'))
{
$fk_id=$_POST['fk_id'];
$errors=array();
foreach($\u FILES['FILES']['tmp\u name']作为$key=>$tmp\u name){
$file\u name=$key.$\u FILES['FILES']['name'][$key];
$file\u size=$\u FILES['FILES']['size'][$key];
$file\u tmp=$\u FILES['FILES']['tmp\u name'][$key];
$file\u type=$\u FILES['FILES']['type'][$key];
如果($file_type=='image/jpeg'| |$type=='image/gif'| |$type=='image/bmp'| |$type=='image/png')
{
$image\u info=getimagesize($\u文件[“文件”][“tmp\u名称”][$key]);
$image\u width=$image\u info[0];
$image\u height=$image\u info[1];
$desired_dir=“brand_images/”;
if(空($errors)=true){
if(is_dir($desired_dir)==false){
mkdir(“$desired_dir”,0755);//如果目录不存在,则创建目录
}
$locationing=“品牌图片/$file\u名称”;
移动上传的文件($file\u tmp,$location);
$image=imagecreatefromstring(文件获取内容(“品牌图像”/$file名称”);
$rand=rand(1114394349739349343);
$filename=“brand_images/$rand-33$file_name”;
如果($image\u width>=840&&$image\u height>=680)
{
$thumb_width=1200;
$thumb_高度=700;
}否则{
$thumb_width=800;
$thumb_高度=533;
}
$width=imagesx($image);
$height=imagesy($image);
$original_aspect=$width/$height;
$thumb\u aspect=$thumb\u width/$thumb\u height;
如果($original\u aspect>=$thumb\u aspect)
{
//如果图像比缩略图宽(在纵横比意义上)
$new_height=$thumb_height;
$new_width=$width/($height/$thumb_height);
}
其他的
{
//如果缩略图比图像宽
$new_width=$thumb_width;
$new_height=$height/($width/$thumb_width);
}
$thumb=ImageCreateTureColor($thumb\u宽度,$thumb\u高度);
//调整大小并裁剪
ImageCopy重新采样($thumb,
$image,
0-($new\u width-$thumb\u width)/2,//将图像水平居中
0-($new\u height-$thumb\u height)/2,//将图像垂直居中
0, 0,
$new_width,$new_height,
$width,$height);
imagejpeg($thumb,$filename,80);
移动上传的文件($tmp\u name,$filename);
mysql_查询(“插入库值(“”,'brand_images/$rand-33$file_name','fk_id'));
回声“
window.location=document.URL.replace(/#$/,'');
";
}
这是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>

上载新图像


这是我上传多个文件并裁剪它们的代码

它将图像上载到文件夹,然后拾取图像,对其进行裁剪,重新上载裁剪后的图像并删除原始图像

我相信你可以玩这个

这是php代码

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>";
        }
if(isset($\u POST['upload\u gal']))
{
$fk_id=$_POST['fk_id'];
$errors=array();
foreach($\u FILES['FILES']['tmp\u name']作为$key=>$tmp\u name){
$file\u name=$key.$\u FILES['FILES']['name'][$key];
$file\u size=$\u FILES['FILES']['size'][$key];
$file\u tmp=$\u FILES['FILES']['tmp\u name'][$key];
$file\u type=$\u FILES['FILES']['type'][$key];
如果($file_type=='image/jpeg'| |$type=='image/gif'| |$type=='image/bmp'| |$type=='image/png')
{
$image\u info=getimagesize($\u文件[“文件”][“tmp\u名称”][$key]);
$image\u width=$image\u info[0];
$image\u height=$image\u info[1];
$desired_dir=“brand_images/”;
if(空($errors)=true){
if(is_dir($desired_dir)==false){
mkdir(“$desired_dir”,0755);//如果目录不存在,则创建目录
}
$locationing=“品牌图片/$file\u名称”;
移动上传的文件($file\u tmp,$location);
$image=imagecreatefromstring(文件获取内容(“品牌图像”/$file名称”);
$rand=rand(1114394349739349343);
$filename=“brand_images/$rand-33$file_name”;
如果($image\u width>=840&&$image\u height>=680)
{
$thumb_width=1200;
$thumb_高度=700;
}否则{
$thumb_width=800;
$thumb_高度=533;
}
$width=imagesx($image);
$height=imagesy($image);
$original_aspect=$width/$height;
$thumb\u aspect=$thumb\u width/$thumb\u height;
如果($original\u aspect>=$thumb\u aspect)
{
//如果图像比缩略图宽(在纵横比意义上)
$new_height=$thumb_height;
$new_width=$width/($height
imagecopyresampled($dimg, $simg, -$int_width, 0, 0, 0, $adjusted_width, $nh, $w, $h);
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;
}
<?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>
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;
        }