php生成縮略圖,並把它輸出到網頁上,不過需在php文件頭加一句話:header("Content-Type:image/jpg");
代碼如下:
<?php
header("Content-Type:image/jpg");
class resizeImg {
private $type;
private $width;
private $height;
private $resize_width;
private $resize_height;
private $srcimg; //圖片源地址
private $desimg; //圖片目的地址
private $img; //新建臨時文件
private $cut; //判斷是否截圖
private $name; //文件名
function __construct($imgpath,$width,$height,$despath,$cut) { //圖片路徑,新寬度,新高度,目的地址,是否裁剪
$this->srcimg = $imgpath;
$this->resize_width = $width;
$this->resize_height = $height;
$this->cut = $cut;
$this->type = strtolower(substr(strrchr($this->srcimg,"."),1));
$this->init_img();
$this->name_img(); //獲取文件名
$this->des_img($despath); //將文件放到指定文件
$this->width = imagesx($this->img); //獲取圖像寬度
$this->height = imagesy($this->img); //獲取圖像高度
$this->new_img();
imagedestroy($this->img);
}
function init_img() { //初始化圖像
if($this->type == "jpg") {
$this->img = imagecreatefromjpeg($this->srcimg);
}elseif($this->type == "gif"){
$this->img = imagecreatefromgif($this->srcimg);
}
elseif($this->type == "png") {
$this->img = imagecreatefrompng($this->srcimg);
}
else{
echo "文件類型不對!!!";
}
}
function des_img($despath) { //圖象目標地址
$this->desimg = $despath.$this->name.'.'.$this->type; //把完整地址賦給$desimg
}
function name_img() {
$full_length = strlen($this->srcimg);
$type_length = strlen($this->type);
$name_length = $full_length-$type_length;
$this->name = substr($this->srcimg,0,$name_length-1); //獲取文件名
}
function new_img() { //新圖像
$resize_ratio = ($this->resize_width)/($this->resize_height); //新圖像比例
$ratio = ($this->width)/($this->height); //源圖像比例
if($this->cut == 1) { //截圖
if($ratio >= $resize_ratio) {
$newimg = imagecreatetruecolor($this->resize_width, $this->resize_height);
imagecopyresampled($newimg, $this->img, 0, 0, 0, 0, $this->resize_width, $this->resize_height, ($this->height)*$resize_ratio, $this->height);
imagejpeg($newimg,$this->desimg); //把圖片的內容輸出到$this->desimg上
imagejpeg($newimg); //將圖片輸出到網頁上
}else {
$newimg = imagecreatetruecolor($this->resize_width, $this->resize_height);
imagecopyresampled($newimg, $this->img, 0, 0, 0, 0, $this->resize_width, $this->resize_height, ($this->width)/$resize_ratio, $this->width);
imagejpeg($newimg,$this->desimg);
imagejpeg($newimg); ////將圖片輸出到網頁上
}
}
else { //不截圖
if($ratio >= $resize_ratio) {
$newimg = imagecreatetruecolor($this->resize_width, ($this->resize_width)/$ratio);
imagecopyresampled($newimg, $this->img, 0, 0, 0, 0, $this->resize_width, ($this->resize_width)/$ratio, $this->width, $this->height);
imagejpeg($newimg,$this->desimg);
imagejpeg($newimg); ////將圖片輸出到網頁上
}
else {
$newimg = imagecreatetruecolor(($this->resize_height)*$ratio, $this->resize_height);
imagecopyresampled($newimg, $this->img, 0, 0, 0, 0, ($this->resize_height)*$ratio, $this->resize_height, $this->width, $this->height);
imagejpeg($newimg,$this->desimg);
imagejpeg($newimg); // //將圖片輸出到網頁上
}
}
}
}
$resizeimg = new resizeImg("./1.jpg",200,200,"work/",0);
?>