PHP 图片处理,生成缩略图、圆形图片

<?php

/*

* name:娄喜贺

*/

class MyUpload{

var $saveName;// 保存名

var $tmpPath;// 临时保存路径

var $savePath;// 保存路径

var $fileFormat = array(‘gif‘,‘jpg‘,‘png‘,‘doc‘,‘application/octet-stream‘);// 文件格式&MIME限定

var $overwrite = 0;// 覆盖模式

var $maxSize = 0;// 文件最大字节

var $ext;// 文件扩展名

var $thumb = 0;// 是否生成缩略图

var $thumbWidth = 130;// 缩略图宽

var $thumbHeight = 130;// 缩略图高

var $thumbPrefix = "thumb_";// 缩略图前缀

var $errno;// 错误代号

var $returnArray= array();// 所有文件的返回信息s

var $returninfo= array();// 每个文件返回信息

var $thumbArray = array();//生成多个缩略图

var $_radius;// 圆形图半径

var $round;// 设置是否生成圆形图,1:是、0:否

var $roundArray;// 处理圆形图多个尺寸

//构造函数

// @param tmpPath 文件保存路径

// @param fileFormat 文件格式限制数组

// @param maxSize 文件最大尺寸

// @param overwriet 是否覆盖 1 允许覆盖 0 禁止覆盖

function MyUpload($params) {

$tmpPath = $params[‘tmpPath‘];

$savePath = $params[‘savePath‘];

$fileFormat = isset($params[‘fileFormat‘]) ? $params[‘fileFormat‘] : ‘‘;

$maxSize = isset($params[‘maxSize‘]) ? $params[‘maxSize‘] : 0;

$overwrite = isset($params[‘overwrite‘]) ? $params[‘overwrite‘] : 0;

$this->setSavepath($tmpPath,$savePath);

$this->setFileformat($fileFormat);

$this->setMaxsize($maxSize);

$this->setOverwrite($overwrite);

$this->setThumb($this->thumb, $this->thumbWidth,$this->thumbHeight);

$this->errno = 0;

}

// 上传

function run($fileInput,$changeName = 1){

if(isset($_FILES[$fileInput])){

$fileArr = $_FILES[$fileInput];

if(is_array($fileArr[‘name‘])){//上传同文件域名称多个文件

for($i = 0; $i < count($fileArr[‘name‘]); $i++){

$ar[‘tmp_name‘] = $fileArr[‘tmp_name‘][$i];

$ar[‘name‘] = $fileArr[‘name‘][$i];

$ar[‘type‘] = $fileArr[‘type‘][$i];

$ar[‘size‘] = $fileArr[‘size‘][$i];

$ar[‘error‘] = $fileArr[‘error‘][$i];

$this->getExt($ar[‘name‘]);//取得扩展名,赋给$this->ext,下次循环会更新

$this->setSavename($changeName == 1 ? ‘‘ : $ar[‘name‘]);//设置保存文件名

if($this->copyfile($ar)){

$this->returnArray[] =   $this->returninfo;

}else{

$this->returninfo[‘error‘] = $this->errmsg();

$this->returnArray[] =   $this->returninfo;

}

}

return $this->errno ?   false :   true;

}else{//上传单个文件

$this->getExt($fileArr[‘name‘]);//取得扩展名

$this->setSavename($changeName == 1 ? ‘‘ : $fileArr[‘name‘]);//设置保存文件名

if($this->copyfile($fileArr)){

$this->returnArray[] =   $this->returninfo;

}else{

$this->returninfo[‘error‘] = $this->errmsg();

$this->returnArray[] =   $this->returninfo;

}

return $this->errno ?   false :   true;

}

return false;

}else{

$this->errno = 10;

return false;

}

}

// 单个文件上传

function copyfile($fileArray){

$this->returninfo = array();

// 返回信息

$this->returninfo[‘name‘] = $fileArray[‘name‘];

$this->returninfo[‘saveName‘] = $this->saveName;

$this->returninfo[‘size‘] = number_format( ($fileArray[‘size‘])/1024 , 0, ‘.‘, ‘ ‘);//以KB为单位

$this->returninfo[‘type‘] = $fileArray[‘type‘];

$this->returninfo[‘tmpPath‘] = $this->tmpPath;

$this->returninfo[‘savePath‘] = $this->savePath;

// 检查文件格式

if (!$this->validateFormat()){

$this->errno = 11;

return false;

}

// 检查目录是否可写

if([email protected]_writable($this->tmpPath)){

$this->errno = 12;

return false;

}

// 如果不允许覆盖,检查文件是否已经存在

if($this->overwrite == 0 && @file_exists($this->tmpPath.$fileArray[‘name‘])){

$this->errno = 13;

return false;

}

// 如果有大小限制,检查文件是否超过限制

if ($this->maxSize != 0 ){

if ($fileArray["size"] > $this->maxSize){

$this->errno = 14;

return false;

}

}

// 文件上传

if([email protected]($fileArray["tmp_name"], $this->tmpPath.$this->saveName)){

$this->errno = $fileArray["error"];

return false;

}else{

if($this->round){

$fielName = $this->_round_it();

$this->_thumb($fielName, $this->roundArray);

}

if($this->thumb){//创建缩略图

$this->_thumb($this->saveName, $this->thumbArray);

}

}

// 删除临时文件

if([email protected]$this->del($fileArray["tmp_name"])){

return false;

}

return true;

}

// 生成画布对象

function _createFunction($fileName){

$CreateFunction = "imagecreatefrom".($this->ext == ‘jpg‘ ? ‘jpeg‘ : $this->ext);

if (strtolower($CreateFunction) == "imagecreatefromgif"

&& !function_exists("imagecreatefromgif")) {

$this->errno = 16;

return false;

} elseif (strtolower($CreateFunction) == "imagecreatefromjpeg"

&& !function_exists("imagecreatefromjpeg")) {

$this->errno = 17;

return false;

} elseif (!function_exists($CreateFunction)) {

$this->errno = 18;

return false;

}else{

return @$CreateFunction($this->tmpPath.$fileName);

}

}

// 保存图片

function _saveFunction($createdThumb, $prefix){

$SaveFunction = "image".($this->ext == ‘jpg‘ ? ‘jpeg‘ : $this->ext);

if ( !$SaveFunction($createdThumb,$this->tmpPath.$prefix.$this->saveName) ){

$this->errno = 22; return false;

}else{

return $prefix.$this->saveName;

}

}

//生成圆形图方画

private function _get_lt_rounder_corner() {

$radius = $this->_radius;

$img = imagecreatetruecolor($radius, $radius);

$bgcolor = imagecolorallocate($img, 255, 255, 255);

$fgcolor = imagecolorallocate($img, 0, 0, 0);

imagefill($img, 0, 0, $bgcolor);

imagefilledarc($img, $radius, $radius, $radius*2, $radius*2, 180, 270, $fgcolor, IMG_ARC_PIE);

imagecolortransparent($img, $fgcolor);

return $img;

}

/**

* 生成圆形图

*/

public function _round_it() {

// load the source image

$src_image = $this->_createFunction($this->saveName);

if ($src_image === false) {

die(‘Sorry, can/t load the image‘);

}

$image_width = imagesx($src_image);

$image_height = imagesy($src_image);

if($image_width < $image_height){

$imageSize = $image_width;

}else{

$imageSize = $image_height;

}

//$imageSize = 800;//$image_width;

$this->_radius = (int)$imageSize/2;

// create a new image, with src_width, src_height, and fill it with transparent color

$image = imagecreatetruecolor($imageSize, $imageSize);

$trans_color = imagecolorallocate($image, 255, 255, 255);

imagefill($image, 0, 0, $trans_color);

// then overwirte the source image to the new created image

imagecopymerge($image, $src_image, 0, 0, 0, 0, $imageSize, $imageSize, 100);

// then just copy all the rounded corner images to the 4 corners

$radius = $this->_radius;

// lt

$lt_corner = $this->_get_lt_rounder_corner();

imagecopymerge($image, $lt_corner, 0, 0, 0, 0, $radius, $radius, 100);

// lb

$lb_corner = imagerotate($lt_corner, 90, $trans_color);

imagecopymerge($image, $lb_corner, 0, $imageSize - $radius, 0, 0, $radius, $radius, 100);

// rb

$rb_corner = imagerotate($lt_corner, 180, $trans_color);

imagecopymerge($image, $rb_corner, $imageSize - $radius, $imageSize - $radius, 0, 0, $radius, $radius, 100);

// rt

$rt_corner = imagerotate($lt_corner, 270, $trans_color);

imagecopymerge($image, $rt_corner, $imageSize - $radius, 0, 0, 0, $radius, $radius, 100);

// set the transparency

imagecolortransparent($image,$trans_color);

return $this->_saveFunction($image, ‘round_‘);

}

// 生成缩略图

function _thumb($fileName, $thumbArray){

//返回值(缩略图)

$Original = $this->_createFunction($fileName);

if (!$Original) {$this->errno = 19; return false;}

$originalHeight = ImageSY($Original);

$originalWidth = ImageSX($Original);

if(!empty($thumbArray)){

foreach($thumbArray as $key => $row){

$this->thumbPrefix = $key;

$this->thumbHeight = $row[‘height‘];

$this->thumbWidth = $row[‘width‘];

//$this->returninfo[‘‘][‘thumbPrefix‘] = $this->thumbPrefix;

$this->returninfo[$this->thumbPrefix] = $this->thumbPrefix.$this->saveName;

if (($originalHeight < $this->thumbHeight

&& $originalWidth < $this->thumbWidth)) {

// 如果比期望的缩略图小,那只Copy

if( $originalHeight > $originalWidth ){// 宽 > 设定宽度

$thumbHeight = $originalHeight;

$thumbWidth = $this->thumbWidth*($originalHeight / $this->thumbWidth);

}else{//高 > 设定高度

$thumbWidth = $this->thumbWidth;

$thumbHeight = $this->thumbHeight*($originalHeight / $this->thumbHeight);

}

} else {

if( $originalWidth > $this->thumbWidth ){// 宽 > 设定宽度

$thumbWidth = $this->thumbWidth ;

$thumbHeight = $this->thumbWidth * ( $originalHeight / $originalWidth );

if($thumbHeight > $this->thumbHeight){//高 > 设定高度

$thumbWidth = $this->thumbHeight * ( $thumbWidth / $thumbHeight );

$thumbHeight = $this->thumbHeight ;

}

}elseif( $originalHeight > $this->thumbHeight ){//高 > 设定高度

$thumbHeight = $this->thumbHeight ;

$thumbWidth = $this->thumbHeight * ( $originalWidth / $originalHeight );

if($thumbWidth > $this->thumbWidth){//宽 > 设定宽度

$thumbHeight = $this->thumbWidth * ( $thumbHeight / $thumbWidth );

$thumbWidth = $this->thumbWidth ;

}

}

if ($thumbWidth == 0) $thumbWidth = 1;

if ($thumbHeight == 0) $thumbHeight = 1;

}

$createdThumb = imagecreatetruecolor($this->thumbWidth, $this->thumbHeight);

$color = imagecolorallocate($createdThumb,255,255,255);

imagefill($createdThumb, 0, 0, $color);

if ( !$createdThumb ) {$this->errno = 20; return false;}

if ( !imagecopyresampled($createdThumb, $Original, ($this->thumbWidth - $thumbWidth)/2, ($this->thumbHeight - $thumbHeight)/2, 0, 0,

$thumbWidth, $thumbHeight, $originalWidth, $originalHeight) )

{$this->errno = 21; return false;}

$this->_saveFunction($createdThumb, $this->thumbPrefix);

}

}

}

//------------------------------------------------------------------------

//建目录函数,其中参数$directoryName最后没有"/",

//要是有的话,以‘/‘打散为数组的时候,最后将会出现一个空值

function makeDirectory($directoryName) {

if(is_dir($directoryName)){

return true;

}

$directoryName = str_replace("\\","/",$directoryName);

$dirNames = explode(‘/‘, $directoryName);

$total = count($dirNames) ;

$temp = ‘‘;

for($i=0; $i<$total; $i++) {

$temp .= $dirNames[$i].‘/‘;

if (!is_dir($temp)) {

$oldmask = umask(0);

if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");

umask($oldmask);

}

}

return true;

}

//---------------------------------------------------------------------------

// 文件格式检查,MIME检测

function validateFormat(){

if(!is_array($this->fileFormat)

|| in_array(strtolower($this->ext), $this->fileFormat)

|| in_array(strtolower($this->returninfo[‘type‘]), $this->fileFormat) )

return true;

else

return false;

}

//获取文件扩展名

function getExt($fileName){

$ext = explode(".", $fileName);

$ext = $ext[count($ext) - 1];

$this->ext = strtolower($ext);

}

//设置上传文件的最大字节限制

// @param $maxSize 文件大小(bytes) 0:表示无限制

function setMaxsize($maxSize){

$this->maxSize = $maxSize;

}

//设置文件格式限定

// @param $fileFormat 文件格式数组

function setFileformat($fileFormat){

if(is_array($fileFormat)){$this->fileFormat = $fileFormat ;}

}

//设置覆盖模式

// @param overwrite 覆盖模式 1:允许覆盖 0:禁止覆盖

function setOverwrite($overwrite){

$this->overwrite = $overwrite;

}

//设置保存路径

// @param $tmpPath 文件保存路径:以 "/" 结尾,若没有 "/",则补上

function setSavepath($tmpPath,$savePath){

$this->tmpPath = substr( str_replace("\\","/", $tmpPath) , -1) == "/"

? $tmpPath : $tmpPath."/";

$this->savePath = substr( str_replace("\\","/", $savePath) , -1) == "/"

? $savePath : $savePath."/";

}

//设置缩略图

// @param $thumb = 1 产生缩略图 $thumbWidth,$thumbHeight 是缩略图的宽和高

function setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0){

$this->thumb = $thumb;

if($thumbWidth) $this->thumbWidth = $thumbWidth;

if($thumbHeight) $this->thumbHeight = $thumbHeight;

}

