복붙노트

PHP에서 이미지 크기 조절

PHP

PHP에서 이미지 크기 조절

폼을 통해 147x147px로 업로드 된 모든 이미지의 크기를 자동으로 조정하는 PHP 코드를 작성하고 싶습니다. 그러나 그것에 대해 알지 못합니다 (저는 상대적인 PHP 초보자입니다).

지금까지 성공적으로 이미지를 업로드하고 파일 형식을 인식하고 이름을 정리했지만 크기 조정 기능을 코드에 추가하고 싶습니다. 예를 들어, 크기가 2.3MB 및 1331x1331 인 테스트 이미지가 있는데 코드 크기를 줄이면 이미지의 파일 크기가 크게 줄어들 것입니다.

지금까지, 나는 다음과 같은 것을 가지고있다.

if ($_FILES) {
                //Put file properties into variables
                $file_name = $_FILES['profile-image']['name'];
                $file_size = $_FILES['profile-image']['size'];
                $file_tmp_name = $_FILES['profile-image']['tmp_name'];

                //Determine filetype
                switch ($_FILES['profile-image']['type']) {
                    case 'image/jpeg': $ext = "jpg"; break;
                    case 'image/png': $ext = "png"; break;
                    default: $ext = ''; break;
                }

                if ($ext) {
                    //Check filesize
                    if ($file_size < 500000) {
                        //Process file - clean up filename and move to safe location
                        $n = "$file_name";
                        $n = ereg_replace("[^A-Za-z0-9.]", "", $n);
                        $n = strtolower($n);
                        $n = "avatars/$n";
                        move_uploaded_file($file_tmp_name, $n);
                    } else {
                        $bad_message = "Please ensure your chosen file is less than 5MB.";
                    }
                } else {
                    $bad_message = "Please ensure your image is of filetype .jpg or.png.";
                }
            }
$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);

