【问题标题】:Resizing images using php使用 php 调整图像大小
【发布时间】:2012-02-28 01:31:49
【问题描述】:

我正在使用一个简洁的小 php 脚本来调整我的图像大小以适应 300x300 像素的正方形,同时保持纵横比。我从here得到了脚本。

这是整个脚本:

<?php

/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/

class SimpleImage {

   var $image;
   var $image_type;

   function load($filename) {

      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {

         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {

         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {

         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image,$filename);
      }
      if( $permissions != null) {

         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {

      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {

         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {

         imagepng($this->image);
      }
   }
   function getWidth() {

      return imagesx($this->image);
   }
   function getHeight() {

      return imagesy($this->image);
   }
   function resizeToHeight($height) {

      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }

   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }

   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }

   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      

}
?>

这是我的使用方法:

    $image = new SimpleImage();
    $image->load($_FILES['uploaded_image']['tmp_name']);
    $image->resizeToWidth(300);
    $image->resizeToHeight(300);
    $image->save('./images/photo'.$id.'.jpg');
    header("Location: people.php");
    exit;

这是我的问题: 它只调整高度。因此,如果我给它一个 1200x990(宽 x 高)的图像,它会吐出一个 400x300(如果有意义的话),这不适合我的 300x300 正方形。

我也试过了:

    $image = new SimpleImage();
    $image2 = new SimpleImage();
    $image->load($_FILES['uploaded_image']['tmp_name']);
    $image->resizeToWidth(300);
    $image->save('temp.jpg');
    $image2->load('temp.jpg');
    $image2->resizeToHeight(300);
    $image2->save('./images/photo'.$id.'.jpg');
    unlink('temp.jpg');
    header("Location: people.php");
    exit;

抱歉,有大量可怕的代码,我想我最好包含源代码,以防万一我得到它的地方移动或关闭。

那里有任何敬虔的编码员吗?

【问题讨论】:

    标签: php image class resize


    【解决方案1】:

    它工作正常 - 将高度调整为 300 并保持纵横比(在这种情况下,宽度为 400)。您需要先查看哪一侧是最大的一侧(或者更准确地说,是距离您需要的纵横比最远的一侧),然后只调用一个函数(resizeToWidth() 或 resizeToHeight())。

    如果我必须使用那个类,我认为这会起作用:

    $image = new SimpleImage();
    $size = getImageSize($_FILES['uploaded_image']['tmp_name']);
    if ($size[0] > 300) {
        $image->load($_FILES['uploaded_image']['tmp_name']);
        $image->resizeToWidth(300);
        $image->save('./images/photo'.$id.'.jpg');
    } else {
        move_uploaded_file($_FILES['uploaded_image']['tmp_name'], './images/photo'.$id.'.jpg');
    }
    
    $size = getImageSize('./images/photo'.$id.'.jpg');
    if ($size[1] > 300) {
        $image->load('./images/photo'.$id.'.jpg');
        $image->resizeToHeight(300);
        $image->save('./images/photo'.$id.'.jpg');
    }
    
    header("Location: people.php");
    exit;
    

    【讨论】:

    • 不客气。这有点难看 - 您可能需要考虑先将文件移动到您的图像目录,以便您可以稍微整理一下代码。
    【解决方案2】:

    您可以使用 PHP 提供的imagescale() 5.5.0 来简化调整图像大小/缩放图像的过程。

    这样……

    $imgresource = imagecreatefromjpeg("pathtoyourimage.jpg");
    imagescale($imgresource, 500, 900, IMG_BICUBIC);
    

    【讨论】:

      【解决方案3】:

      在 SimpleImage 类中添加 fitToSquare 函数,该函数计算源图像的 x 和 y 坐标,然后裁剪为正方形。我还没有测试我的功能:) 但它似乎没问题。

         function fitToSquare($width) {
            $new_image = imagecreatetruecolor($width, $height);
      
            $sourceX = 0;
            $sourceY = 0;
      
            if($this->getWidth() > $this->getHeight())
            {
                $sourceX = ($this->getWidth() - $this->getHeight()) / 2;
            }
            else
            {
                $sourceY = ($this->getHeight() - $this->getWidth()) / 2;
            }
      
            imagecopyresampled($new_image, $this->image, 0, 0, $sourceX, $sourceY, $width, $height, $this->getWidth(), $this->getHeight());
            $this->image = $new_image;
         }  
      

      【讨论】:

