PHP 实现图片压缩

  • Post author:
  • Post category:php


imagejpeg函数压缩图片

/**
 * desription 压缩图片
 * @param string $imgsrc 图片路径
 * @param string $imgdst 压缩后保存路径,从项目根目录开始的路径(为空则输出图片)
 */
function compressedImage($imgsrc, $imgdst)
{
    list($width, $height, $type) = getimagesize($imgsrc);
    $new_width = $width > 800 ? 800 : $width; //图片宽度的限制
    $new_height = $height > 800 ? ceil($height * 800 / $width) : $height; //自适应匹配图片高度
    switch ($type) {
        case 1:
            #先判断是否为gif动画
            $fp = fopen($imgsrc, 'rb');
            $image_head = fread($fp, 1024);
            fclose($fp);
            $giftype =  preg_match("/" . chr(0x21) . chr(0xff) . chr(0x0b) . 'NETSCAPE2.0' . "/", $image_head) ? false : true;
            if ($giftype) {
                header('Content-Type:image/gif');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromgif($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //90代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 90);
                imagedestroy($image_wp);
                imagedestroy($image);
            }
            break;
        case 2:
            header('Content-Type:image/jpeg');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //90代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst, 90);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
        case 3:
            header('Content-Type:image/png');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefrompng($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //90代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst, 90);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
    }
}

imagejpeg函数

(PHP 4, PHP 5, PHP 7)

imagejpeg — 输出图象到浏览器或文件。

说明

bool

imagejpeg

( resource

$image

[, string

$filename

[, int

$quality

]] )


imagejpeg()



image

图像以

filename

为文件名创建一个 JPEG 图像。

参数


  • image

    由图象创建函数(例如 imagecreatetruecolor() )返回的图象资源。


  • filename

    文件保存的路径,如果未设置或为


    NULL


    ,将会直接输出原始图象流。如果要省略这个参数而提供

    quality

    参数,使用NULL。


  • quality


    quality

    为可选项,范围从 0(最差质量,文件更小)到 100(最佳质量,文件最大)。默认为 IJG 默认的质量值(大约 75)。

返回值

成功时返回


TRUE


, 或者在失败时返回


FALSE


imagejpeg详细解释链接:

imagejpeg – [ php中文手册 ] – 在线原生手册 – php中文网



版权声明:本文为qq_41469037原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。