使用PHP调整图像大小,支持PNG,JPG

2022-08-30 18:44:45

我正在使用这个类:

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图像?


答案 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");
}

答案 2

我已经写了一个类,可以做到这一点,而且很好,易于使用。它被称为
PHP图像魔术师

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

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

  • jpg
  • 巴新
  • 动图
  • 断续器

并且可以只读

  • 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');

推荐