search
HomeBackend DevelopmentPHP TutorialImage processing class (improved version)

<?php #封装一个image类
class Image{
	private static $info;    #图片基本信息
	private static $image;   #内存中的图片

	public function __construct($src){
		#判断文件
		if(!is_file($src)){
			return false;
		} #如果不是文件,直接返回
		//获取图片信息
		$info = getimagesize($src);

		self::$info=array(
			&#39;width&#39;=>$info[0],
			'height'=>$info[1],
			'type'=>image_type_to_extension($info[2],false),
			'mime'=>$info['mime']
			);

		//获取图片信息
		$type=self::$info['type'];
		$fun ="imagecreatefrom{$type}";
		self::$image = $fun($src);
	}

	/**
	 * @param  int   $width  $height  应该在配置文件中声明使用,可取消参数
	 * @return 						  缩略图 图片资源
	 * 缩略图的形成与使用
	 */
	public function thumb($width ,$height){
		//新建镇色彩图片
		$image_thumb =imagecreatetruecolor($width ,$height);

		#获取图片的宽高比
		$src_m = self::$info['width'] / self::$info['height'];   #源文件空格比
		$dst_m = $width / $height;								 #缩略图宽高比

		#源文件图片是 N:1 型的  宽不变, 改变高
		if($src_m > $dst_m ){
			$cha_width = $width;
			$cha_height = ceil($width / $src_m) ; 
		}else{

		#源文件图片是 1:N 型的   高不变,改变宽
			$cha_width = floor($height * $src_m) ;
			$cha_height = $height ;
		}

		#对缩略图的其实位置进行重置
		$dst_x = ($width - $cha_width) /2 ;
		$dst_y = ($height - $cha_height) /2 ;

		imagecopyresampled($image_thumb ,self::$image , $dst_x , $dst_y ,0 , 0, $cha_width , $cha_height ,self::$info['width'],self::$info['height']);
	
		#生成缩略图
		self::$image =$image_thumb;
		// #显示缩略图图片
		// self::show(self::$image);

		#保存缩略图
		self::save(self::getNewName());

		//销毁图片
		imagedestroy($this->image_thumb);
		#返回缩略图名字
		return self::getNewName();
	}

	#水印的生成坐标
	private static function setLocal($pos){
		#对 pos 参数进行判断 , 指定相应的水印生成坐标
		#水印图片在config 文件中记录 $conf['mark']
		switch ($pos) {
			case 1:
				$x = 0;
				$y = 0;
			break ;

			case 2:
			default:
				$x = self::$info['width']-50;
				$y = self::$info['height']-50;   #不该是20 这个定制, 应该改成水印图片的宽高

		}
		return $local=array('x' => $x ,'y'=>$y);

	}

	#添加文字水印
	public function fontMark($content ,$font_url ,$size,$angle){
		#字体颜色
		$col = imagecolorallocatealpha(self::$image,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255),20);
		#获取水印输出位置坐标
		$local = self::setLocal(2);

		imagettftext(self::$image,$size,$angle,$local['x'],$local['y'],$col,$font_url,$content);
		#显示缩略图图片
		self::show(self::$image);
		#保存文字水印 没有添加保存路径
		self::save(self::getNewName());
		#返回水印图片的名字
		return self::getNewName();
 
	}

	#添加图片水印
	public function imageMark($url  ,$alpha){
		$info= getimagesize($url);  #获取图片信息
		$type=image_type_to_extension($info[2],false);
		$fun = "imagecreatefrom{$type}";
		
		#获取水印输出位置坐标
		$local = self::setLocal(2);

		$water = $fun($url);        #水印图片
		imagecopymerge(self::$image, $water, $local['x'], $local['y'],0 , 0,$info[0] , $info[1], 30);

		#销毁图片水印
		imagedestroy($water);

		#显示缩略图图片
		self::show(self::$image);

		#保存图片水印 没有添加保存路径
		self::save(self::getNewName());
		#返回水印图片的名字
		return self::getNewName();

	}

	#生成随机的 图片名字
	/**
	 * @return      string     				返回一个新的名字
	 * 
	 */
	private static function getNewName(){
		#获取一个时间
		$str = time();
		#获取随机字符串
		$string = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOASDFGHJKZXCVBNM1234567890";

		for($i=0 ; $i<br>
                
                
                <p>
                    The above introduces the image processing class (improved version), including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials. </p>
                <p>
                    </p>
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor