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程序設計有所幫助。
分享到:
投訴收藏