Изменение размера изображений с помощью php


Я использую аккуратный небольшой php-скрипт для изменения размера моих изображений, чтобы они помещались в квадрат размером 300x300 пикселей, сохраняя при этом соотношение сторон. Я получил сценарий от здесь.

Вот весь сценарий:

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

Извините за ужасную массу кода, я подумал, что мне лучше включить источник на случай, если место, откуда я его получил, переместится или закроется.

Есть там какие-нибудь благочестивые программисты?

Author: Joe, 2012-02-06

7 answers

Он работает правильно - он изменяется до высоты 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;
 3
Author: Grim..., 2012-02-06 15:33:06

Вы можете воспользоваться imagescale() доступно с PHP 5.5.0 чтобы упростить процесс изменения размера/масштабирования изображений.

Такой, что...

$imgresource = imagecreatefromjpeg("pathtoyourimage.jpg");
imagescale($imgresource, 500, 900, IMG_BICUBIC);
 2
Author: Shankar Damodaran, 2013-12-23 11:14:55

Добавьте функцию fitToSquare в класс SimpleImage, эти функции вычисляют координаты 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;
   }  
 1
Author: adenizc, 2012-02-06 15:39:36
        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);
    }
 1
Author: nandu, 2012-10-04 04:50:10

Если это доставляет вам проблемы, вы можете сделать это через черный ход. Вместо того, чтобы позволять классу вычислять коэффициенты, перейдите прямо к функции изменения размера.

     $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; 
 0
Author: phpmeh, 2012-02-06 15:29:21

Вы не можете изменить ширину, а затем изменить высоту.
это фактически изменит его размер до 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); 
 0
Author: Robin LeBon, 2014-09-20 00:00:13

Я исправил функцию, опубликованную @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;
    }
 0
Author: Hawkee, 2015-10-30 17:11:03