[Yii Framework] A component for creating and getting the thumb image path

本文介绍了一种在Yii框架中创建图片缩略图的方法。通过安装phpThumb扩展并自定义ImageThumb组件,可以轻松地为不同尺寸生成图片缩略图。

There may be another good way to create and get the thumb image in Yii, here is my method to do it.

 

1. You have to install this extension, "phpthumb", please search this extension in this website. :P

 

2. Create a file named "ImageThumb.php", and locate it in protected/components , and insert the code as below:

ContractedBlock.gifExpandedBlockStart.gif代码
<?php
/**
*/
class ImageThumb extends CApplicationComponent
{
private $originalPath = "/upload/products/";
private $thumbPath = "/upload/thumbs";

public function createThumb($modelImage, $site="", $resizeW=100, $resizeH=100)
{
$oldImage = $modelImage;
$modelImage = $this->_thumbName($modelImage, $site);
$oldImageResite = $modelImage;

if(!file_exists(Yii::getPathOfAlias("webroot").$this->originalPath.$oldImage))
{
$modelImage = "thumb.jpg";//You shall have a thumb.jpg image exists in path of $this->originalPath
$oldImage = $modelImage;
$modelImage = $this->_thumbName($modelImage, $site);
$oldImageResite = $modelImage;
}




Yii
::app()->thumb->setThumbsDirectory($this->thumbPath);
if(!file_exists(Yii::getPathOfAlias("webroot").$this->thumbPath.$oldImageResite))
{
Yii
::app()->thumb
->load(Yii::getPathOfAlias("webroot").$this->originalPath.$oldImage)
->resize($resizeW, $resizeH)
->save($modelImage, "JPG", "JPG");
}
return $modelImage;
}




private function _thumbName($modelImage, $site)
{
if(!empty($site))
{
$tem = explode(".", $modelImage);
if(count($tem) > 1)
$modelImage = $tem[0]."_".$site.".".$tem[1];//the file name starts with "m_", "s_", or null;
}
return $modelImage;
}
}

 


 

 

3. Demo

ContractedBlock.gifExpandedBlockStart.gif代码
Yii::import("application.components.ImageThumb");
$imageThumb = new ImageThumb();



$imageOne
= $imageThumb->createThumb("example.jpg", "", 580, 280);
$imageTwo = $imageThumb->createThumb("example2.jpg", "s", 100, 70);

 


 


Have fun with Yii. :)

转载于:https://www.cnblogs.com/davidhhuan/archive/2010/08/23/1806818.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值