栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将图片调整大小/裁剪/填充为固定大小

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将图片调整大小/裁剪/填充为固定大小

这个解决方案与Can BerkGüder的解决方案基本相同,但是花了一些时间写和发表评论后,我才觉得喜欢发布。

此功能创建的缩略图与您提供的尺寸完全一样。调整图像大小以使其最适合缩略图的大小。如果在两个方向上都不完全适合,则将其放在缩略图的中心。大量的评论解释了这一过程。

function thumbnail_box($img, $box_w, $box_h) {    //create the image, of the required size    $new = imagecreatetruecolor($box_w, $box_h);    if($new === false) {        //creation failed -- probably not enough memory        return null;    }    //Fill the image with a light grey color    //(this will be visible in the padding around the image,    //if the aspect ratios of the image and the thumbnail do not match)    //Replace this with any color you want, or comment it out for black.    //I used grey for testing =)    $fill = imagecolorallocate($new, 200, 200, 205);    imagefill($new, 0, 0, $fill);    //compute resize ratio    $hratio = $box_h / imagesy($img);    $wratio = $box_w / imagesx($img);    $ratio = min($hratio, $wratio);    //if the source is smaller than the thumbnail size,     //don't resize -- add a margin instead    //(that is, dont magnify images)    if($ratio > 1.0)        $ratio = 1.0;    //compute sizes    $sy = floor(imagesy($img) * $ratio);    $sx = floor(imagesx($img) * $ratio);    //compute margins    //Using these margins centers the image in the thumbnail.    //If you always want the image to the top left,     //set both of these to 0    $m_y = floor(($box_h - $sy) / 2);    $m_x = floor(($box_w - $sx) / 2);    //Copy the image data, and resample    //    //If you want a fast and ugly thumbnail,    //replace imagecopyresampled with imagecopyresized    if(!imagecopyresampled($new, $img,        $m_x, $m_y, //dest x, y (margins)        0, 0, //src x, y (0,0 means top left)        $sx, $sy,//dest w, h (resample to this size (computed above)        imagesx($img), imagesy($img)) //src w, h (the full size of the original)    ) {        //copy failed        imagedestroy($new);        return null;    }    //copy successful    return $new;}

用法示例:

$i = imagecreatefromjpeg("img.jpg");$thumb = thumbnail_box($i, 210, 150);imagedestroy($i);if(is_null($thumb)) {        header('HTTP/1.1 500 Internal Server Error');    exit();}header('Content-Type: image/jpeg');imagejpeg($thumb);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/466121.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号