//设置文件保存名

// @saveName 保存名,如果为空,则系统自动生成一个随机的文件名

function setSavename($saveName){

if ($saveName == ‘‘){   // 如果未设置文件名,则生成一个随机文件名

$name = date(‘YmdHis‘)."_".rand(100,999).‘.‘.$this->ext;

} else {

$name = $saveName;

}

$this->saveName = $name;

}

//删除文件

// @param $file 所要删除的文件名

function del($fileName){

if([email protected]($fileName)){

$this->errno = 15;

return false;

}

return true;

}

// 返回上传文件的信息

function getInfo(){

return $this->returnArray;

}

// 得到错误信息

function errmsg(){

$uploadClassError = array(

0     =>‘文件上传成功 ‘,

1     =>‘The uploaded file exceeds the upload_max_filesize directive in php.ini.‘,

2     =>‘The uploaded file exceeds the MAX_FILE_SIZE that was specified in the HTML form.‘,

3     =>‘The uploaded file was only partially uploaded. ‘,

4     =>‘No file was uploaded. ‘,

6     =>‘Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ‘,

7     =>‘Failed to write file to disk. Introduced in PHP 5.1.0. ‘,

10   =>‘Input name is not unavailable!‘,

11   =>‘The uploaded file is Unallowable!‘,

12   =>‘Directory unwritable!‘,

13   =>‘File exist already!‘,

14   =>‘File is too big!‘,

15   =>‘Delete file unsuccessfully!‘,

16   =>‘Your version of PHP does not appear to have GIF thumbnailing support.‘,

17   =>‘Your version of PHP does not appear to have JPEG thumbnailing support.‘,

18   =>‘Your version of PHP does not appear to have pictures thumbnailing support.‘,

19   =>‘An error occurred while attempting to copy the source image .

Your version of php (‘.phpversion().‘) may not have this image type support.‘,

20   =>‘An error occurred while attempting to create a new image.‘,

21   =>‘An error occurred while copying the source image to the thumbnail image.‘,

22   =>‘An error occurred while saving the thumbnail image to the filesystem.

Are you sure that PHP has been configured with both read and write access on this folder?‘,

);

if ($this->errno == 0)

return false;

else

return $uploadClassError[$this->errno];

}

}