해결법

  1. ==============================

    1.이미지 작업에는 PHP의 ImageMagick 또는 GD 함수 중 하나를 사용해야합니다.

    이미지 작업에는 PHP의 ImageMagick 또는 GD 함수 중 하나를 사용해야합니다.

    예를 들어, GD를 사용하면 간단합니다 ...

    function resize_image($file, $w, $h, $crop=FALSE) {
        list($width, $height) = getimagesize($file);
        $r = $width / $height;
        if ($crop) {
            if ($width > $height) {
                $width = ceil($width-($width*abs($r-$w/$h)));
            } else {
                $height = ceil($height-($height*abs($r-$w/$h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if ($w/$h > $r) {
                $newwidth = $h*$r;
                $newheight = $h;
            } else {
                $newheight = $w/$r;
                $newwidth = $w;
            }
        }
        $src = imagecreatefromjpeg($file);
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
        return $dst;
    }
    

    그리고이 함수를 호출 할 수 있습니다.

    $img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
    

    개인적인 경험을 통해 GD의 이미지 재 샘플링은 특히 원시 디지털 카메라 이미지를 리샘플링 할 때 파일 크기를 크게 줄입니다.

  2. ==============================

    2.GD를 사용하는 매우 정돈 된 코드도 있습니다. 그러나 OP의 요구 사항을 충족하는이 함수를 만들기 위해 최종 코드 스 니펫을 수정했습니다 ...

    GD를 사용하는 매우 정돈 된 코드도 있습니다. 그러나 OP의 요구 사항을 충족하는이 함수를 만들기 위해 최종 코드 스 니펫을 수정했습니다 ...

    function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
    
        $target_dir = "your-uploaded-images-folder/";
        $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
    
        $image = new SimpleImage();
        $image->load($_FILES[$html_element_name]['tmp_name']);
        $image->resize($new_img_width, $new_img_height);
        $image->save($target_file);
        return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
    
    }
    

    당신은 또한이 PHP 파일을 포함해야합니다 ...

    <?php
    
    /*
    * File: SimpleImage.php
    * Author: Simon Jarvis
    * Copyright: 2006 Simon Jarvis
    * Date: 08/11/06
    * Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-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;
       }      
    
    }
    ?>
    
  3. ==============================

    3.가로 세로 비율에 대해 신경 쓰지 않는다면 (즉, 이미지를 특정 크기로 강제하려는 경우) 여기 간단한 대답이 있습니다.

    가로 세로 비율에 대해 신경 쓰지 않는다면 (즉, 이미지를 특정 크기로 강제하려는 경우) 여기 간단한 대답이 있습니다.

    // for jpg 
    function resize_imagejpg($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefromjpeg($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
    
     // for png
    function resize_imagepng($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefrompng($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
    
    // for gif
    function resize_imagegif($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefromgif($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
    

    이제 업로드 부분을 처리해 보겠습니다. 첫 번째 단계로 원하는 디렉토리에 파일을 업로드하십시오. 그런 다음 파일 유형 (jpg, png 또는 gif)을 기반으로 위 기능 중 하나를 호출하고 업로드 된 파일의 절대 경로를 다음과 같이 전달합니다.

     // jpg  change the dimension 750, 450 to your desired values
     $img = resize_imagejpg('path/image.jpg', 750, 450);
    

    반환 값 $ img는 리소스 객체입니다. 새 위치에 저장하거나 원본을 다음과 같이 재정의 할 수 있습니다.

     // again for jpg
     imagejpeg($img, 'path/newimage.jpg');
    

    희망이 사람을 도움이됩니다. Imagick :: resizeImage의 크기를 조정하는 방법에 대한 링크를 확인하십시오. imagejpeg ()

  4. ==============================

    4.나는 당신을 위해 일할 것이기를 바랍니다.

    나는 당신을 위해 일할 것이기를 바랍니다.

    /**
             * Image re-size
             * @param int $width
             * @param int $height
             */
            function ImageResize($width, $height, $img_name)
            {
                    /* Get original file size */
                    list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']);
    
    
                    /*$ratio = $w / $h;
                    $size = $width;
    
                    $width = $height = min($size, max($w, $h));
    
                    if ($ratio < 1) {
                        $width = $height * $ratio;
                    } else {
                        $height = $width / $ratio;
                    }*/
    
                    /* Calculate new image size */
                    $ratio = max($width/$w, $height/$h);
                    $h = ceil($height / $ratio);
                    $x = ($w - $width / $ratio) / 2;
                    $w = ceil($width / $ratio);
                    /* set new file name */
                    $path = $img_name;
    
    
                    /* Save image */
                    if($_FILES['logo_image']['type']=='image/jpeg')
                    {
                        /* Get binary data from image */
                        $imgString = file_get_contents($_FILES['logo_image']['tmp_name']);
                        /* create image from string */
                        $image = imagecreatefromstring($imgString);
                        $tmp = imagecreatetruecolor($width, $height);
                        imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
                        imagejpeg($tmp, $path, 100);
                    }
                    else if($_FILES['logo_image']['type']=='image/png')
                    {
                        $image = imagecreatefrompng($_FILES['logo_image']['tmp_name']);
                        $tmp = imagecreatetruecolor($width,$height);
                        imagealphablending($tmp, false);
                        imagesavealpha($tmp, true);
                        imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h);
                        imagepng($tmp, $path, 0);
                    }
                    else if($_FILES['logo_image']['type']=='image/gif')
                    {
                        $image = imagecreatefromgif($_FILES['logo_image']['tmp_name']);
    
                        $tmp = imagecreatetruecolor($width,$height);
                        $transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
                        imagefill($tmp, 0, 0, $transparent);
                        imagealphablending($tmp, true); 
    
                        imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h);
                        imagegif($tmp, $path);
                    }
                    else
                    {
                        return false;
                    }
    
                    return true;
                    imagedestroy($image);
                    imagedestroy($tmp);
            }
    
  5. ==============================

    5.ZF 케이크 :

    ZF 케이크 :

    <?php
    
    class FkuController extends Zend_Controller_Action {
    
      var $image;
      var $image_type;
    
      public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
    
        $target_dir = APPLICATION_PATH  . "/../public/1/";
        $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
    
        //$image = new SimpleImage();
        $this->load($_FILES[$html_element_name]['tmp_name']);
        $this->resize($new_img_width, $new_img_height);
        $this->save($target_file);
        return $target_file; 
        //return name of saved file in case you want to store it in you database or show confirmation message to user
    
    
    
      public 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);
          }
       }
      public 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);
          }
       }
      public 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);
          }
       }
      public function getWidth() {
    
          return imagesx($this->image);
       }
      public function getHeight() {
    
          return imagesy($this->image);
       }
      public function resizeToHeight($height) {
    
          $ratio = $height / $this->getHeight();
          $width = $this->getWidth() * $ratio;
          $this->resize($width,$height);
       }
    
      public function resizeToWidth($width) {
          $ratio = $width / $this->getWidth();
          $height = $this->getheight() * $ratio;
          $this->resize($width,$height);
       }
    
      public function scale($scale) {
          $width = $this->getWidth() * $scale/100;
          $height = $this->getheight() * $scale/100;
          $this->resize($width,$height);
       }
    
      public 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;
       }
    
      public function savepicAction() {
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);
    
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $this->_response->setHeader('Access-Control-Allow-Origin', '*');
    
        $this->db = Application_Model_Db::db_load();        
        $ouser = $_POST['ousername'];
    
    
          $fdata = 'empty';
          if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) {
            $file_size = $_FILES['picture']['size'];
            $tmpName  = $_FILES['picture']['tmp_name'];  
    
            //Determine filetype
            switch ($_FILES['picture']['type']) {
                case 'image/jpeg': $ext = "jpg"; break;
                case 'image/png': $ext = "png"; break;
                case 'image/jpg': $ext = "jpg"; break;
                case 'image/bmp': $ext = "bmp"; break;
                case 'image/gif': $ext = "gif"; break;
                default: $ext = ''; break;
            }
    
            if($ext) {
              //if($file_size<400000) {  
                $img = $this->store_uploaded_image('picture', 90,82);
                //$fp      = fopen($tmpName, 'r');
                $fp = fopen($img, 'r');
                $fdata = fread($fp, filesize($tmpName));        
                $fdata = base64_encode($fdata);
                fclose($fp);
    
              //}
            }
    
          }
    
          if($fdata=='empty'){
    
          }
          else {
            $this->db->update('users', 
              array(
                'picture' => $fdata,             
              ), 
              array('username=?' => $ouser ));        
          }
    
    
    
      }  
    
  6. ==============================

    6.TinyPNG PHP 라이브러리를 사용해보십시오. 이 라이브러리를 사용하면 크기 조정 과정에서 이미지가 자동으로 최적화됩니다. 라이브러리를 설치하고 https://tinypng.com/developers에서 API 키를 받으려면 모두 필요합니다. 라이브러리를 설치하려면 아래 명령을 실행하십시오.

    TinyPNG PHP 라이브러리를 사용해보십시오. 이 라이브러리를 사용하면 크기 조정 과정에서 이미지가 자동으로 최적화됩니다. 라이브러리를 설치하고 https://tinypng.com/developers에서 API 키를 받으려면 모두 필요합니다. 라이브러리를 설치하려면 아래 명령을 실행하십시오.

    composer require tinify/tinify
    

    그 후 코드는 다음과 같습니다.

    require_once("vendor/autoload.php");
    
    \Tinify\setKey("YOUR_API_KEY");
    
    $source = \Tinify\fromFile("large.jpg"); //image to be resize
    $resized = $source->resize(array(
        "method" => "fit",
        "width" => 150,
        "height" => 100
    ));
    $resized->toFile("thumbnail.jpg"); //resized image
    

    동일한 주제에 대한 블로그를 작성했습니다. http://artisansweb.net/resize-image-php-using-tinypng

  7. ==============================

    7.이미지 크기 조정을위한 사용하기 쉬운 라이브러리를 만들었습니다. 여기 Github에서 찾을 수 있습니다.

    이미지 크기 조정을위한 사용하기 쉬운 라이브러리를 만들었습니다. 여기 Github에서 찾을 수 있습니다.

    라이브러리 사용 방법의 예 :

    // Include PHP Image Magician library
    require_once('php_image_magician.php');
    
    // Open JPG image
    $magicianObj = new imageLib('racecar.jpg');
    
    // Resize to best fit then crop (check out the other options)
    $magicianObj -> resizeImage(100, 200, 'crop');
    
    // Save resized image as a PNG (or jpg, bmp, etc)
    $magicianObj -> saveImage('racecar_small.png');
    

    필요한 다른 기능은 다음과 같습니다.

  8. ==============================

    8.piio.co를 사용하는 것이 좋습니다. 일단 이미지를 저장소에 업로드하면 태그의 원본 이미지 URL 만 사용하면 라이브러리가 자동으로 크기를 조정합니다.

    piio.co를 사용하는 것이 좋습니다. 일단 이미지를 저장소에 업로드하면 태그의 원본 이미지 URL 만 사용하면 라이브러리가 자동으로 크기를 조정합니다.

    이미지 태그는 다음과 같습니다.

    그런 다음 Piio의 스크립트를 초기화하면 이미지의 크기가 자동으로 조정되고 CDN에서 제공됩니다.

    다음은 문서 링크입니다.

    수동으로하고 싶다면 네이티브 PHP 함수를 사용하는 것이 좋습니다.이 함수는 GD 라이브러리를 사용합니다. 예를 들어 JPEG 크기를 조정하려면 다음과 같이 시작할 수 있습니다.

    list($width, $height) = getimagesize($filepath);
    $original = imagecreatefromjpeg($filepath);
    $thumb    = imagecreatetruecolor($new_width, $new_height);
    imagecopyresized($thumb, $original, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    

    이미지를 직접 출력하려면 :

    imagejpeg ($ thumb);

    이미지를 파일에 저장하려면,

    imagejpeg ($ thumb, 'filepath / image.jpg');

  9. ==============================

    9.나는이 일을 끝내기위한 수학적 방법을 발견했다.

    나는이 일을 끝내기위한 수학적 방법을 발견했다.

    Github 레포 - https://github.com/gayanSandamal/easy-php-image-resizer

    실제 예 - https://plugins.nayague.com/easy-php-image-resizer/

    <?php
    //path for the image
    $source_url = '2018-04-01-1522613288.PNG';
    
    //separate the file name and the extention
    $source_url_parts = pathinfo($source_url);
    $filename = $source_url_parts['filename'];
    $extension = $source_url_parts['extension'];
    
    //define the quality from 1 to 100
    $quality = 10;
    
    //detect the width and the height of original image
    list($width, $height) = getimagesize($source_url);
    $width;
    $height;
    
    //define any width that you want as the output. mine is 200px.
    $after_width = 200;
    
    //resize only when the original image is larger than expected with.
    //this helps you to avoid from unwanted resizing.
    if ($width > $after_width) {
    
        //get the reduced width
        $reduced_width = ($width - $after_width);
        //now convert the reduced width to a percentage and round it to 2 decimal places
        $reduced_radio = round(($reduced_width / $width) * 100, 2);
    
        //ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
        $reduced_height = round(($height / 100) * $reduced_radio, 2);
        //reduce the calculated height from the original height
        $after_height = $height - $reduced_height;
    
        //Now detect the file extension
        //if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
        if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
            //then return the image as a jpeg image for the next step
            $img = imagecreatefromjpeg($source_url);
        } elseif ($extension == 'png' || $extension == 'PNG') {
            //then return the image as a png image for the next step
            $img = imagecreatefrompng($source_url);
        } else {
            //show an error message if the file extension is not available
            echo 'image extension is not supporting';
        }
    
        //HERE YOU GO :)
        //Let's do the resize thing
        //imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
        $imgResized = imagescale($img, $after_width, $after_height, $quality);
    
        //now save the resized image with a suffix called "-resized" and with its extension. 
        imagejpeg($imgResized, $filename . '-resized.'.$extension);
    
        //Finally frees any memory associated with image
        //**NOTE THAT THIS WONT DELETE THE IMAGE
        imagedestroy($img);
        imagedestroy($imgResized);
    }
    ?>
    
  10. ==============================

    10.그냥 PHP 함수를 사용합니다 : 주어진

    그냥 PHP 함수를 사용합니다 : 주어진

    // read the img
    $img = imagecreatefromjpeg("source_of_img.jpg");
    
    // Now read the iamge width = 200 and height = 200
    $imgresize = imagescale($dp,200,200);
    
  11. from https://stackoverflow.com/questions/14649645/resize-image-in-php by cc-by-sa and MIT license