用PHP写一个完美GIF图片等比缩放类,附带去除缩放黑背景
程序员文章站
2022-04-30 09:35:23
...
用PHP写一个完美GIF图片等比缩放类,附带去除缩放黑背景
这里没有判断文件类型,因为png和jpeg缩放后都不会出现黑色背景,就单独gif不行.
查了下资料发现了一个完美的解决办法,附带有详解...
现在写东西都喜欢封装成类.....大家调用一下就行了..我就不说怎么调用了
效果如下:
o_img_file=$oldfile; $this->o_img_width=$width; $this->o_img_height=$height; $this->n_img_file=$newfile; } //等比例缩放并且解决GIF透明色为黑色背景的问题 function get_resize_scaling_img(){ $this->n_img_width=$this->o_img_width*$this->o_to_n_per; $this->n_img_height=$this->o_img_height*$this->o_to_n_per; //等比例缩放图片(算法) if ( $this->n_img_width && ( $this->o_img_width o_img_height)) { $this->n_img_width = ( $this->n_img_height/$this->o_img_height) * $this->o_img_width; } else { $this->n_img_height = ($this->n_img_width / $this->o_img_width) * $this->o_img_height; } $this->o_img_source=imagecreatefromgif($this->o_img_file); //创建一个等比例缩放大小的画布 $this->n_img_source=imagecreatetruecolor($this->o_img_width,$this->n_img_height); //美化:去除黑色不透明背景 $trans_init=imagecolortransparent($this->o_img_source); //寻找透明色并且判断是否在总颜色中 if($trans_init>=0 && $trans_init o_img_source)){ //如果在的话则搜索这个颜色的RGB色相 $trans_index=imagecolorsforindex($this->o_img_source,$trans_init); //找到之后就创建这样一个颜色 $trans_new=imagecolorallocate($this->n_img_source,$trans_index["red"],$trans_index["green"],$trans_index["blue"]); //然后我们用这个颜色去填充新的图像 imagefill($this->n_img_source,0,0,$trans_new); //然后我们在把填充色设置为透明 imagecolortransparent($this->n_img_source,$trans_new); } //拷贝原图像到新画板上 imagecopyresized($this->n_img_source,$this->o_img_source,0,0,0,0,$this->n_img_width,$this->n_img_height,$this->o_img_width,$this->o_img_height); return $this->n_img_source; } //最终销毁资源 function __destruct(){ imagedestroy($this->o_img_source); imagedestroy($this->n_img_source); } }
说明:因为先前没想那么多所以声明了很多私有的内部变量以便调用...程序看起来很笨拙啊......