在PHP中调整图像大小

Ale*_*ans 75 php image-processing image-upload image-resizing

我想写一些PHP代码,自动调整通过表单上传到147x147px的任何图像,但我不知道如何去做(我是一个相对的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);
Run Code Online (Sandbox Code Playgroud)

Gor*_*man 124

您需要使用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;
}
Run Code Online (Sandbox Code Playgroud)

你可以调用这个函数,就像这样......

$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
Run Code Online (Sandbox Code Playgroud)

从个人经验来看,GD的图像重采样确实大大减少了文件大小,特别是在重新采样原始数码相机图像时.

  • 请注意,此解决方案仅适用于JPEG.您可以使用以下任何一项替换imagecreatefromjpeg:imagecreatefromgd,imagecreatefromgif,imagecreatefrompng,imagecreatefromstring,imagecreatefromwbmp,imagecreatefromxbm,imagecreatefromxpm以处理不同的图像类型. (13认同)
  • 要将调整大小的图像保存在文件系统中,请在“imagecopyresampled($dst,...”行之后添加“imagejpeg($dst, $file);”。如果您不想覆盖原始图像,请更改“$file” 。 (5认同)
  • @ArmanP.添加你的修复到答案:) (3认同)
  • @GordonFreeman感谢伟大的代码片段,但是有一个小故障,加上`abs()`,就像`ceil($ width - ($ width*abs($ r- $ w/$ h)))`和`到高处部分.某些情况需要它. (2认同)

ban*_*ing 19

这个资源也值得考虑 - 一些使用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

}
Run Code Online (Sandbox Code Playgroud)

您还需要包含此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;
   }      

}
?>
Run Code Online (Sandbox Code Playgroud)

  • 你的样品是最好的。它直接在 Zend 框架中工作,无需制作喜剧、戏剧、拉头发。竖起大拇指 (2认同)

小智 12

如果您不关心纵横比(即您想要将图像强制为特定维度),这里有一个简化的答案

// 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;
}
Run Code Online (Sandbox Code Playgroud)

现在让我们处理上传部分.第一步,将文件上传到所需目录.然后根据文件类型(jpg,png或gif)调用上述函数之一,并传递上传文件的绝对路径,如下所示:

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

返回值$img是资源对象.我们可以保存到新位置或覆盖原始内容,如下所示:

 // again for jpg
 imagejpeg($img, 'path/newimage.jpg');
Run Code Online (Sandbox Code Playgroud)

希望这有助于某人.有关调整Imagick :: resizeImageimagejpeg()大小的更多信息,请查看这些链接


Mab*_*abd 10

只是简单地使用php函数:

// Read the image
$img = imagecreatefromjpeg("source_of_img.jpg");

// Now resize the image width = 200 and height = 200
$imgresize = imagescale($img, 200, 200);
Run Code Online (Sandbox Code Playgroud)

  • PHP 5.6.3 的最佳解决方案 &gt; (2认同)

Er.*_*oni 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);
        }
Run Code Online (Sandbox Code Playgroud)


Jar*_*rod 6

我创建了一个易于使用的图像调整库。它可以在 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');
Run Code Online (Sandbox Code Playgroud)

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

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

  • 嘿,@Hema_Elmasry。仅供参考,我刚刚将这些更改合并到主文件中:) (2认同)

dan*_*ore 6

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

我在我的php 7.2项目中创建了这个(例如 imagebmp 肯定(PHP 7 >= 7.2.0):php/manual/function.imagebmp)关于techfry.com/php-tutorial,使用 GD2,(所以没有第三方库)和与 Nico Bistolfi 的答案非常相似,但适用于所有五种基本图像模仿类型(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;
}
Run Code Online (Sandbox Code Playgroud)