現在越來越多ajax上傳圖片是使用將圖片轉換成base64的形式,再將圖片的資料串傳遞給後端做存檔。但是後端要怎麼驗證這個base64的資料串為圖片呢?下面提供一個簡單的函數給大家參考!!

   function check_base64_image($base64='',$type='png') {
	    //自動過濾掉 data:image/png;base64, 前綴
	    if(mb_strpos($base64, ",", 0,'UTF-8' )>0){
	    	$base64=explode(",",$base64);
	    	if(isset($base64[1])){
	    		$base64=$base64[1];
	    	} 
	    }
	    $img = imagecreatefromstring(base64_decode($base64));
	    if (!$img) {  
	        return false;
	    }
	    if($type=='png'){
	    	$tmp_name=time().'tmp.png'; 
		    imagepng($img, $tmp_name);
		    
	    }elseif($type=='jpg'){
	    	$tmp_name=time().'tmp.jpg'; 
		    imagejpeg($img, $tmp_name); 
	    }
	    $info = getimagesize($tmp_name); 
            unlink($tmp_name); 
	    if ($info[0] > 0 && $info[1] > 0 && $info['mime']) { 
	        return true;
	    } 
	    return false; 
}



文章轉載或引用,請先告知並保留原文出處與連結!!(單純分享或非營利的只需保留原文出處,不用告知)

原文連結:
https://blog.aidec.tw/post/check-base64-image