【问题标题】:Resize image in PHP在 PHP 中调整图像大小
【发布时间】:2013-01-16 23:06:37
【问题描述】:

我想编写一些 PHP 代码,它可以自动将通过表单上传的任何图像调整为 147x147 像素,但我不知道如何去做(我是一个相对的 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);

【问题讨论】:

  • 在不改变php.ini中的upload_max_filesize的情况下,首先是否可以上传大于upload_max_filesize的文件?是否有机会调整大小超过upload_max_filesize 的图像?无需更改 upload_max_filesize 中的 php.ini

标签: php image-processing image-resizing image-upload


【解决方案1】:

您需要使用 PHP 的 ImageMagickGD 函数来处理图像。

以 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 的图像重采样确实也大大减小了文件大小,尤其是在重采样原始数码相机图像时。

【讨论】:

  • 您是否将图像存储为BLOBs?我建议将图像存储在文件系统中并在数据库中插入引用。我还建议您阅读完整的 GD(或 ImageMagick)文档,了解您还有哪些其他可用选项。
  • 注意,此解决方案仅适用于 JPEG。您可以将 imagecreatefromjpeg 替换为以下任何内容:imagecreatefromgd、imagecreatefromgif、imagecreatefrompng、imagecreatefromstring、imagecreatefromwbmp、imagecreatefromxbm、imagecreatefromxpm 以处理不同的图像类型。
  • @GordonFreeman 感谢伟大的代码 sn-p,但有一个小故障,添加abs(),如ceil($width-($width*abs($r-$w/$h))) 和高度部分相同。在某些情况下需要它。
  • 将默认裁剪值更改为true,并将http://wallpapercave.com/wp/wc1701171.jpg处的图像大小调整为400x128(横幅)创建黑色图像;我不知道为什么会这样。
  • 要将调整大小的图像保存在文件系统中,请在 imagecopyresampled($dst,... 行之后添加 imagejpeg($dst, $file);。如果您不想覆盖原来的内容,请更改 $file
【解决方案2】:

只需使用 PHP 的 GD 函数(如 imagescale):

语法:

imagescale ( $image , $new_width , $new_height )

示例:

步骤:1 读取文件

$image_name =  'path_of_Image/Name_of_Image.jpg|png|gif';      

步骤:2:加载图像文件

 $image = imagecreatefromjpeg($image_name); // For JPEG
//or
 $image = imagecreatefrompng($image_name);   // For PNG
 //or
 $image = imagecreatefromgif($image_name);   // For GIF

步骤:3:我们的救生员出现在'_' |缩放图像

   $imgResized = imagescale($image , 500, 400); // width=500 and height = 400
//  $imgResized is our final product

注意:imagescale 适用于 (PHP 5 >= 5.5.0, PHP 7)

步骤:4:将调整大小的图像保存到您想要的目录。

imagejpeg($imgResized, 'path_of_Image/Name_of_Image_resized.jpg'); //for jpeg
imagepng($imgResized, 'path_of_Image/Name_of_Image_resized.png'); //for png

来源:Click to Read more

【讨论】:

  • PHP 5.6.3 的最佳解决方案 >
【解决方案3】:

This resource(断开的链接)也值得考虑 - 一些使用 GD 的非常整洁的代码。但是,我修改了他们的最终代码 sn-p 以创建满足 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;
   }      
 
}
?>

【讨论】:

  • 您的样品是最好的。它直接在 Zend 框架中工作,无需制作喜剧、戏剧、扯头发。竖起大拇指
  • 我认为您需要的所有代码都应该在我的答案中,但这也可能会有所帮助:gist.github.com/arrowmedia/7863973
  • 谢谢!干得好
【解决方案4】:

如果您不关心纵横比(即您想将图像强制为特定尺寸),这是一个简化的答案

// 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::resizeImageimagejpeg()

【讨论】:

  • 不更改php.ini中的upload_max_filesize,首先不能上传大于upload_max_filesize的文件。有没有机会在php.ini中不改变upload_max_filesize的情况下调整大于upload_max_filesize的图像大小
【解决方案5】:

重要提示:在动画(动画 webp 或 gif)调整大小的情况下,结果将是从第一帧开始调整大小的非动画图像!(原始动画保持不变.. .)

