PHP 图片压缩 (尺寸和质量)

虽然是图片压缩, 但是 png 和 gif 暂时没有提供实质性的压缩方案, 只能改变尺寸压缩图片, jepg 可以很有效的得到压缩

/**
 * 图片压缩类
 *
 * @package App\Http\Controllers\Common
 * @author Ican Bachors
 * @carrier CLZ 19/1/16
 */
class ImgCompressor {

    /**
     * 可供压缩的类型
     */
    private $setting = [
        'file_type' => [
            'image/jpeg',
            'image/png',
            'image/gif'
        ]
    ];

    /**
     * 被处理的图片原始路径
     */
    private $imagePath;

    /**
     * 压缩之后的存储路径
     */
    private $imageCompressPath;

    /**
     * [
     *      "0": 879,
     *      "1": 623,
     *      "2": 2,
     *      "3": "width=\"879\" height=\"623\"",
     *      "bits": 8,
     *      "channels": 3,
     *      "mime": "image/jpeg"
     *  ]
     */
    private $imageInfo;

    private $res = [
        'code' => 0,
        'original' => [
            'name' => 'oldName',
            'type' => 'imageType',
            'size' => 'imageSize'
        ],
        'compressed' => [
            'name' => 'newName',
            'type' => 'imageType',
            'size' => 'imageSize'
        ]
    ];

    function __construct($fileType = false) {
        if ($fileType)
            $this->setting['file_type'] = $fileType;
    }

    /**
     * @param int $level
     * @return ImgCompressor
     * @throws \Exception
     * @author 19/1/17 CLZ.
     */
    public function compress(  $level = 0) {
        if ($level < 0 || $level > 9)
            throw new \Exception(__METHOD__ . 'Compression level: [0, 9]');

        $compressImageName = $this->imageCompressPath;

        $type = $this->imageInfo['mime'];

        $image = ( 'imagecreatefrom' . basename($type) )($this->imagePath);

        if($type == 'image/jpeg'){
            imagejpeg($image, $compressImageName, (100 - ($level * 10)) );
        } else if ($type == 'image/gif') {
            if($this->ifTransparent($image)) { // 保留图片透明状态
                imageAlphaBlending($image, true);
                imageSaveAlpha($image, true);
                imagegif($image, $compressImageName);
            } else
                imagegif($image, $compressImageName);

        } else if($type == 'image/png'){
            if($this->ifTransparent($image)) {
                imageAlphaBlending($image, true);
                imageSaveAlpha($image, true);
                imagepng($image, $compressImageName, $level);
            } else
                imagepng($image, $compressImageName, $level);
        }

        // 销毁图片
        imagedestroy($image);

        $this->res['compressed']['size'] = filesize($compressImageName);

        return $this;
    }

    /**
     * 判断图片是否为 透明 图片
     *
     * @param $image
     * @return bool
     * @author 19/1/16 CLZ.
     */
    private function ifTransparent($image) {
        for($x = 0; $x < imagesx($image); $x++)
            for($y = 0; $y < imagesy($image); $y++)
                if((imagecolorat($image, $x, $y) & 0x7F000000) >> 24) return true;
        return false;
    }

    /**
     * 设置 被压缩图片路径, 压缩之后的存储路径
     * 
     * @param $image
     * @param $compressImageName
     * @return $this
     * @author 19/1/17 CLZ.
     * @throws \Exception
     */
    public function set($image, $compressImageName)
    {
        try {
            $this->imageInfo = getImageSize($image);
        } catch (\Exception $e) {
            throw new \Exception('不是图片类型');
        }

        $this->imagePath = $image;
        $this->imageCompressPath = $compressImageName;

        $this->res['original'] = [
            'name' => $this->imagePath,
            'type' => $this->imageInfo['mime'],
            'size' => filesize($this->imagePath)
        ];

        $this->res['compressed'] = [
            'name' => $this->imageCompressPath,
            'type' => $this->imageInfo['mime'],
            'size' => ''
        ];

        if( in_array($this->imageInfo['mime'], $this->setting['file_type']) )
            return $this;

        throw new \Exception(__METHOD__);
    }

    /**
     * 尺寸变更
     * 
     * @param $width
     * @param $height
     * @return $this
     * @author 19/1/17 CLZ.
     * @throws \Exception
     */
    function resize($width, $height) {

        if($width == 0 && $height > 0) {
            $width = ( $height / $this->imageInfo['1'] ) * $this->imageInfo['0'] ;
        } else if ($width > 0 && $height == 0) {
            $height = ( $width / $this->imageInfo['0'] ) * $this->imageInfo['1'] ;
        } else if ($width <= 0 && $height <= 0) {
            throw new \Exception('illegal size!');
        }

        $imageSrc = ( 'imagecreatefrom' . basename($this->imageInfo['mime']) )($this->imagePath);

        $image = imagecreatetruecolor($width, $height); //创建一个彩色的底图
        imagecopyresampled($image, $imageSrc, 0, 0, 0, 0,$width, $height, $this->imageInfo[0], $this->imageInfo[1]);

        ( 'image' . basename($this->imageInfo['mime']) )($image, $this->imageCompressPath);

        $this->imagePath = $this->imageCompressPath;

        $this->res['compressed']['size'] = filesize($this->imageCompressPath);

        imagedestroy($image);
        imagedestroy($imageSrc);

        return $this;
    }

    /**
     * 获取结果
     * 
     * @return array
     * @author 19/1/17 CLZ.
     */
    public function get()
    {
        return $this->res;
    }
}

使用 示例

$ImgCompressor = new ImgCompressor();

# 仅压缩
$result = $ImgCompressor->set('/vim.png', '/compressOnly.png')->compress(5)->get();
# 仅改变尺寸
$result = $ImgCompressor->set('/vim.jpg', '/resizeOnly.jpg')->resize(500, 500)->get();
# 压缩且改变尺寸
$result = $ImgCompressor->set('/vim.png', '/resizeAndCompress.png')->resize(0, 500)->compress(5)->get();

return $result;
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中常用的图片压缩方式有两种:质量压缩尺寸压缩。 1. 质量压缩 质量压缩是指在不改变图片大小的前提下减小图片的存储空间,即减小图片的文件大小。这种压缩方式不会改变图片的分辨率,也不会影响图片的清晰度,但是会导致一定程度的失真。在Android中,可以使用Bitmap类的compress方法进行质量压缩。 示例代码: ```java public Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 50, baos); byte[] bytes = baos.toByteArray(); return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } ``` 其中,第二个参数50表示压缩质量,取值范围是0-100,数字越小,压缩后的图片质量越低。 2. 尺寸压缩 尺寸压缩是指通过改变图片的分辨率来减小图片的存储空间,即减小图片的像素数。这种压缩方式会导致图片的清晰度下降,但是不会导致失真。在Android中,可以使用Bitmap类的createScaledBitmap方法进行尺寸压缩。 示例代码: ```java public Bitmap compressImage(Bitmap image) { int width = image.getWidth(); int height = image.getHeight(); Matrix matrix = new Matrix(); matrix.postScale(0.5f, 0.5f); // 将图片缩小一半 Bitmap compressedBitmap = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true); return compressedBitmap; } ``` 其中,Matrix类表示一个3x3的矩阵,通过postScale方法可以设置图片的缩放比例。最后一个参数true表示保持缩放后的图片与原图的宽高比一致。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值