【问题标题】:Resize images with PHP, support PNG, JPG使用 PHP 调整图像大小,支持 PNG、JPG
【发布时间】:2012-11-15 19:34:17
【问题描述】:

我正在使用这个类:

class ImgResizer {

function ImgResizer($originalFile = '$newName') {
    $this -> originalFile = $originalFile;
}
function resize($newWidth, $targetFile) {
    if (empty($newWidth) || empty($targetFile)) {
        return false;
    }
    $src = imagecreatefromjpeg($this -> originalFile);
    list($width, $height) = getimagesize($this -> originalFile);
    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
        unlink($targetFile);
    }
    imagejpeg($tmp, $targetFile, 95);
}

}

效果很好,但使用 png 失败,它会创建一个调整大小的黑色图像。

有没有办法调整这个类以支持 png 图像?

【问题讨论】:

标签: php image resize png


【解决方案1】:
function resize($newWidth, $targetFile, $originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
            case 'image/jpeg':
                    $image_create_func = 'imagecreatefromjpeg';
                    $image_save_func = 'imagejpeg';
                    $new_image_ext = 'jpg';
                    break;

            case 'image/png':
                    $image_create_func = 'imagecreatefrompng';
                    $image_save_func = 'imagepng';
                    $new_image_ext = 'png';
                    break;

            case 'image/gif':
                    $image_create_func = 'imagecreatefromgif';
                    $image_save_func = 'imagegif';
                    $new_image_ext = 'gif';
                    break;

            default: 
                    throw new Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);

    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
            unlink($targetFile);
    }
    $image_save_func($tmp, "$targetFile.$new_image_ext");
}

【讨论】:

  • 您介意将其重写为调整大小功能吗?只是我特别分享了这个类,所以我们可以扩展它..
  • 这是函数的内容,所以你只需要用相同的函数标签包装它。但我已经在上面为你完成了。
  • 嗨!我刚刚对此进行了测试,它给了我一个错误,它会引发未知异常……知道为什么吗? (问题是它在默认情况下输入的 swich,所以不是很好地协调 mime 吗?
  • @ToniMichelCaubet 不确定您是否尝试打印 $info 以查看返回的 mime 类型?
  • 效果很好,但在指定保存图像的位置时包含 $new_image_ext 没有意义。此调整大小函数的预期输入是resize(100, "newfile.png", "oldfile.png")。此外,throw Exception 应该是 throw new Exception。编辑问题以反映这一点。
【解决方案2】:

你可以试试这个。目前它假设图像将始终是 jpeg。这将允许您加载 jpeg、png 或 gif。我还没有测试,但它应该可以工作。

function resize($newWidth, $targetFile) {
    if (empty($newWidth) || empty($targetFile)) {
        return false;
    }

    $fileHandle = @fopen($this->originalFile, 'r');

    //error loading file
    if(!$fileHandle) {
        return false;
    }

    $src = imagecreatefromstring(stream_get_contents($fileHandle));

    fclose($fileHandle);

    //error with loading file as image resource
    if(!$src) {
        return false;
    }

    //get image size from $src handle
    list($width, $height) = array(imagesx($src), imagesy($src));

    $newHeight = ($height / $width) * $newWidth;

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

    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    //allow transparency for pngs
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);

    if (file_exists($targetFile)) {
        unlink($targetFile);
    }

    //handle different image types.
    //imagepng() uses quality 0-9
    switch(strtolower(pathinfo($this->originalFile, PATHINFO_EXTENSION))) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($tmp, $targetFile, 95);
            break;
        case 'png':
            imagepng($tmp, $targetFile, 8.5);
            break;
        case 'gif':
            imagegif($tmp, $targetFile);
            break;
    }

    //destroy image resources
    imagedestroy($tmp);
    imagedestroy($src);
}

【讨论】:

  • 我不明白“假设图像是 jpg”
  • 在原始的resize 方法中,$originalFile 仅处理为 jpeg (imagecreatefromjpeg/imagejpeg) 的大小调整。
  • 我尝试将我的 resize() 函数替换为你的,但它没有生成任何图像;S
  • @Sharpless512 进行了编辑,将break 语句放在switch/case 语句中的适当位置。
  • 谢谢我没有抓住那个。 (双关语不是故意的)
【解决方案3】:

我采用了 P. Galbraith 的版本,修复了错误并将其更改为按区域调整大小(宽 x 高)。对于我自己,我想调整太大的图像。

