PHP实现图片等比例缩略图

PHP实现图片等比例缩略图,生成正方形缩略图。

步骤:待压缩正方形图片的边长为原始图片宽度和高度的像素最小值,图片宽高较长的一边裁剪中间部分,再实现像素压缩。

<?php

$imgpath = 'test.jpg';

if (!empty($imgpath)) {
    $info = getImageInfo($imgpath);
    if ($info) {
        $srcWidth  = $info['width'];
        $srcHeight = $info['height'];
        if ($srcWidth < $srcHeight) {
            $srcSize = $srcWidth;
            $srcX = 0;
            $srcY = ($srcHeight - $srcWidth) / 2;
        } else {
            $srcSize = $srcHeight;
            $srcX = ($srcWidth - $srcHeight) / 2;
            $srcY = 0;
        }
        $type = strtolower(empty($type) ? $info['type'] : $type);
        unset($info);

        //构造函数
        $loadImage = 'imagecreatefrom'.($type=='jpg'?'jpeg':$type);
        $createImage = 'image'.($type=='jpg'?'jpeg':$type);

        //参数
        $quality = 60;
        $thumb_size = 200;

        //载入原图
        $src_image    = $loadImage($imgpath);

        //创建目标图
        $thumb_image = imagecreatetruecolor($thumb_size, $thumb_size);
        $color = imagecolorallocatealpha($thumb_image, 255, 255, 255, 100);
        imagefill($thumb_image, 0, 0, $color);

        //处理
        //bool imagecopyresampled(resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h)
        $result = imagecopyresampled($thumb_image, $src_image, 0, 0, $srcX, $srcY, $thumb_size, $thumb_size, $srcSize, $srcSize);

        //生成图片
        $index = strpos($imgpath, '.', 0);
        $thumb_imgpath = substr($imgpath, 0, $index) . "-thumb" . substr($imgpath, $index);
        $createImage($thumb_image, $thumb_imgpath, 100);

        //释放资源
        imagedestroy($src_image);
        imagedestroy($thumb_image);
    }
}

function getImageInfo($imgpath) {
    $info = array();
    $imageInfo = getimagesize($imgpath);
    if($imageInfo !== false) {
        $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
        $imageSize = filesize($imgpath);
        $info['width'] = $imageInfo[0];
        $info['height'] = $imageInfo[1];
        $info['type'] = $imageType;
        $info['size'] = $imageSize;
        $info['mime'] = $imageInfo['mime'];
    }
    return $info;
}

?>
上一篇 PHP使用curl提交json格式数据
下一篇 PHP file_get_contents获取表单POST请求内容为空问题
目录
文章列表
1 Gradle替代Maven实现Spring Boot项目构建
Gradle替代Maven实现Spring Boot项目构建
2
Spring Boot 中 JPA 的使用
Spring Boot 中 JPA 的使用
3
支付宝的App支付
支付宝的App支付
4
Kubernetes api微服务开发之service与rc基本操作
Kubernetes api微服务开发之service与rc基本操作
5
Android的HorizontalScrollView控件使用注意
Android的HorizontalScrollView控件使用注意
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。