1. 程式人生 > >PHP 圖片等比例縮放不失真

PHP 圖片等比例縮放不失真

<?php
/**
 * 圖片等比例縮放類
 * @author zhx
 */

class ImgThumbnail {

	private $source;
	private $imageinfo;
	private $image;
	private $percent = 0.1;
	private $newImageName;

	/**
	 * @param string $source 圖片url
	 * @param string $percent 預設就可以
	 * @param unknown $newImageName	儲存圖片的名稱
	 */
	public function __construct( $source, $percent, $newImageName ) {
		$this->source = $source;
		$this->percent = $percent;
		$this->newImageName = $newImageName;

		$this->openImage();
		$this->thumpImage();
		$this->showImage();
		$this->saveImage();
	}

	/**
	 * 開啟圖片
	 * @author zhx
	 */
	public function openImage() {
		list ( $width, $height, $type, $attr ) = getimagesize ( $this->source );

		$this->imageinfo = array (
				'width' => $width,
				'height' => $height,
				'type' => image_type_to_extension ( $type, false ),
				'attr' => $attr
		);

		$fun = "imagecreatefrom" . $this->imageinfo ['type'];
		$this->image = $fun ( $this->source );
	}

	/**
	 * 操作圖片
	 * @author zhx
	 */
	public function thumpImage() {
		$new_width = $this->imageinfo ['width'] * $this->percent;
		$new_height = $this->imageinfo ['height'] * $this->percent;
		$image_thump = imagecreatetruecolor ( $new_width, $new_height );
		// 將原圖複製帶圖片載體上面,並且按照一定比例壓縮,極大的保持了清晰度
		imagecopyresampled ( $image_thump, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->imageinfo ['width'], $this->imageinfo ['height'] );
		imagedestroy ( $this->image );
		$this->image = $image_thump;
	}

	/**
	 * 輸出圖片
	 * @author zhx
	 */
	public function showImage() {
		header ( 'Content-Type: image/' . $this->imageinfo ['type'] );
		$funcs = "image" . $this->imageinfo ['type'];
		$funcs ( $this->image );
	}

	/**
	 * 儲存圖片到硬碟
	 * @author zhx
	 */
	public function saveImage() {
		$funcs = "image" . $this->imageinfo ['type'];
		$funcs ( $this->image, $this->newImageName . '.' . $this->imageinfo ['type'] );
	}


	/**
	 * 銷燬圖片
	 * @author zhx
	 */
	public function __destruct() {
		imagedestroy ( $this->image );
	}


}

# 呼叫示例
// $image = new ImgThumbnail( $url , 0.2, 'test' );