搜尋
首頁後端開發php教程为什么上传图片中含有透明通道,图片就会变成黑色?

p.s. 改的图片上传类原文地址:http://blog.csdn.net/a957651480/article/details/23124257

<?phpclass Images{	var $inputName;                 //控件名	var $allowType = array(				'image/gif','image/jpg','image/jpeg','image/png','image/x-png','image/pjpeg'	);	                           //上传类型	var $allowSize = 1048576;	//限制大小	var $saveDir = "";      //保存目录	var $FileName = ""; //文件名	var $isRename = false;               //是否重命名,默认为true	var $errID = 0;                     //错误代码,默认为0	var $errMsg = "";                   //错误信息	var $savePath = "";                 //保存路径	var $ImgSize = 0; //图片尺寸	function __construct($inputName,$allowType="",$allowSize="",$saveDir="",$isRename=true){		if(empty($inputName)){			$this->chk_err(-1);       //无传入控件名		}else{			$this->inputName = $inputName;		}		if(!empty($allowType)) $this->allowType = $allowType;		if(!empty($allowSize)) $this->allowSize = $allowSize;		if(!empty($saveDir)) $this->saveDir = $saveDir;		if(!empty($isRename)) $this->isRename = $isRename;	}	function is_uploaded(){		if(empty($_FILES[$this->inputName]['name'])){			$this->chk_err(4);    //没有文件被上传		}else{			if(is_uploaded_file($_FILES[$this->inputName]['tmp_name'])){				return true;			}else{				$this->chk_err(-2);       //文件上传不合法			}		}	}	function chk_type(){		if(!in_array($_FILES[$this->inputName]['type'],$this->allowType)){			$this->chk_err(-3);         //上传的文件类型不被允许		}else{			return true;		}	}	function chk_size(){		if($_FILES[$this->inputName]['size'] > $this->allowSize){			$this->chk_err(-4);          //上传的文件过大		}else{			return true;		}	}	function move_uploaded(){        //移动上传文件		if(!$this->is_uploaded()){			return false;		}		if(!$this->chk_size()){			return false;		}		if(!$this->chk_type()){			return false;		}		//重命名		if($this->isRename){			$arrTmp = pathinfo($_FILES[$this->inputName]['name']);			$extension = strtolower($arrTmp['extension']);			$file_newname = $this->FileName; //重命名新文件		}else{			$file_newname = $_FILES[$this->inputName]['name'];		}				if(!file_exists($this->saveDir)){       //判断保存目录是否存在			mkdir($this->saveDir,0777,true);    //建立保存目录		}		//移动文件		$result = move_uploaded_file($_FILES[$this->inputName]['tmp_name'],$this->saveDir."/".$file_newname);		if($result){			$path = $this->savePath = $this->saveDir."/".$file_newname;		//文件的成功保存路径			return $path;		}else{			$this->chk_err($_FILES[$this->inputName]['error']);		}		}	//判断出错信息	function chk_err($errID){		$this->errID = $errID;		switch($this->errID){			case -4:				$this->errMsg = '只能上传1M以内的图片 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			case -3:				$this->errMsg = '这不是一张图片 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			case -2:				$this->errMsg = '文件上传不合法 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			case -1:				$this->errMsg = '无控件名传入 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			case 1:				$this->errMsg = '上传的文件超出了php.ini中upload_max_filesize设定的最大值 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			case 2:				$this->errMsg = '上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			case 3:				$this->errMsg = '文件只有部分被上传 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			case 4:				$this->errMsg = '请选择一张图片 | <a href="javascript:window.history.back(-1);">[返回]</a>';				break;			default:				break;		}		return false;		}	function get_errMsg(){		echo $this->errMsg;  //输出错误信息	}    /**     +----------------------------------------------------------     * 取得图像信息     *     +----------------------------------------------------------     * @static     * @access public     +----------------------------------------------------------     * @param string $image 图像文件名     +----------------------------------------------------------     * @return mixed     +----------------------------------------------------------     */    function getImageInfo($img) {        $imageInfo = getimagesize($img);        if( $imageInfo!== false) {            $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]),1));            $imageSize = filesize($img);            $info = array(                "width"		=>$imageInfo[0],                "height"	=>$imageInfo[1],                "type"		=>$imageType,                "size"		=>$imageSize,                "mime"		=>$imageInfo['mime'],            );            return $info;        }else {            return false;        }    }	/**     +----------------------------------------------------------     * 生成缩略图     +----------------------------------------------------------     * @static     * @access public     +----------------------------------------------------------     * @param string $image  原图     * @param string $type 图像格式     * @param string $thumbname 缩略图文件名     * @param string $maxWidth  宽度     * @param string $maxHeight  高度     * @param string $position 缩略图保存目录     * @param boolean $interlace 启用隔行扫描     * @param boolean $is_save 是否保留原图     +----------------------------------------------------------     * @return void     +----------------------------------------------------------     */	     function thumb($image,$is_save=true,$suofang=0,$type='',$maxWidth=500,$maxHeight=500,$interlace=true){        // 获取原图信息       $info  = $this->getImageInfo($image);         if($info !== false) {            $srcWidth  = $info['width'];            $srcHeight = $info['height'];            $type = empty($type)?$info['type']:$type;			$type = strtolower($type);            $interlace  =  $interlace? 1:0;            unset($info);            if ($suofang==1) {                $width  = $srcWidth;                $height = $srcHeight;            } else {                $scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight); // 计算缩放比例                if($scale>=1) {                    // 超过原图大小不再缩略                    $width   =  $srcWidth;                    $height  =  $srcHeight;                }else{                    // 缩略图尺寸                    $width  = (int)($srcWidth*$scale);	//147                    $height = (int)($srcHeight*$scale);	//199                }            }            // 载入原图            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);            $srcImg     = $createFun($image);            //创建缩略图            if($type!='gif' && function_exists('imagecreatetruecolor'))                $thumbImg = imagecreatetruecolor($width, $height);            else                $thumbImg = imagecreate($width, $height);            // 复制图片            if(function_exists("ImageCopyResampled"))                imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth,$srcHeight);            else                imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height,  $srcWidth,$srcHeight);            if('gif'==$type || 'png'==$type) {                //imagealphablending($thumbImg, false);//取消默认的混色模式                //imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息                $background_color  =  imagecolorallocate($thumbImg,  0,255,0);  //  指派一个绿色				imagecolortransparent($thumbImg,$background_color);  //  设置为透明色,若注释掉该行则输出绿色的图            }            // 对jpeg图形设置隔行扫描            if('jpg'==$type || 'jpeg'==$type) 	imageinterlace($thumbImg,$interlace);            //$gray=ImageColorAllocate($thumbImg,255,0,0);            //ImageString($thumbImg,2,5,5,"ThinkPHP",$gray);			            // 生成图片            $imageFun = 'imagejpeg'; 			$length = strlen("00.".$type) * (-1);			$_type = substr($image,-4);			$length = ($type != $_type ? $length+1 : $length);            //裁剪            if ($suofang == 1){								//$thumbname01 = substr_replace($image,"01.".$type,$length);		//大头像				$thumbname02 = substr_replace($image,'.gif',-8);		//小头像				//$imageFun($thumbImg,$thumbname01,100);				$imageFun($thumbImg,$thumbname02,100);				                //$thumbImg01 = imagecreatetruecolor(190,195);                //imagecopyresampled($thumbImg01,$thumbImg,0,0,$_POST['x'],$_POST['y'],190,195,$_POST['w'],$_POST['h']);								$thumbImg02 = imagecreatetruecolor($this->ImgSize,$this->ImgSize);                imagecopyresampled($thumbImg02,$thumbImg,0,0,$_POST['x'],$_POST['y'],$this->ImgSize,$this->ImgSize,$_POST['w'],$_POST['h']);				//$imageFun($thumbImg01,$thumbname01,100);				$imageFun($thumbImg02,$thumbname02,100);												unlink($image);								//imagedestroy($thumbImg01);				imagedestroy($thumbImg02);				imagedestroy($thumbImg);				imagedestroy($srcImg);				return array(/*'big' => $thumbname01 ,*/ 'small' => $thumbname02);	//返回包含大小头像路径的数组				            }else{				if($is_save == false){											//缩略图覆盖原图,缩略图的路径还是原图路径					$imageFun($thumbImg,$image,100);				}else{					$thumbname03 = $image;	//缩略图与原图同时存在,					$imageFun($thumbImg,$thumbname03,100);					imagedestroy($thumbImg);					imagedestroy($srcImg);					return $thumbname03 ;					//返回缩略图的路径,字符串				}			}         }         return false;    }}


回复讨论(解决方案)

上传不会改变图片,你可以把图片贴在这里
对于 GD2 缩略图都应 imagecreatetruecolor、imagecopyresampled
如果有透明色,还需 imagecolortransparent

贴出图来看一下

贴出图来看一下





就是一张含透明通道的普通图片……


贴出图来看一下





就是一张含透明通道的普通图片……
你是怎么上传调用的,我刚才试了下你的图片,我这传完没问题

imagecreate 和 imagecreatetruecolor 产生的图片都是黑色的(注意:不是透明的)
你的图片是透明的,自然就将背景显现出来了
也就是说图片是放在黑色的背景上的了
所以被缩放的图片还需要设置透明色

$url = 'http://img.bbs.csdn.net/upload/201404/15/1397545309_839045.gif';$sm = imagecreatefromstring(file_get_contents($url));$dm = imagecreatetruecolor(imagesx($sm), imagesy($sm));//$dm = imagecreate(imagesx($sm), imagesy($sm));$c = imagecolorallocate($dm, 100, 1, 1);imagefill($dm, 0, 0, $c);imagecolortransparent($dm, $c);imagecopyresampled($dm, $sm, 0, 0, 0, 0, imagesx($dm), imagesy($dm), imagesx($sm), imagesy($sm));imagegif($dm);


我自己解决了。。还是谢谢你们,是我没有用imagefill事先填充的原因

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
解釋負載平衡如何影響會話管理以及如何解決。解釋負載平衡如何影響會話管理以及如何解決。Apr 29, 2025 am 12:42 AM

負載均衡會影響會話管理,但可以通過會話複製、會話粘性和集中式會話存儲解決。 1.會話複製在服務器間複製會話數據。 2.會話粘性將用戶請求定向到同一服務器。 3.集中式會話存儲使用獨立服務器如Redis存儲會話數據,確保數據共享。

說明會話鎖定的概念。說明會話鎖定的概念。Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

有其他PHP會議的選擇嗎?有其他PHP會議的選擇嗎?Apr 29, 2025 am 12:36 AM

PHP會話的替代方案包括Cookies、Token-basedAuthentication、Database-basedSessions和Redis/Memcached。 1.Cookies通過在客戶端存儲數據來管理會話,簡單但安全性低。 2.Token-basedAuthentication使用令牌驗證用戶,安全性高但需額外邏輯。 3.Database-basedSessions將數據存儲在數據庫中,擴展性好但可能影響性能。 4.Redis/Memcached使用分佈式緩存提高性能和擴展性,但需額外配

在PHP的上下文中定義'會話劫持”一詞。在PHP的上下文中定義'會話劫持”一詞。Apr 29, 2025 am 12:33 AM

Sessionhijacking是指攻擊者通過獲取用戶的sessionID來冒充用戶。防範方法包括:1)使用HTTPS加密通信;2)驗證sessionID的來源;3)使用安全的sessionID生成算法;4)定期更新sessionID。

PHP的完整形式是什麼?PHP的完整形式是什麼?Apr 28, 2025 pm 04:58 PM

文章討論了PHP,詳細介紹了其完整形式,在We​​b開發中的主要用途,與Python和Java的比較以及對初學者的學習便利性。

PHP如何處理形式數據?PHP如何處理形式數據?Apr 28, 2025 pm 04:57 PM

PHP使用$ \ _ post和$ \ _獲取超級全局的php處理數據,並通過驗證,消毒和安全數據庫交互確保安全性。

PHP和ASP.NET有什麼區別?PHP和ASP.NET有什麼區別?Apr 28, 2025 pm 04:56 PM

本文比較了PHP和ASP.NET,重點是它們對大規模Web應用程序,性能差異和安全功能的適用性。兩者對於大型項目都是可行的,但是PHP是開源和無關的,而ASP.NET,

PHP是對病例敏感的語言嗎?PHP是對病例敏感的語言嗎?Apr 28, 2025 pm 04:55 PM

PHP的情況敏感性各不相同:功能不敏感,而變量和類是敏感的。最佳實踐包括一致的命名和使用對案例不敏感的功能進行比較。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器