search
HomeBackend DevelopmentPHP Tutorial php > 依据远程图片URL 生成缩略图

php > 根据远程图片URL 生成缩略图

<?php /**
*
*函数:调整图片尺寸或生成缩略图
*修改:2013-2-15
*返回: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');

function compressImg($Image,$Dw,$Dh,$Type){
	
	IF(!file_exists($Image)){
		return false;
	}
	// 如果需要生成缩略图,则将原图拷贝一下重新给$Image赋值(生成缩略图操作)
	// 当Type==1的时候,将不拷贝原图像文件,而是在原来的图像文件上重新生成缩小后的图像(调整尺寸操作)
	IF($Type!=1){
		copy($Image,str_replace(".","_x.",$Image));
		$Image=str_replace(".","_x.",$Image);
	}
	// 取得文件的类型,根据不同的类型建立不同的对象
	$ImgInfo=getimagesize($Image);
	Switch($ImgInfo[2]){
		case 1:
			$Img =@imagecreatefromgif($Image);
			break;
		case 2:
			$Img =@imagecreatefromjpeg($Image);
			Break;
		case 3:
			$Img =@imagecreatefrompng($Image);
			break;
	}
	// 如果对象没有创建成功,则说明非图片文件
	IF(Empty($Img)){
		// 如果是生成缩略图的时候出错,则需要删掉已经复制的文件
		IF($Type!=1){
			unlink($Image);
		}
		return false;
	}
	// 如果是执行调整尺寸操作则
	IF($Type==1){
		$w=ImagesX($Img);
		$h=ImagesY($Img);
		$width = $w;
		$height = $h;
		IF($width>$Dw){
			$Par=$Dw/$width;
			$width=$Dw;
			$height=$height*$Par;
			IF($height>$Dh){
				$Par=$Dh/$height;
				$height=$Dh;
				$width=$width*$Par;
			}
		} ElseIF($height>$Dh) {
			$Par=$Dh/$height;
			$height=$Dh;
			$width=$width*$Par;
			IF($width>$Dw){
				$Par=$Dw/$width;
				$width=$Dw;
				$height=$height*$Par;
			}
		} Else {
			$width=$width;
			$height=$height;
		}
		$nImg =ImageCreateTrueColor($width,$height);// 新建一个真彩色画布
		ImageCopyReSampled($nImg,$Img,0,0,0,0,$width,$height,$w,$h);// 重采样拷贝部分图像并调整大小
		ImageJpeg($nImg,$Image);// 以JPEG格式将图像输出到浏览器或文件
		return true;
	} Else {// 如果是执行生成缩略图操作则
		$w=ImagesX($Img);
		$h=ImagesY($Img);
		$width = $w;
		$height = $h;
		$nImg =ImageCreateTrueColor($Dw,$Dh);
		IF($h/$w>$Dh/$Dw){// 高比较大
			$width=$Dw;
			$height=$h*$Dw/$w;
			$IntNH=$height-$Dh;
			ImageCopyReSampled($nImg, $Img, 0, -$IntNH/1.8, 0, 0, $Dw, $height, $w, $h);
		} Else {// 宽比较大
			$height=$Dh;
			$width=$w*$Dh/$h;
			$IntNW=$width-$Dw;
			ImageCopyReSampled($nImg, $Img,-$IntNW/1.8,0,0,0, $width, $Dh, $w, $h);
		}
		ImageJpeg($nImg,$Image);
		return true;
	}
};



/**
 *根据url获取服务器上的图片
 *$url服务器上图片路径 $filename文件名
*/
function GrabImage($url,$filename="") {
	if($url=="") return false;
	if($filename=="") {
		$ext=strrchr($url,".");
		if($ext!=".gif" && $ext!=".jpg" && $ext!=".png")
			return false;
		$filename=date("YmdHis").$ext;
	}
	ob_start(); 
	readfile($url); 
	$img = ob_get_contents(); 
	ob_end_clean();
	$size = strlen($img); 

	$fp2=@fopen($filename, "a");
	fwrite($fp2,$img);
	fclose($fp2);
	return $filename;
}
?>




<?php //网络图片路径
$imgPath = 'http://news.jingway.cn/images/1382088444437.jpg';//远程URL 地址
$tempPath = 'aa/bbs.jpg';//保存图片路径

if(is_file($tempPath)){
	unlink($tempPath);
}

$bigImg=GrabImage($imgPath, $tempPath);

compressImg($bigImg,70,70,1);
?>


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.