      • 感谢 adenizc!我最终没有使用它,因为有一些错误(这可能是微不足道的 - 但我对 php 类不是很好)
      • 我已修复此问题并将其添加为答案。
      【解决方案4】:
              function imageResize($filename, $dest, $ndest,$filetempname,$filename) {
              $userfile_name = (isset($filename) ? $filename : "");
      
              $mb_byte_2 = (1024 * 2 * 1000);            
              $ftmp = $filetempname;
      
              $oname = $filename;
              $fname = $dest;
              $sizes = getimagesize($ftmp);
              $width = $sizes[0];
              $height = $sizes[1];
      
              $extenssion = strstr($oname, ".");
      
              $prod_img = $fname;
              $prod_img_thumb =$ndest;
              move_uploaded_file($ftmp, $prod_img);
              $original_filesize = (filesize($prod_img) / 1024);
              $sizes = getimagesize($prod_img);
      
              $expected_max_width = 125;
              $expected_max_height = 100;
              $originalw = $sizes[0];
              $originalh = $sizes[1];
      
              if ($originalh < $expected_max_height) {
                  if ($originalw < $expected_max_width) {
                      $imgwidth = $originalw;
                      $imgheight = $originalh;
                  } else {
                      $imgheight = ($expected_max_width * $originalh) / $originalw;
                      $imgwidth = $expected_max_width;
                  }
              } else {
                  $new_height = $expected_max_height;
                  $new_width = ($expected_max_height * $originalw) / $originalh;
      
                  if ($new_width > $expected_max_width) {
                      $new_height = ($expected_max_width * $expected_max_height) / $new_width;
                      $new_width = $expected_max_width;
                  }
      
                  $imgwidth = $new_width;
                  $imgheight = $new_height;
              }
              $new_h = $imgheight;
              $new_w = $imgwidth;
              $new_w_im = '125';
              $new_h_im = '100';
              $offsetwidth = $new_w_im - $new_w;
              $offsetw = $offsetwidth / 2;
              $offsetheight = $new_h_im - $new_h;
              $offseth = $offsetheight / 2;
              //  echo $extenssion;
              $dest = imagecreatetruecolor($new_w_im, $new_h_im);
              $bg = imagecolorallocate($dest, 255, 255, 255);
              imagefill($dest, 0, 0, $bg);
      
              if ($extenssion == '.jpg') {
                  $src = imagecreatefromjpeg($prod_img)
                          or die('Problem In opening Source JPG Image');
              } elseif ($extenssion == '.jpeg') {
                  $src = imagecreatefromjpeg($prod_img)
                          or die('Problem In opening Source JPEG Image');
              } elseif ($extenssion == '.gif') {
                  $src = imagecreatefromgif($prod_img)
                          or die('Problem In opening Source GIF Image');
              } elseif ($extenssion == '.png') {
                  $src = imagecreatefrompng($prod_img)
                          or die('Problem In opening Source PNG Image');
              } elseif ($extenssion == '.bmp') {
                  //print_r($prod_img);
                //                $src = imagecreatefrombmp($prod_img)
               //                or die('Problem In opening Source BMP Image');
              }
      
              if (function_exists('imagecopyresampled')) {
                  imagecopyresampled($dest, $src, $offsetw, $offseth, 0, 0, 
                   $new_w, $new_h,   imagesx($src), imagesy($src))
                          or die('Problem In resizing');
              } else {
                  Imagecopyresized($dest, $src, $offsetw, $offseth, 0, 0,  
                  $new_w, $new_h, imagesx($src), imagesy($src))
                          or die('Problem In resizing');
              }
              imagejpeg($dest, $prod_img_thumb, 72)
                      or die('Problem In saving');
              imagedestroy($dest);
              @ob_flush();
              $new_filesize = (filesize($prod_img) / 1024);
          }
      

      【讨论】:

      • 想在您的答案中添加一些 cmets 吗?它是如何工作的?你的算法流程是什么?
      【解决方案5】:

      如果它给您带来问题,您可以使用后门。与其让类计算比率,不如直接使用 resize 函数。

           $image = new SimpleImage();
           $image->load($_FILES['uploaded_image']['tmp_name']);     
           $image->resize(300, 300);
           $image->save('./images/photo'.$id.'.jpg');
           header("Location: people.php");
           exit; 
      

      【讨论】:

      • 不过,这不会保持纵横比。
      【解决方案6】:

      你不能先resizetowidth,然后resizetoheight。
      这实际上会将其大小调整为 363x300。
      创建一个保留纵横比的新函数:

      function scale_kar($maxwidth,$maxheight) { 
        $width = $this->getWidth();
        $height = $this->getheight();
        if($width > $height) {
                $ratio = $maxwidth / $width;
                $height = $height * $ratio;
                $this->resize($maxwidth,$height);
        }
        if($width < $height) {
                $ratio = $maxheight / $height;
                $width = $width * $ratio;
                $this->resize($width,$maxheight);
        }
      }
      

      然后调用它:

       $image->scale_kar(300,300); 
      

      【讨论】:

        【解决方案7】:

        我修复了@adenizc 发布的函数,并为 SimpleImage 库创建了一个拉取请求。这是函数:

        /**
             * Square crop 
             *
             * This function crops the image to fit the given size which is both the width and the height
             *
             * @param int   $size
             *
             * @return SimpleImage
             */
        
            function square($size) {
                $new = imagecreatetruecolor($size, $size);
        
                $sourceX = 0;
                $sourceY = 0;
        
                if($this->width > $this->height) {
                    $this->fit_to_height($size);
                    $sourceX = ($this->width - $size) / 2;
                }
                else {
                    $this->fit_to_width($size);
                    $sourceY = ($this->height - $size) / 2;
                }
        
                imagealphablending($new, false);
                imagesavealpha($new, true);
                imagecopy($new, $this->image, 0, 0, $sourceX, $sourceY, $size, $size);
                $this->image = $new;
        
                return $this;
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-08-12
          • 1970-01-01
          • 2011-11-25
          • 2012-01-09
          • 1970-01-01
          • 2015-06-08
          • 2012-04-19
          • 1970-01-01
          相关资源
          最近更新 更多