Image.class.php
<?php
/*
* Image 图片操作类
*
* Author: DYmyw
* Email: dymayongwei@163.com
* Date: 2012/07/15
* Version: 1.0
*/
class Image{
public $srcimg;
private $type;
private $width;
private $height;
private $src_temp_img;
public $dstimg;
// 构造函数,初始化
public function __construct( $srcimg ){
$this->srcimg = $srcimg;
if ( @is_file( $this->srcimg ) ){
$file_info = pathinfo( $this->srcimg );
$this->type = strtolower( $file_info['extension'] );
$this->onInit();
$this->width = imagesx( $this->src_temp_img );
$this->height = imagesy( $this->src_temp_img );
} else {
// 错误提示!
}
}
// 生成图片缩略图
public function createThumbnail( $r_width, $r_height, $dstimg ){
$resize_prop = $r_width / $r_height;
$src_prop = $this->width / $this->height;
if ( $src_prop >= $resize_prop ){
$newimg = imagecreatetruecolor( $r_width , $r_width/$src_prop);
imagecopyresized($newimg, $this->src_temp_img, 0, 0, 0, 0, $r_width, $r_width / $src_prop, $this->width, $this->height);
} else {
$newimg = imagecreatetruecolor($r_height*$src_prop, $r_height);
imagecopyresized($newimg, $this->src_temp_img, 0, 0, 0, 0, $r_height * $src_prop, $r_height, $this->width, $this->height);
}
imagejpeg( $newimg, $dstimg );
}
// 图片水印
public function setWatermark( $W_pic, $p_x, $p_y, $desimg ){
if ( @is_file( $W_pic ) ){
$W_pic_info = pathinfo( $W_pic );
$W_pic_type = strtolower( $W_pic_info['extension'] );
switch ( $W_pic_type ){
case 'jpg':
$water_img = imagecreatefromjpeg( $W_pic );
break;
case 'gif':
$water_img = imagecreatefromgif( $W_pic );
break;
case 'png':
$water_img = imagecreatefrompng( $W_pic );
break;
case 'bmp':
$water_img = imagecreatefromwbmp( $W_pic );
break;
default:
break;
}
$water_img_width = imagesx( $water_img );
$water_img_height = imagesy( $water_img );
imagecopy($this->src_temp_img, $water_img, $p_x, $p_y, 0, 0, $water_img_width, $water_img_height);
imagejpeg( $this->src_temp_img, $desimg );
}
}
// 初始化载入图片
private function onInit(){
switch ( $this->type ){
case 'jpg':
$this->src_temp_img = imagecreatefromjpeg( $this->srcimg );
break;
case 'gif':
$this->src_temp_img = imagecreatefromgif( $this->srcimg );
break;
case 'png':
$this->src_temp_img = imagecreatefrompng( $this->srcimg );
break;
case 'bmp':
$this->src_temp_img = imagecreatefromwbmp( $this->srcimg );
break;
default:
break;
}
}
}
?>
使用方法:
<?php
include_once 'Image.class.php';
$Img = new Image('111.jpg');
$Img->createThumbnail(400, 400, 'Thumb.jpg');
$Img = new Image('Thumb.jpg');
$Img->setWatermark('222.gif', 15, 15, 'Watermark.jpg');
?>