手机版

php生成带有白边的缩略图(等缩略图方案)

时间:2021-11-12 来源:互联网 编辑:宝哥软件园 浏览:

在网站上传图片后生成缩略图应该是非常常见的功能。一般来说,为了网站显示美观,缩略图会是一样大小的。比如笔者最近做的一个网站,缩略图规格都是160120。但是如果上传的图片比例与缩略图不一致,直接缩放会导致图片失真,所以体验肯定不好。于是笔者想到了一个折中的办法,那就是收缩后加白边的方法。来源图,尺寸600 366:

最终生成的渲染图:

代码比较长,所以下面是一个简单的思路:首先从源图像按比例生成缩略图,宽度不超过160,高度不超过120。例如,上面的图片将是16098的缩略图。新建一张160120的白色背景图片,将上一步生成的缩略图放在这张图片的中央。最终代码如下:复制代码如下://源映像的路径可以是本地文件,也可以是远程映像$ src _ path=' 1.jpg//最终保存图片的宽度为$ width=160//最终保存图片的高度为$ height=120//源图形对象$ src _ image=imagecreatefromstring(file _ get _ contents($ src _ path));$ src _ width=imagesx($ src _ image);$ src _ height=imagesy($ src _ image);//生成等比例缩略图$ tmp _ image _ width=0;$ tmp _ image _ height=0;if($ src _ width/$ src _ height=$ width/$ height){ $ tmp _ image _ width=$ width;$ tmp _ image _ height=round($ tmp _ image _ width * $ src _ height/$ src _ width);} else { $ tmp _ image _ height=$ height;$ tmp _ image _ width=round($ tmp _ image _ height * $ src _ width/$ src _ height);} $ tmpImage=imagecreatetrue color($ tmp _ image _ width,$ tmp _ image _ height);imagecopyresampled($tmpImage,$src_image,0,0,0,0,$tmp_image_width,$tmp_image_height,$src_width,$ src _ height);//添加白边$ final _ image=image create true color($ width,$ height);$ color=imagecolor allocate($ final _ image,255,255,255);imagefill($final_image,0,0,$ color);$ x=round($ width-$ tmp _ image _ width)/2);$ y=round($ height-$ tmp _ image _ height)/2);imagecopy($final_image,$tmpImage,$x,$y,0,0,$tmp_image_width,$ tmp _ image _ height);//输出图片标题('内容类型:图像/JPEG ');image JPEG($ final _ image);

版权声明:php生成带有白边的缩略图(等缩略图方案)是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。