脚本宝典收集整理的这篇文章主要介绍了PHP缩略图图像按比例调整大小,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
作为一个例子,我希望“配置文件”图像(缩略图)不大于120 * 150px.脚本需要调整上传图像的大小(无论是纵向还是横向,无论比例如何)都要遵守这些尺寸而不会被拉伸.
宽度(例如120像素)应始终保持不变,但高度(例如150px)可以变化以保持图像成比例.如果它是风景照片,我假设脚本需要从图像中间取出一块?
所有要调整大小的图像的原因是,当在网格中显示所有缩略图大小大致相同的配置文件时.
任何投入将不胜感激.
$maxwidth = 120; $maxheight = 150; $img = imagecreatefromjPEg($jpgimage); //or imagecreateFrompng,imagecreatefromgif,etc. depending on user's uploaded file extension $width = imagesx($img); //get width and height of original image $height = imagesy($img); //determine which side is the longest to use in calculating length of the shorter side,since the longest will be the max size for whichever side is longest. if ($height > $width) { $ratio = $maxheight / $height; $newheight = $maxheight; $newwidth = $width * $ratio; } else { $ratio = $maxwidth / $width; $newwidth = $maxwidth; $newheight = $height * $ratio; } //create new image resource to hold the resized image $newimg = imagecreatetruecolor($newwidth,$newheight); $palsize = ImageColorstotal($img); //Get palette size for original image for ($i = 0; $i < $palsize; $i++) //Assign color palette to new image { $colors = ImageColorsForIndex($img,$i); ImageColorAllocate($newimg,$colors['red'],$colors['green'],$colors['blue']); } //copy original image into new image at new size. imagecopyresized($newimg,$img,$newwidth,$newheight,$width,$height); imagejpeg($newimg,$outputfile); //$output file is the path/filename where you wish to save the file. //Have to figure that one out yourself using whatever rules you want. Can use imagegif() or imagepng() or whatever.
这将根据较长的一侧(宽度或高度)按比例缩小任何图像,以达到最大尺寸.它还会炸掉任何小于最大值的图像,您可以通过检查宽度和高度是否小于最大值来停止.因此,200×300图像将缩小至100×150,300×200图像将缩小至120×80.
嗯,你想要宽度总是120,所以它会改变一点,是的,它必须在像200×300的图像的情况下削减一些东西,因为它会缩小到120×180没有任何失真,或者它会必须将它缩小得更远,并将信箱装箱,但这应该让你开始很好.
LetterBoxing这个例子只需要弄清楚在imagecopyresized()函数中开始绘制到新图像的正确x和y是什么.在像100×150这样的情况下,我认为X将是10,所以最终每侧有10px的空白区域为120×150. LetterBoxing 120×80 X将为0但Y将为35,因此对于120×150,上下将有35px的空白区域.
你还想用$maxwidth,$maxheight而不是$newwidth,$newheight制作$newimg,但是imagecopyresized()仍然会使用两个$new值.
由于我很无聊而且没有别的事可做,这些改变会做到:
if ($height > $width) { $ratio = $maxheight / $height; $newheight = $maxheight; $newwidth = $width * $ratio; $wrITex = round(($maxwidth - $newwidth) / 2); $writey = 0; { else { $ratio = $maxwidth / $width; $newwidth = $maxwidth; $newheight = $height * $ratio; $writex = 0; $writey = round(($maxheight - $newheight) / 2); } $newimg = imagecreatetruecolor($maxwidth,$maxheight); //Since you PRobably will want to set a color for the letter Box do this //Assign a color for the letterBox to the new image,//since this is the First call,for imagecolorallocate,it will set the background color //in this case,black rgb(0,0) imagecolorallocate($newimg,0); //Loop Palette assignment stuff here imagecopyresized($newimg,$writex,$writey,$height);
这应该工作,尚未尝试过.
以上是脚本宝典为你收集整理的PHP缩略图图像按比例调整大小全部内容,希望文章能够帮你解决PHP缩略图图像按比例调整大小所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。