随心的博客

好记性不如个烂笔头,随心记录!

返回顶部

PHP生成缩略图功能

直接上代码:

复制代码
$source_pic = @$_POST['source_pic']; //源图像
    if (!empty($source_pic))
    {
        $filename = ROOT_PATH.$source_pic;
        $pathRes = pathinfo($filename);
        $newname = "thumb_".substr($pathRes['filename'],strpos($pathRes['filename'],"_")).".".$pathRes['extension'];//生成新图像名称
        $file_ext = $pathRes['extension'];
        //header('Content-type: image/jpeg');
        // Get new dimensions
        list($width, $height) = getimagesize($filename);
        $new_width = $_POST['x2']-$_POST['x1']; //x2,x1 分别为横轴截取的两个点
        $new_height = $_POST['y2']-$_POST['y1']; //y2,y1 分别为纵轴截取的两个点
        
        // Resample
        $image_p = imagecreatetruecolor($new_width, $new_height);
        if ($file_ext=="jpg" || $file_ext=="jpeg") //生成jpg图像
        {
            $image = imagecreatefromjpeg($filename);
            imagecopyresampled($image_p, $image, 0, 0, $_POST['x1'], $_POST['y1'], $new_width, $new_height, $new_width, $new_height);
            // Output
            imagejpeg($image_p,ROOT_PATH."images/user_face/".$newname, 100);
        }
        elseif ($file_ext=="png") //生成png图像
        {
            $image = imagecreatefrompng($filename);
            imagecopyresampled($image_p, $image, 0, 0, $_POST['x1'], $_POST['y1'], $new_width, $new_height, $new_width, $new_height);
            // Output
            imagepng($image_p,ROOT_PATH."images/user_face/".$newname);
        }
        elseif ($file_ext=="gif") //生成gif图像
        {
            $image = imagecreatefromgif($filename);
            imagecopyresampled($image_p, $image, 0, 0, $_POST['x1'], $_POST['y1'], $new_width, $new_height, $new_width, $new_height);
            // Output
            imagegif($image_p,ROOT_PATH."images/user_face/".$newname);
        }
        
        $res  = $userInfoObj->updateItem($uid,array('user_face'=>$newname));
        echo "OK";
        exit();
复制代码

 

其他说明:选择四个点的时候,可以使用js插件进行选择 具体的链接地址为:https://files.cnblogs.com/ypeih/imagecut_demo.rar 点击下载

 

注意:生成缩缩图错误的实例

在做的过程中,突然旁边的同事使用这个插件怎么上传都出错,可是上传其他的图片文件都没有问题,代码也没有更改过,这个事情折腾了我一个多小时,最后找资料才知道是文件类型被同事更改了

本来是gif的文件,他把后缀更改为了jpg

 

posted @   yangphp  阅读(274)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示