/**

* 调用上传图片类

* 上传图片

* Enter description here ...

* @param $inputFile表单中上传文件输入框input的名字

* @param $thumb设置是否生成缩略图,1:是,0:否

* @param $thumbWidth缩略图宽,单位是像素(px),留空则使用默认值 130

* @param $thumbHeight缩略图高,单位是像素(px),留空则使用默认值 130

* @param $thumbPrefix缩略图前缀,没有设置则使用默认值 thumb_

*/

public function _uploadImg($inputFile){

$savePath = UPLOADIMGPATH.date(‘Y‘,time()).‘/‘.date(‘m‘,time()).‘/‘.date(‘d‘,time());

$tmpPath = TMPIMGPATH.date(‘Y‘,time()).‘/‘.date(‘m‘,time()).‘/‘.date(‘d‘,time());

$params[‘savePath‘] = $savePath;

$params[‘tmpPath‘] = $tmpPath;

$this->load->library(‘myupload‘,$params);

$this->myupload->setThumb(1); // 设置是否生成缩略图

$this->myupload->round = 1; // 设置是否生成圆形图

//生成多个缩略图

$this->myupload->thumbArray = array(‘thumb_‘=>array(‘width‘=>76,‘height‘=>76));

//圆形图生成缩略图尺寸

$this->myupload->roundArray = array(‘round_pro_‘=>array(‘width‘=>76,‘height‘=>76));

//创建目录

$this->myupload->makeDirectory($savePath); // 保存目录

$this->myupload->makeDirectory($tmpPath); // 临时目录

//参数中的uploadinput是表单中上传文件输入框input的名字

//后面的0表示不更改文件名,若为1,则由系统生成随机文件名

$this->myupload->run($inputFile,1);

//获取上传结果

return $this->myupload->getInfo();

}

