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

前端之家收集整理的这篇文章主要介绍了php – 如何使用于图像大小调整的代码可以工作并针对各种图像扩展进行优化?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上,我在我的网站上使用 PHP和HTML.我是 PHP的新手.所以如果我在我的代码方法中犯了任何错误,我请求你纠正我.

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

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

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

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>

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

          ImageFill($images_fin,$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,$width+1,$height+1,$photoX,$photoY);*/
          ImageCopyResampled($images_fin,$width / 2 - $scaleW / 2,$height / 2 - $scaleH / 2,$scaleW+1,$scaleH+1,$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";
    }
?>

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

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

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

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

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

回答你的第一个问题

It’s giving warnings for image files with extensions other than .jpg.
It should not happen.

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

// line 48
$images_orig = ImageCreateFromJPEG($images);

解决此问题,您可以使用通用的imagecreatefromstring函数,该函数可以打开图像而无需考虑其格式.

// line 48
$images_orig = ImageCreateFromString(file_get_contents($images));

资源:

> imagecreatefromstring
> file_get_contents

回答你的第二个问题

the image is saving to the server after modifications in it’s
dimensions (940 px * 370px). The quality of image saved to the server
is same as of original image uploaded by user but it’s adding
additional black space in the background to the image. It should not
happen.

这里有2个错误

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

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

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

更换:

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

     $background = ImageColorAllocate($images_fin,0);

     ImageFill($images_fin,$background);

通过以下几行:

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

     $transparent = ImageColorAllocate($images_fin,255,255);
     ImageFill($images_fin,$transparent);
     ImageColorTransparent($images_fin,$transparent);

您将结果保存为JPEG,但是为JPEG does not support transparency.

解决此问题,只需替换:

// 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"];

通过:

// 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;

资源:

> imagecolortransparent
> imagepng

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

<?PHP

$allowedExts = array ("gif","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);
         imagefill($images_fin,$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,* reducing the size of an image still retains a great deal of clarity.
          */
         /* ImageCopyResampled($images_fin,$photoY); */
         ImageCopyResampled($images_fin,$scaleW + 1,$scaleH + 1,$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";
}
原文链接:https://www.f2er.com/php/133314.html

猜你在找的PHP相关文章