PHP图片压缩函数

使用PHP对图片大小尺寸进行压缩,
当图片宽高超过一定大小时,对宽高进行等比压缩
当图片过大,但尺寸不大时,保持原始尺寸,对大小进行压缩

// 图片压缩
function compress($images, $width, $insert=false)
{
    $images = explode(',', $images);
    $image = $images[0] ?? '';

    $url = '.' . $image;
    $yuan = @file_get_contents($url);
    $ext = pathinfo($image, PATHINFO_EXTENSION);

    if ($yuan && strlen($yuan) > 100 && $image && in_array($ext, ['png', 'jpg', 'jpeg'])) {
        $srcimg = imagecreatefromstring($yuan);
        $src_w = imagesx($srcimg);
        $src_h = imagesy($srcimg);
        $file_size = filesize($url);
        
        if (max($src_w, $src_h) <= $width && $file_size < 500 * 1024)
            return false;
        
        $exif = @exif_read_data($url); // 少用
        if (!empty($exif['Orientation'])) {
            switch ($exif['Orientation']) {
                case 8:
                    $srcimg = imagerotate($srcimg, 90, 0);
                    break;
                case 3:
                    $srcimg = imagerotate($srcimg, 180, 0);
                    break;
                case 6:
                    $srcimg = imagerotate($srcimg, -90, 0);
                    break;
            }
            $src_w = imagesx($srcimg);
            $src_h = imagesy($srcimg);
        }

        if (max($src_w, $src_h) <= $width && $file_size > 500 * 1024)
            $width = max($src_w, $src_h);

        if ($src_w > $src_h) {
            $height = round($width * $src_h / $src_w);
        } else {
            $height = $width;
            $width = round($height * $src_w / $src_h);
        }
        $canvas = imagecreatetruecolor($width, $height);
        imagecopyresampled($canvas,$srcimg,0,0,0,0,$width,$height,$src_w,$src_h);
        $url_thumb = $insert ? str_replace('.', '_thumb.', $image) : $image;
        if (isset($exif['MimeType']) && $exif['MimeType'] == 'image/png') {
            imagepng($canvas, '.'.$url_thumb); // 保存图片为png
        } else {
            imagejpeg($canvas, '.'.$url_thumb); // 保存图片为jpeg
        }
        $attachment = [];
        // 清除文件状态缓存
        clearstatcache(true, $url);
        imagedestroy($canvas); // 清除画布资源
        $attachment['filesize'] = filesize($url);
        $attachment['imagewidth'] = $width;
        $attachment['imageheight'] = $height;
        $attachment['url'] = $url_thumb;
        
        return $attachment;
    } else {
        return false;
    }
}

冯奎博客
请先登录后发表评论
  • latest comments
  • 总共0条评论