PHP图像处理绘图、水印、验证码、图像压缩技术实例总结(3)
	2019-01-22 15:21
	
互联网
	4、图像压缩
对图像进行压
缩处理非常简单,因为就一个函数
参数1:目标图像资源(画布)
参数2:等待压缩图像资源
参数3:目标点的x坐标
参数4:目标点的y坐标
参数5:原图的x坐标
参数6:原图的y坐标
参数7:目的地宽度(画布宽)
参数8:目的地高度(画布高)
参数9:原图宽度
参数10:原图高度
imagecopyresampled($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
封装的图像压缩类
- <?php
- /*
- * 图像压缩处理类
- */
- class- Thumb
- {
- private- $_filename- ;- //等待压缩的图像
- private- $_thumb_path- =- 'thumb/'- ;- //压缩图像的保存目录
- public- function- __set(- $p- ,- $v- )
- {
- if- (property_exists(- $this- ,- $p- )){
- $this- ->- $p- =- $v- ;
- }
- }
- //构造方法初始化需要压缩的图像
- public- function- __construct(- $file- )
- {
- if- (!- file_exists- (- $file- )){
- echo- '文件有误,不能压缩'- ;
- return- ;
- }
- $this- -> _filename =- $file- ;
- }
- //图像压缩处理
- function- makeThumb(- $area_w- ,- $area_h- )
- {
- $src_image- = imagecreatefrompng(- $this- ->_filename);
- $res- =- getimagesize- (- $this- ->_filename);
- echo- '<pre>'- ;
- var_dump(- $res- );
- die- ;
- $dst_x- = 0;
- $dst_y- = 0;
- $src_x- = 0;
- $src_y- = 0;
- //原图的宽度、高度
- $src_w- = imagesx(- $src_image- );- //获得图像资源的宽度
- $src_h- = imagesy(- $src_image- );- //获得图像资源的高度
- if- (- $src_w- /- $area_w- <- $src_h- /- $area_h- ){
- $scale- =- $src_h- /- $area_h- ;
- }
- if- (- $src_w- /- $area_w- >=- $src_h- /- $area_h- ){
- $scale- =- $src_w- /- $area_w- ;
- }
- $dst_w- = (int)(- $src_w- /- $scale- );
- $dst_h- = (int)(- $src_h- /- $scale- );
- $dst_image- = imagecreatetruecolor(- $dst_w- ,- $dst_h- );
- $color- = imagecolorallocate(- $dst_image- ,255,255,255);
- //将白色设置为透明色
- imagecolortransparent(- $dst_image- ,- $color- );
- imagefill(- $dst_image- ,0,0,- $color- );
- imagecopyresampled(- $dst_image- ,- $src_image- ,- $dst_x- ,- $dst_y- ,- $src_x- ,- $src_y- ,- $dst_w- ,- $dst_h- ,- $src_w- ,- $src_h- );
- //可以在浏览器直接显示
- //header("Content-Type:image/png");
- //imagepng($dst_image);
- //分目录保存压缩的图像
- $sub_path- =- date- (- 'Ymd'- ).- '/'- ;
- //规范:上传的图像保存到upload目录,压缩的图像保存到thumb目录
- if- (!- is_dir- (- $this- -> _thumb_path .- $sub_path- )){
- mkdir- (- $this- -> _thumb_path .- $sub_path- ,0777,true);
- }
- $filename- =- $this- -> _thumb_path .- $sub_path- .- 'thumb_'- .- $this- ->_filename;
- //也可以另存为一个新的图像
- imagepng(- $dst_image- ,- $filename- );
- return- $filename- ;
- }
- }
- $thumb- =- new- Thumb(- 'upload.jpg'- );
- $thumb- -> _thumb_path =- 'static/thumb/'- ;
- $file- =- $thumb- -> makeThumb(100,50);
- // var_dump($file);
以上就是PHP图像处理绘图、水印、验证码、图像压缩技术实例总结介绍,希望本文所述对大家PHP程序设计有所帮助。