function resizeByArea($originalFile,$targetFile){

    $newArea = 375000; //a little more than 720 x 480

    list($width,$height,$type) = getimagesize($originalFile);
    $area = $width * $height;

if($area > $newArea){

    if($width > $height){ $big = $width; $small = $height; }
    if($width < $height){ $big = $height; $small = $width; }

    $ratio = $big / $small;

    $newSmall = sqrt(($newArea*$small)/$big);
    $newBig = $ratio*$newSmall;

    if($width > $height){ $newWidth = round($newBig, 0); $newHeight = round($newSmall, 0); }
    if($width < $height){ $newWidth = round($newSmall, 0); $newHeight = round($newBig, 0); }

    }

switch ($type) {
    case '2':
            $image_create_func = 'imagecreatefromjpeg';
            $image_save_func = 'imagejpeg';
            $new_image_ext = '.jpg';
            break;

    case '3':
            $image_create_func = 'imagecreatefrompng';
         // $image_save_func = 'imagepng';
         // The quality is too high with "imagepng"
         // but you need it if you want to allow transparency
            $image_save_func = 'imagejpeg';
            $new_image_ext = '.png';
            break;

    case '1':
            $image_create_func = 'imagecreatefromgif';
            $image_save_func = 'imagegif';
            $new_image_ext = '.gif';
            break;

    default: 
            throw Exception('Unknown image type.');
}

    $img = $image_create_func($originalFile);
    $tmp = imagecreatetruecolor($newWidth,$newHeight);
    imagecopyresampled( $tmp, $img, 0, 0, 0, 0,$newWidth,$newHeight, $width, $height );

    ob_start();
    $image_save_func($tmp);
    $i = ob_get_clean();

    // if file exists, create a new one with "1" at the end
    if (file_exists($targetFile.$new_image_ext)){
      $targetFile = $targetFile."1".$new_image_ext;
    }
    else{
      $targetFile = $targetFile.$new_image_ext;
    }

    $fp = fopen ($targetFile,'w');
    fwrite ($fp, $i);
    fclose ($fp);

    unlink($originalFile);
}

如果您想允许透明度,请检查:http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/

我测试了这个功能,它工作正常!

【讨论】:

  • 有趣!会给它一些测试,让你知道。谢谢!
【解决方案4】:

我已经编写了一个可以做到这一点的类,并且很好用并且易于使用。它叫
PHP Image Magician

$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200);
$magicianObj -> saveImage('racecar_convertd.png', 100);

它支持读写(包括转换)以下格式

  • jpg
  • png
  • gif
  • bmp

并且只能读取

  • psd的

示例

// 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
$magicianObj -> resizeImage(100, 200, 'crop');

// Save resized image as a PNG
$magicianObj -> saveImage('racecar_small.png');

【讨论】:

  • 您的库是否能够根据宽度自动修复高度的大小?
【解决方案5】:

接受的答案有很多错误,是否已修复

<?php 




function resize($newWidth, $targetFile, $originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
            case 'image/jpeg':
                    $image_create_func = 'imagecreatefromjpeg';
                    $image_save_func = 'imagejpeg';
                    $new_image_ext = 'jpg';
                    break;

            case 'image/png':
                    $image_create_func = 'imagecreatefrompng';
                    $image_save_func = 'imagepng';
                    $new_image_ext = 'png';
                    break;

            case 'image/gif':
                    $image_create_func = 'imagecreatefromgif';
                    $image_save_func = 'imagegif';
                    $new_image_ext = 'gif';
                    break;

            default: 
                    throw Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);
    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
            unlink($targetFile);
    }
    $image_save_func($tmp, "$targetFile.$new_image_ext");
}



$img=$_REQUEST['img'];
$id=$_REQUEST['id'];

  //  echo $img
resize(120, $_SERVER['DOCUMENT_ROOT'] ."/images/$id",$_SERVER['DOCUMENT_ROOT'] ."/images/$img") ;


?>

【讨论】:

    【解决方案6】:

    试试这个,使用它你还可以将图像保存到特定路径。

    function resize($file, $imgpath, $width, $height){
        /* Get original image x y*/
        list($w, $h) = getimagesize($file['tmp_name']);
        /* calculate new image size with ratio */
        $ratio = max($width/$w, $height/$h);
        $h = ceil($height / $ratio);
        $x = ($w - $width / $ratio) / 2;
        $w = ceil($width / $ratio);
    
        /* new file name */
        $path = $imgpath;
        /* read binary data from image file */
        $imgString = file_get_contents($file['tmp_name']);
        /* create image from string */
        $image = imagecreatefromstring($imgString);
        $tmp = imagecreatetruecolor($width, $height);
        imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
        /* Save image */
        switch ($file['type']) {
           case 'image/jpeg':
              imagejpeg($tmp, $path, 100);
              break;
           case 'image/png':
              imagepng($tmp, $path, 0);
              break;
           case 'image/gif':
              imagegif($tmp, $path);
              break;
              default:
              //exit;
              break;
            }
         return $path;
    
         /* cleanup memory */
         imagedestroy($image);
         imagedestroy($tmp);
    }
    

    现在您需要在保存图像时调用此函数...

    <?php
    
        //$imgpath = "Where you want to save your image";
        resize($_FILES["image"], $imgpath, 340, 340);
    
    ?>
    

    【讨论】:

    • 如果我想将整体图片质量降低 50% 而不是固定数量以保持纵横比怎么办?
    【解决方案7】:

    我知道这是一个非常古老的线程,但我发现 PHP 内置了 imagescale 函数,它可以完成所需的工作。见文档here

    示例用法:

    $temp = imagecreatefrompng('1.png'); 
    $scaled_image= imagescale ( $temp, 200 , 270);
    

    这里 200 是宽度,270 是调整后图像的高度。

    【讨论】:

      猜你喜欢
      • 2012-04-01
      • 1970-01-01
      • 2011-07-01
      • 2013-02-09
      • 2011-09-28
      • 1970-01-01
      • 2014-04-14
      • 2012-02-28
      • 1970-01-01
      相关资源
      最近更新 更多