我在我的 php 7.2 项目(例如 imagebmp 肯定 (PHP 7 >= 7.2.0) :php/manual/function.imagebmp)中创建了这个,大约是 techfry.com/php-tutorial,使用 GD2,(所以没有第 3 方库) 并且与 Nico Bistolfi 的答案非常相似,但适用于所有五种基本图像 mimetype(png、jpeg、webp、bmp 和 gif),创建一个新的调整大小的文件,而不修改原始文件,以及一个功能中的所有内容并准备使用(复制并粘贴到您的项目中)。 (你可以用第五个参数设置新文件的扩展名,如果你想保留原来的,你可以留下它):

function createResizedImage(
    string $imagePath = '',
    string $newPath = '',
    int $newWidth = 0,
    int $newHeight = 0,
    string $outExt = 'DEFAULT'
) : ?string
{
    if (!$newPath or !file_exists ($imagePath)) {
        return null;
    }

    $types = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP, IMAGETYPE_WEBP];
    $type = exif_imagetype ($imagePath);

    if (!in_array ($type, $types)) {
        return null;
    }

    list ($width, $height) = getimagesize ($imagePath);

    $outBool = in_array ($outExt, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']);

    switch ($type) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg ($imagePath);
            if (!$outBool) $outExt = 'jpg';
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng ($imagePath);
            if (!$outBool) $outExt = 'png';
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif ($imagePath);
            if (!$outBool) $outExt = 'gif';
            break;
        case IMAGETYPE_BMP:
            $image = imagecreatefrombmp ($imagePath);
            if (!$outBool) $outExt = 'bmp';
            break;
        case IMAGETYPE_WEBP:
            $image = imagecreatefromwebp ($imagePath);
            if (!$outBool) $outExt = 'webp';
    }

    $newImage = imagecreatetruecolor ($newWidth, $newHeight);

    //TRANSPARENT BACKGROUND
    $color = imagecolorallocatealpha ($newImage, 0, 0, 0, 127); //fill transparent back
    imagefill ($newImage, 0, 0, $color);
    imagesavealpha ($newImage, true);

    //ROUTINE
    imagecopyresampled ($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    // Rotate image on iOS
    if(function_exists('exif_read_data') && $exif = exif_read_data($imagePath, 'IFD0'))
    {
        if(isset($exif['Orientation']) && isset($exif['Make']) && !empty($exif['Orientation']) && preg_match('/(apple|ios|iphone)/i', $exif['Make'])) {
            switch($exif['Orientation']) {
                case 8:
                    if ($width > $height) $newImage = imagerotate($newImage,90,0);
                    break;
                case 3:
                    $newImage = imagerotate($newImage,180,0);
                    break;
                case 6:
                    $newImage = imagerotate($newImage,-90,0);
                    break;
            }
        }
    }

    switch (true) {
        case in_array ($outExt, ['jpg', 'jpeg']): $success = imagejpeg ($newImage, $newPath);
            break;
        case $outExt === 'png': $success = imagepng ($newImage, $newPath);
            break;
        case $outExt === 'gif': $success = imagegif ($newImage, $newPath);
            break;
        case  $outExt === 'bmp': $success = imagebmp ($newImage, $newPath);
            break;
        case  $outExt === 'webp': $success = imagewebp ($newImage, $newPath);
    }

    if (!$success) {
        return null;
    }

    return $newPath;
}

【讨论】:

  • 你太棒了!这是简单而干净的解决方案。我遇到了 Imagick 模块的问题,并用这个简单的类解决了问题。谢谢!
  • 太好了,如果你愿意,我可以稍后再添加一个更新,我会稍微改进一下。
  • 当然!我还没有时间构建动画调整大小部分...
  • @danigore,如何调整原始图像的大小(.cr2, .dng, .nef 等)? GD2 没有任何支持,经过一番努力,我能够设置 ImageMagick。但是,它在读取文件时因连接超时错误而失败。而且,也没有错误日志..
  • @danigore 我将自动图像旋转功能添加到您的功能中以解决 Apple 问题。
【解决方案6】:

希望对你有用。

