基本上,我在我的网站上使用 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";
}

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

  1. 从iOS应用程序发送帖子到PHP脚本不工作…简单的解决方案就像

    我之前已经做了好几次了但是由于某些原因我无法通过这个帖子…我尝试了设置为_POST且没有的变量的PHP脚本……当它们未设置为发布时它工作精细.这是我的iOS代码:这里是PHP的一大块,POST变量不在正确的位置?我想这对于更有经验的开发人员来说是一个相当简单的答案,感谢您的帮助!解决方法$_POST是一个数组,而不是一个函数.您需要使用方括号来访问数组索引:

  2. Swift社交应用文本输入优化汇总

    本文将汇总一下Swift社交应用文本输入优化技巧。

  3. swift学习2 元组 tuples

    swift中出现了一种新的数据结构,非常牛掰的元组tuples如果懂PHP的猿,会发现这个元组和PHP的数组非常类似,同样是可以默认不指定key,也可以指定key目前的学习疑问是,如何进行元组的遍历?

  4. Swift思量与初探:我需要学习Swift吗?

    最近,除了N多的基于Swift的服务端开发框架,笔者不由深思,到底该这么评价Swift呢?前两点在Swift的语法和语言特性中已经表现得淋漓尽致:像是尾随闭包,枚举关联值,可选值和强制的类型安全等都是Swift显而易见的优点。综上所述,Swift拥有着被广泛使用以及当做第一学习语言的潜质。Swift在语法层次上会更加高级,并且Swift并没有使用GC机制,因此可以与C更好地相兼容。Swift中的注释与C语言的注释非常相似。

  5. 尝试使用swift mailer,gmail smtp,php发送邮件

    这里是我的代码:在运行时出现此错误…

  6. PHP使用JpGraph绘制折线图操作示例【附源码下载】

    这篇文章主要介绍了PHP使用JpGraph绘制折线图操作,结合实例形式分析了php使用JpGraph的相关操作技巧与注意事项,并附带源码供读者下载参考,需要的朋友可以参考下

  7. jQuery的Cookie封装,与PHP交互的简单实现

    下面小编就为大家带来一篇jQuery的Cookie封装,与PHP交互的简单实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  8. PHP+jquery+CSS制作头像登录窗(仿QQ登陆)

    本篇文章介绍了PHP结合jQ和CSS制作头像登录窗(仿QQ登陆),实现了类似QQ的登陆界面,很有参考价值,有需要的朋友可以了解一下。

  9. 如何在PHP环境中使用ProtoBuf数据格式

    这篇文章主要介绍了如何在PHP环境中使用ProtoBuf数据格式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

  10. PHP rsa加密解密算法原理解析

    这篇文章主要介绍了PHP rsa加密解密算法原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

随机推荐

  1. PHP个人网站架设连环讲(一)

    先下一个OmnihttpdProffesinalV2.06,装上就有PHP4beta3可以用了。PHP4给我们带来一个简单的方法,就是使用SESSION(会话)级变量。但是如果不是PHP4又该怎么办?我们可以假设某人在15分钟以内对你的网页的请求都不属于一个新的人次,这样你可以做个计数的过程存在INC里,在每一个页面引用,访客第一次进入时将访问时间送到cookie里。以后每个页面被访问时都检查cookie上次访问时间值。

  2. PHP函数学习之PHP函数点评

    PHP函数使用说明,应用举例,精简点评,希望对您学习php有所帮助

  3. ecshop2.7.3 在php5.4下的各种错误问题处理

    将方法内的函数,分拆为2个部分。这个和gd库没有一点关系,是ecshop程序的问题。会出现这种问题,不外乎就是当前会员的session或者程序对cookie的处理存在漏洞。进过本地测试,includes\modules\integrates\ecshop.php这个整合自身会员的类中没有重写integrate.php中的check_cookie()方法导致,验证cookie时返回的username为空,丢失了登录状态,在ecshop.php中重写了此方法就可以了。把他加到ecshop.php的最后面去就可

  4. NT IIS下用ODBC连接数据库

    $connection=intodbc_connect建立数据库连接,$query_string="查询记录的条件"如:$query_string="select*fromtable"用$cur=intodbc_exec检索数据库,将记录集放入$cur变量中。再用while{$var1=odbc_result;$var2=odbc_result;...}读取odbc_exec()返回的数据集$cur。最后是odbc_close关闭数据库的连接。odbc_result()函数是取当前记录的指定字段值。

  5. PHP使用JpGraph绘制折线图操作示例【附源码下载】

    这篇文章主要介绍了PHP使用JpGraph绘制折线图操作,结合实例形式分析了php使用JpGraph的相关操作技巧与注意事项,并附带源码供读者下载参考,需要的朋友可以参考下

  6. zen_cart实现支付前生成订单的方法

    这篇文章主要介绍了zen_cart实现支付前生成订单的方法,结合实例形式详细分析了zen_cart支付前生成订单的具体步骤与相关实现技巧,需要的朋友可以参考下

  7. Thinkphp5框架实现获取数据库数据到视图的方法

    这篇文章主要介绍了Thinkphp5框架实现获取数据库数据到视图的方法,涉及thinkPHP5数据库配置、读取、模型操作及视图调用相关操作技巧,需要的朋友可以参考下

  8. PHP+jquery+CSS制作头像登录窗(仿QQ登陆)

    本篇文章介绍了PHP结合jQ和CSS制作头像登录窗(仿QQ登陆),实现了类似QQ的登陆界面,很有参考价值,有需要的朋友可以了解一下。

  9. 基于win2003虚拟机中apache服务器的访问

    下面小编就为大家带来一篇基于win2003虚拟机中apache服务器的访问。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  10. Yii2中组件的注册与创建方法

    这篇文章主要介绍了Yii2之组件的注册与创建的实现方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

返回
顶部