оптимизировать уменьшенные файлы png с помощью imagick

Я использую приведенный ниже код для создания миниатюры изображений, но когда я использую прозрачный фон png после миниатюры, результат намного больше (по размеру данных), чем исходный файл.

и оптимизация imagick не работала хорошо. и я пробовал все ответы на всех веб-сайтах и ​​​​на этом сайте, но проблему нельзя исправить.

//
// parameters:  src = source image
//              wmax = max width
//              hmax = max height
//              quality = JPG quality of generated thumb - optional.
//                        if not specified, quality=90
//              bgcol = if specified, allways generates exact wmax x hmax sized thumb,
//                      with bacground color bgcol and centered source image
//
// note: if source image is smaller than desired thumbnail, it will not be resized!
require_once '../../../includes/functions.php';

error_reporting(0);
$hmax = $_GET['hmax'];
$wmax = $_GET['wmax'];
@$compression = $_GET['compression'];
$bgcol = $_GET['bgcol'];
@$quality = $_GET['quality'];
$src = $_GET['src'];

if (empty($bgcol))
    $bgcol = 'transparent';

$host = $_SERVER['HTTP_HOST'];
$ext = get_extension($src);

if (!preg_match('#http(.*)://(.+|)#is', $src, $matches)) {
    $src = match_http($host . $src);
}

$src = str_replace('http://' . $host . '/', '../../', $src);

switch($ext) {
    case 'jpg' :
        header("Content-type: image/jpeg");
        break;
    case 'png' :
        header("Content-type: image/png");
        break;
}

if (strrchr($src, '/')) {
    $filename = substr(strrchr($src, '/'), 1);
    // remove folder references
} else {
    $filename = $src;
}

/* Caching additions by Trent Davies */
// first check cache
// cache must be world-readable
$resized = '../../tmp/cache/images/' . $hmax . 'x' . $wmax . '-' . $filename;
if (file_exists($resized)) {
    $src_f = $src;
    $resized_f = $resized;

    $imageModified = @filemtime($src_f);
    $thumbModified = @filemtime($resized_f);
    // if thumbnail is newer than image then output cached thumbnail and exit
    if ($imageModified < $thumbModified) {
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", $thumbModified) . " GMT");
        header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', $thumbModified + 15552000));
        //6month

        readfile($resized);
        exit ;

    }
}

switch($ext) {
    case 'jpg' :
        $source = imagecreatefromjpeg($src);
        break;
    case 'png' :
        if (class_exists('Imagick')) {
            $image = new Imagick($src);
        } else

            $source = imagecreatefrompng($src);
        break;
}
if (!class_exists('Imagick') or $ext != 'png') {

    $orig_w = imagesx($source);
    $orig_h = imagesy($source);

    $thumb_w = $wmax;
    $thumb_h = $hmax;

    if (!@$bgcol) {
        $thumb = imagecreatetruecolor($thumb_w, $thumb_h);
        imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_w, $thumb_h, $orig_w, $orig_h);
    } else {
        $thumb = imagecreatetruecolor($wmax, $hmax);

        $bgcolor = intval($bgcol, 16);
        imagefilledrectangle($thumb, 0, 0, $wmax - 1, $hmax - 1, $bgcolor);
        imagecopyresampled($thumb, $source, round(($wmax - $thumb_w) / 2), round(($hmax - $thumb_h) / 2), 0, 0, $thumb_w, $thumb_h, $orig_w, $orig_h);
    }
}
if (!$quality)
    $quality = 90;

switch($ext) {
    case 'jpg' :
        {

            imagejpeg($thumb, $resized, $quality);
            chmod($resized, 0755);
            readfile($resized);
        }

        break;
    case 'png' :
        {
            if (!class_exists('Imagick')) {
                $bg_color = imagecolorat($thumb, 1, 1);

                imagecolortransparent($thumb, $bg_color);

                imagepng($thumb, "", $compression);
                imagepng($thumb, $resized, $compression);
                chmod($resized, 0755);
            } else {
                $image-> setImageCompression(true);
                $image->setImageCompression(Imagick::COMPRESSION_UNDEFINED);
                $image -> setImageCompressionQuality (0);
                $image -> thumbnailImage($wmax, $hmax);
                $image -> setImageFormat('png');    

                //create cache
                $ourFileHandle = fopen($resized, 'w');
                fwrite($ourFileHandle, $image);
                fclose($ourFileHandle);

                chmod($resized, 0775);

                echo $image;
            }

        }

        break;
}

imagedestroy($thumb);

person Nasser G.    schedule 08.07.2013    source источник


Ответы (1)


Попробуйте преобразовать PNG в PNG8, который является более эффективным форматом. Вы можете сделать это с помощью pngquant.

person Kornel    schedule 24.10.2013