如何使用于图像大小调整的代码可以使用并针对各种图像扩展进行优化?

PHP*_*Fan 6 php file-upload image-uploading image-resizing php-gd

基本上,我在我的网站上使用PHP和HTML.我是PHP的新手.所以如果我在我的代码或方法中犯了任何错误,我请求你纠正我.

我编写了用于重新调整用户上传到特定大小(即特定宽度和高度)的图像的代码.我想制作尺寸为940 px*370 px的上传图片.但在这样做的同时,我想照顾以下问题:

  1. 在修改其尺寸后保存到服务器的图像的整体质量应与用户上传的图像相同.它不应该缩小或拉伸,它的原始颜色不应受到干扰等.图像的所有内容应该是原样,但在940 px*370 px的尺寸范围内.
  2. 不应将黑色背景添加到保存在服务器上的图像中.
  3. 该代码应适用于所有标准图像格式.也就是说,如果用户上传的图像是任何标准图像格式,则应该重新调整大小,否则不会.

因此,为了实现上述功能,我编写了以下代码:

HTML代码(upload_file.html):

<html>
  <body>
    <form action="upload_file.php" method="post" enctype="multipart/form-data">
      <label for="file">Filename:</label>
      <input type="file" name="file" id="file"><br>
      <input type="submit" name="submit" value="Submit">
    </form>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

PHP代码(upload_file.php):

<?php
  $allowedExts = array("gif", "jpeg", "jpg", "png");
  $temp = explode(".", $_FILES["file"]["name"]);
  $extension = end($temp);

  if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 5242880)
    && in_array($extension, $allowedExts)) {
      if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
      } else {
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
        if (file_exists("upload/upload" . $_FILES["file"]["name"])) {
          echo $_FILES["file"]["name"] . " already exists. ";
        } else {
          //Store the name of the temporary copy of the file stored on the server
          $images = $_FILES["file"]["tmp_name"];         

          /*Create a new file name for uploaded image file :
           *prepend the string "upload" to it's original file name
          */
          $new_images = "upload".$_FILES["file"]["name"];


          //Copies a file contents from one file to another
          //copy($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);

          $width = 940;

          //Determine the size of a given image file and return the dimensions along with the file type 
          $size=GetimageSize($images);

          //$height=round($width*$size[1]/$size[0]);

          $height = 370;

          //Create a new image from file or URL & returns an image identifier representing the image obtained from the given filename.
          $images_orig = ImageCreateFromJPEG($images);

          //Get image width of originally uploaded image
          $photoX = ImagesX($images_orig);

          //Get image height of originally uploaded image
          $photoY = ImagesY($images_orig);

          $scaleX = $width / $photoX;
          $scaleY = $height / $photoY;
          $scale = min($scaleX, $scaleY);

          $scaleW = $scale * $photoX;
          $scaleH = $scale * $photoY;

          /*$width = $scale * $photoX;
          $height = $scale * $photoY;*/

          //Create a new true color image & returns an image identifier representing a black image of the specified size.
          $images_fin = ImageCreateTrueColor($width, $height);

          $background = ImageColorAllocate($images_fin, 0, 0, 0);

          ImageFill($images_fin, 0, 0, $background);

          /*Copy and resize part of an image with resampling
           *copies a rectangular portion of one image to another image, 
           *smoothly interpolating pixel values so that, in particular, 
           *reducing the size of an image still retains a great deal of clarity. 
          */
          /*ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);*/
          ImageCopyResampled($images_fin, $images_orig, $width / 2 - $scaleW / 2, $height / 2 - $scaleH / 2, 0, 0, $scaleW+1, $scaleH+1, $photoX, $photoY);

          /*Output image to browser or file
           *creates a JPEG file from the given image.
          */  
          ImageJPEG($images_fin,"upload/".$new_images);

          /*Destroy an image
           *frees any memory associated with image image.  
          */
          ImageDestroy($images_orig);
          ImageDestroy($images_fin);

          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
        }
      }
    } else {
      echo "Invalid file";
    }
?>
Run Code Online (Sandbox Code Playgroud)

注意:要测试上面的代码并查看上传的图像,请在文件upload_file.html和upload_file.php所在的同一目录中创建一个标题为"upload"的文件夹.

实际上,上面的代码对我有用,但它几乎没有问题如下:

  1. 它为除了扩展名以外的扩展名的图像文件发出警告.jpg.它不应该发生.
  2. 在修改尺寸(940 px*370px)后,图像将保存到服务器.保存到服务器的图像质量与用户上传的原始图像质量相同,但它在背景中为图像添加了额外的黑色空间.它不应该发生.

您可以通过上传尺寸高于940像素*370像素且大小不超过5 MB的图像来检查本地计算机上的代码功能.

如果有人可以帮助我解决上述两个问题,对我来说将是非常有帮助的.

Ala*_*blo 13

回答你的第一个问题

它为包含.jpg以外扩展名的图像文件发出警告.它不应该发生.

您会收到警告,因为您使用JPEG特定功能打开图像,无论格式如何:

// line 48
$images_orig = ImageCreateFromJPEG($images);
Run Code Online (Sandbox Code Playgroud)