/**
         * 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);
        }

【讨论】:

    【解决方案7】:

    我创建了一个易于使用的图像调整库。可以找到here on 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');
    

    如果您需要,其他功能包括:

    • 快速轻松地调整大小 - 调整为横向、纵向或自动大小
    • 轻松裁剪
    • 添加文字
    • 质量调整
    • 水印
    • 阴影和反射
    • 透明度支持
    • 读取 EXIF 元数据
    • 边框、圆角、旋转
    • 滤镜和效果
    • 图像锐化
    • 图像类型转换
    • BMP 支持

    【讨论】:

    • 这拯救了我的一天。但是,我向像我一样正在搜索 3 天并且即将失去寻找任何调整大小解决方案的希望的人发出一个小通知。如果您以后看到未定义的索引通知,只需查看此链接:github.com/Oberto/php-image-magician/pull/16/commits 并将更改应用于文件。它可以 100% 正常工作,没有任何问题。
    • 嘿,@Hema_Elmasry。仅供参考,我刚刚将这些更改合并到主要 :)
    • 好吧,抱歉,我没注意到。但我有一个问题。当我在质量不变的情况下调整到较小的分辨率时,显示的图像质量会低得多。你以前有过类似的事情吗?因为我还没有找到解决办法。
    【解决方案8】:

    我找到了完成这项工作的数学方法

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

    【讨论】:

      【解决方案9】:

      这是@Ian Atkin' 给出的答案的扩展版本。我发现它工作得非常好。对于更大的图像是:)。如果您不小心,您实际上可以将较小的图像放大。 变化: - 支持 jpg、jpeg、png、gif、bmp 文件 - 保留 .png 和 .gif 的透明度 - 仔细检查原件的尺寸是否已经更小 - 覆盖直接给出的图像(这是我需要的)

      原来如此。函数的默认值是“黄金法则”

      function resize_image($file, $w = 1200, $h = 741, $crop = false)
         {
             try {
                 $ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION);
                 list($width, $height) = getimagesize($file);
                 // if the image is smaller we dont resize
                 if ($w > $width && $h > $height) {
                     return true;
                 }
                 $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;
                     }
                 }
                 $dst = imagecreatetruecolor($newwidth, $newheight);
      
                 switch ($ext) {
                     case 'jpg':
                     case 'jpeg':
                         $src = imagecreatefromjpeg($file);
                         break;
                     case 'png':
                         $src = imagecreatefrompng($file);
                         imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
                         imagealphablending($dst, false);
                         imagesavealpha($dst, true);
                         break;
                     case 'gif':
                         $src = imagecreatefromgif($file);
                         imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
                         imagealphablending($dst, false);
                         imagesavealpha($dst, true);
                         break;
                     case 'bmp':
                         $src = imagecreatefrombmp($file);
                         break;
                     default:
                         throw new Exception('Unsupported image extension found: ' . $ext);
                         break;
                 }
                 $result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                 switch ($ext) {
                     case 'bmp':
                         imagewbmp($dst, $file);
                         break;
                     case 'gif':
                         imagegif($dst, $file);
                         break;
                     case 'jpg':
                     case 'jpeg':
                         imagejpeg($dst, $file);
                         break;
                     case 'png':
                         imagepng($dst, $file);
                         break;
                 }
                 return true;
             } catch (Exception $err) {
                 // LOG THE ERROR HERE 
                 return false;
             }
         }
      

      【讨论】:

      • 伟大的功能@DanielDoinov - 感谢发布它 - 快速问题:有没有办法只传递宽度并让函数根据原始图像相对调整高度?换句话说,如果原来是 400x200,我们是否可以告诉函数我们希望新的宽度为 200,并让函数计算出高度应该为 100?
      • 关于您的条件表达式,如果$w === $width &amp;&amp; $h === $height,我认为执行调整大小技术没有意义。想想看。应该是&gt;=&gt;= 比较。 @丹尼尔
      【解决方案10】:

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

      【讨论】:

        【解决方案11】:
        private function getTempImage($url, $tempName){
          $tempPath = 'tempFilePath' . $tempName . '.png';
          $source_image = imagecreatefrompng($url); // check type depending on your necessities.
          $source_imagex = imagesx($source_image);
          $source_imagey = imagesy($source_image);
          $dest_imagex = 861; // My default value
          $dest_imagey = 96;  // My default value
        
          $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
        
          imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);
        
          imagejpeg($dest_image, $tempPath, 100);
        
          return $tempPath;
        

        }

        这是基于this 很好的解释的改编解决方案。这家伙一步一步地解释。 希望大家喜欢。

        【讨论】:

        • 非常感谢!
        【解决方案12】:

        你可以试试 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

        【讨论】:

          【解决方案13】:

          我建议一个简单的方法:

          function resize($file, $width, $height) {
              switch(pathinfo($file)['extension']) {
                  case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file);
                  case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file);
                  default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file);
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2014-08-07
            • 1970-01-01
            • 2011-11-25
            相关资源
            最近更新 更多