?>

时间: 2024-11-06 03:29:59

PHP 图片处理,生成缩略图、圆形图片的相关文章

php获取远程图片url生成缩略图的方法

getimg.php <?php /** * *函数:调整图片尺寸或生成缩略图 *返回:True/False *参数: * $Image 需要调整的图片(含路径) * $Dw=450 调整时最大宽度;缩略图时的绝对宽度 * $Dh=450 调整时最大高度;缩略图时的绝对高度 * $Type=1 1,调整尺寸; 2,生成缩略图 */ $phtypes=array('img/gif', 'img/jpg', 'img/jpeg', 'img/bmp', 'img/pjpeg', 'img/x-png

C# 生成缩略图 去除图片旋转角度

图片生成缩略图会有旋转角度 /// <summary> /// 测试JRE图片压缩后图片会旋转问题 /// </summary> public void Uploadimg1() { HttpPostedFile hpf = HttpContext.Current.Request.Files[0]; var context = HttpContext.Current; string newurl = context.Server.MapPath("/upload/img/

验证码识别与生成类API调用的代码示例合集:六位图片验证码生成、四位图片验证码生成、简单验证码识别等

以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 六位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数字+小写.数字+大写.数字+大小写等情况. 四位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数字+小写.数字+大写.数字+大小写等情况. 简单验证码识别:验证码类型 : 数字+字母, 纯英文, 纯数字,计算题 英数_验证码识别:纯数字,纯英文,数字+英文 中英数_验证码识别:英文.数

Bitmap长方形图片加载为圆形图片

package com.lib.andlib_libtemp.example.dir.exam1; import android.graphics.Bitmap;import android.graphics.Matrix;import android.view.View; import com.lib.andlib_libtemp.utils.LogUtil; /** * Created by envy15 on 2016/6/16. * 根据View的比例剪切图片大小工具类 * 剪切模式:中

分页、图片水印、缩略图【图片处理工具类】、php错误机制

1.分页技术[limit] 分页技术就是传入分页需要的每页的大小和当前页,对页的控制,实现分页的功能 使用分页的方式来展示相关的列表信息. [公司的分页是通过接口进行处理,因为我们只使用显示的部分,不用取库的操作,所以比较简单.使用ajax调用接口实现分页的异步显示] [做一个分页的工具类] [gd图片处理的相关] 2.缩略图 步骤: (1)在原图上采样,获取在原图上的采集区域 (2)拷贝:将文件复制一份 (3)修改:修改文件大小 (4)导出(imagejpeg)并销毁资源(destory) i

php使用GD库实现图片水印和缩略图——给图片添加图片水印

今天呢,就来学习一下在php中使用PD库来实现对图片水印的文字水印方法,不需要PS哦! 首先,准备素材 (1)准备一张图片 (2)准备一张水印(最好是透明的,即背景是白色底) (3)准备一中字体(在电脑中C:\Windows\Fonts位置里有,其中找一个自己喜欢的复制就行) (4)把上面3步准备的东西都放在一个文件夹中(在www文件夹目录下) 这是我的准备啦! (5)开启GD库功能(在php.ini文件中,把前面的分号去掉,重启服务器) 1.新建一个php文件(imageziti.php) 2

Android长方形图片生成正圆形,以及矩形图片生成圆角

一般要做正圆形图片,只能是正方形的基础上才能实现,否则就变成椭圆了,下面说说如何使长方形的图片生成正圆形图片 废话不多说,没图没真相,先上图吧: 原图:  变成正圆后:  下面上代码: public static Bitmap makeRoundCorner(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int left = 0, top = 0, right = width, b

自定义圆形图片

圆形图片相必是项目开发中也是不少用的一个知识点吧. 那么这里学习一下简单的制作圆形图片,主要运用 BitmapShader 类的知识来实现 一.首先,了解一下 BitmapShader 类 BitmapShader是Shader的子类,可以通过Paint.setShader(Shader shader)进行设置 看一下BitmapShader 的构造方法 BitmapShader bitmapShader = new BitmapShader(bitmap,TileMode, TileMode)

PHP使用JPG生成GIF动画图片,基于php_imagick_st-Q8.dll

PHP使用php_imagick_st-Q8.dll类库,把JPG图片连接生成GIF动画图片,需要事先下载好php_imagick_st-Q8.dll,文件,并配置php.ini文件,启用php_imagick_st-Q8.dll.配置方法如下: 1.将下载的php_imagick_st-Q8.dll文件放到PHP默认的扩展目录,也就是:php/ext/目录内: 2.打开php.ini,在extension区域新加入此行,注意前面不要有“;” extension=php_imagick_st-Q

nginx利用image_filter动态生成缩略图

原文:http://www.open-open.com/lib/view/open1416193847945.html "我现在是有些图片需要生成缩略图,这个现在加了image_filter这个已经实现了,但我不知道怎么样才能访问我上传的原图" 刚开始觉得也不太好弄,让他用程序区处理,实际上稍微动脑筋分析一下也可以不修改程序实现动态生成缩略图且能够访问原图. 前提是需要定好图片的访问规则. 先来看一下什么是nginx的image filter模块. HttpImageFilterMod