图片的等比缩放我们需要的是一个等比缩放的公式即可:
原图宽度/新图宽度=原图高度/新图高度
有了这个等比数列,我们就可以根据需求,来计算高宽的值。
逻辑:
当原图的宽度超过我们限定的宽度,已知的就是新图的宽度,得公式:
新图高度=原图高度*新图宽度/原图宽度
反之,当高度超过了,得公式:
新图宽度=原图宽度*新高宽度/原图宽度
有人这时候会问,如果2个都超过怎么办?是的,如果2个都超过的话,我们就比较原图中,哪个值比较大,然后再根据大的值做优先缩放,套用上面的公式。
补白剧中,首先我们看一张图:
图中B部分是等比缩放后的图的大小,A部分则是我们需要的图片限定的高宽,那么,X,Y分别为B图相对于A图的距离。假设,我们有2张图,一个背景为红色的A图(即限定尺寸的图),一个背景为黄色的B图(等比缩放后的图),如要B在A中剧中显示,我们要计算出X,Y的值,然后将B定位到(X,Y)的位置,并合并2张图即可。
公式:
x=(A图宽度-B图宽度)÷2
y=(A图高度-B图高度)÷2
需要的PHP函数:
getimagesize
imagecreatetruecolor
imagecopyresampled
imagecreate
imagecolorallocate
imagecreatefromjpeg
imagecopy
imagejpeg
列出一些只要的PHP函数,具体的作用就不解释了,大家可以去查看手册,我相信手册讲的绝对会比我跟清楚的,哈哈。
通过上面的简单分析,个人感觉,图片的等比缩放和缩略图剧中补白,其实也不是很难的样子…<?php
classImageCopy{
public$ImageUrl;
public$Path;
public$ImageWidth;
public$ImageHeight;
function__construct($ImageUrl,$Path,$ImageWidth,$ImageHeight){
$this->ImageUrl=$ImageUrl;
$this->Path=$Path;
$this->ImageWidth=$ImageWidth;
$this->ImageHeight=$ImageHeight;
}
//获取图片信息,高宽的值
publicfunctiongetImageSize(){
list($width,$height)=getimagesize($this->ImageUrl);
$imageArr=array(
"width"=>$width,
"height"=>$height
);
return$imageArr;
}
publicfunctionSetImageCopy(){
//创建一个新的图像
//
if(function_exists("imagecreatetruecolor")){
$NewImage=imagecreatetruecolor($this->ImageWidth,$this->ImageHeight);//创建目标图gd2
$back=imagecolorallocate($NewImage,255,255,255);
imagefilledrectangle($NewImage,0,0,$this->ImageWidth,$this->ImageHeight,$back);
}
else
$NewImage=imagecreate($this->ImageWidth,$this->ImageHeight);//创建目标图gd1
//设置图像的背景颜色,白色
imagecolorallocate($NewImage,255,255,255);
//读取图片
$Image=imagecreatefromjpeg($this->ImageUrl);
//获取图片信息
$imageSize=$this->getImageSize();
//计算高宽的值
$x=($this->ImageWidth-$imageSize['width'])/2;
$y=($this->ImageHeight-$imageSize['height'])/2;
//进行图片的合并操作
imagecopy($NewImage,$Image,$x,$y,0,0,$imageSize['width'],$imageSize['height']);
//$NewImageUrl=$this->Path."/".basename($this->ImageUrl,".jpg")."_".$this->ImageWidth."_".$this->ImageHeight.".jpg";
$NewImageUrl=$this->Path."/".basename($this->ImageUrl,".jpg")."_b.jpg";
//输出新的图片
imagejpeg($NewImage,$NewImageUrl,100);
imagedestroy($NewImage);
//最后返回图片保存路径
returnarray(
"imageUrl"=>$NewImageUrl
);
}
}
?>