要解决此问题,您可以使用通用imagecreatefromstring功能,它可以打开图像而无需考虑其格式.

// line 48
$images_orig = ImageCreateFromString(file_get_contents($images));
Run Code Online (Sandbox Code Playgroud)

资源:


回答你的第二个问题

在修改尺寸(940 px*370px)后,图像将保存到服务器.保存到服务器的图像质量与用户上传的原始图像质量相同,但它在背景中为图像添加了额外的黑色空间.它不应该发生.

这里有2个错误:

  • 您正在重新采样图像,而未指定目标gd图像应支持透明度
  • 您将结果保存为JPEG,但JPEG不支持透明度.

您正在重新采样图像,而未指定目标gd图像应支持透明度.

要实现它,你应该首先选择目标图像中的透明颜色:我习惯使用浅粉色(#FF00FF)作为透明,因为这不是图像上常见的颜色(如果你上传花卉图片,选择另一种颜色:-)).然后,在将源图像复制到目标图像之前,将背景颜色设置为浅粉色:整个图像将变为透明而不是黑色.

更换:

     // line 67
     $images_fin = ImageCreateTrueColor($width, $height);

     $background = ImageColorAllocate($images_fin, 0, 0, 0);

     ImageFill($images_fin, 0, 0, $background);
Run Code Online (Sandbox Code Playgroud)

通过以下几行:

     $images_fin = ImageCreateTrueColor($width, $height);

     $transparent = ImageColorAllocate($images_fin, 255, 0, 255);
     ImageFill($images_fin, 0, 0, $transparent);
     ImageColorTransparent($images_fin, $transparent);
Run Code Online (Sandbox Code Playgroud)

您将结果保存为JPEG,但JPEG不支持透明度.

要解决此问题,只需替换:

     // line 31
     $new_images = "upload" . $_FILES["file"]["name"];
     // line 85
     ImageJPEG($images_fin, "upload/" . $new_images);
     // line 93
     echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
Run Code Online (Sandbox Code Playgroud)

通过:

     // line 31
     $new_images = "upload" . $_FILES["file"]["name"] . '.png';
     // line 85
     ImagePNG($images_fin, "upload/" . $new_images);
     // line 93
     echo "Stored in: " . "upload/" . $new_images;
Run Code Online (Sandbox Code Playgroud)

资源:


您的代码,上面有修复程序

<?php

$allowedExts = array ("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 5242880) && in_array($extension,
      $allowedExts))
{
   if ($_FILES["file"]["error"] > 0)
   {
      echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
   }
   else
   {
      echo "Upload: " . $_FILES["file"]["name"] . "<br>";
      echo "Type: " . $_FILES["file"]["type"] . "<br>";
      echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
      echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
      if (file_exists("upload/upload" . $_FILES["file"]["name"]))
      {
         echo $_FILES["file"]["name"] . " already exists. ";
      }
      else
      {
         //Store the name of the temporary copy of the file stored on the server
         $images = $_FILES["file"]["tmp_name"];

         /* Create a new file name for uploaded image file :
          * prepend the string "upload" to it's original file name
          */
         $new_images = "upload" . $_FILES["file"]["name"] . '.png';


         //Copies a file contents from one file to another
         //copy($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);

         $width = 940;

         //Determine the size of a given image file and return the dimensions along with the file type
         $size = GetimageSize($images);

         //$height=round($width*$size[1]/$size[0]);

         $height = 370;

         //Create a new image from file or URL & returns an image identifier representing the image obtained from the given filename.
         $images_orig = ImageCreateFromString(file_get_contents($images));

         //Get image width of originally uploaded image
         $photoX = ImagesX($images_orig);

         //Get image height of originally uploaded image
         $photoY = ImagesY($images_orig);

         $scaleX = $width / $photoX;
         $scaleY = $height / $photoY;
         $scale = min($scaleX, $scaleY);

         $scaleW = $scale * $photoX;
         $scaleH = $scale * $photoY;

         /* $width = $scale * $photoX;
           $height = $scale * $photoY; */

         //Create a new true color image & returns an image identifier representing a black image of the specified size.
         $images_fin = ImageCreateTrueColor($width, $height);
         $transparent = imagecolorallocate($images_fin, 255, 0, 255);
         imagefill($images_fin, 0, 0, $transparent);
         imagecolortransparent($images_fin, $transparent);

         /* Copy and resize part of an image with resampling
          * copies a rectangular portion of one image to another image,
          * smoothly interpolating pixel values so that, in particular,
          * reducing the size of an image still retains a great deal of clarity.
          */
         /* ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY); */
         ImageCopyResampled($images_fin, $images_orig, $width / 2 - $scaleW / 2, $height / 2 - $scaleH / 2, 0, 0,
            $scaleW + 1, $scaleH + 1, $photoX, $photoY);

         /* Output image to browser or file
          * creates a JPEG file from the given image.
          */
         ImagePNG($images_fin, "upload/" . $new_images);

         /* Destroy an image
          * frees any memory associated with image image.
          */
         ImageDestroy($images_orig);
         ImageDestroy($images_fin);

         echo "Stored in: " . "upload/" . $new_images;
      }
   }
}
else
{
   echo "Invalid file";
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述