Home Backend Development PHP Tutorial PHP从0单排(十八)图片处理

PHP从0单排(十八)图片处理

Jun 13, 2016 am 11:56 AM
gt image img lt quot

PHP从零单排(十八)图片处理

1.打开已经存在的图片

<?phpheader ("Content-type:image/jpeg"); $img=imagecreatefromjpeg("cc.jpg");imagejpeg($img);imagedestroy($img);?>
Copy after login
函数imagecreatefromjpeg()的参数即文件所在路径,返回值是参数所指图片的资源标识符。该函数时通过已有图像新建一个图像,并不是单纯打开原图像本身。如果将图片的后缀名.jpg强制改为.png,即便是使用函数imagecreatefrompng(),也无法打开文件,因为图片本质还是jpg格式的图片。

2.获取图片的相关属性

<?php $img=imagecreatefromjpeg("cc.jpg");$x=imagesx($img);$y=imagesy($img);echo "图片cc.jpg的宽为:<b>$x pixels";echo "<br>";echo "<br>";echo "图片cc.jpg的高为:<b>$y</b> pixels";?>
Copy after login

另外,通过一个不属于GD库的函数getimagesize(),可以取得图片的大小等相关属性,该函数的语法如下:

array getimagesize(string $filename [, array &imageinfo])

<?php $img_info=getimagesize("cc.jpg");for($i=0;$i<4;++$i){	echo $img_info[$i];	echo "<br/>";		}?>
Copy after login
第三个元素是图片的格式,它的取值含义如下所示:

1:表示该图片是GIF格式

2:表示该图片是JPG格式

3:表示该图片是PNG格式

4:表示该图片是SWF格式

5:表示该图片是PSD格式

6:表示该图片是BMP格式

<?php $pic_name="ee.png";$pic_size=getimagesize($pic_name);?><img  src="<?php%20echo%20%24pic_name;%20?>" echo alt="PHP从0单排(十八)图片处理" >>
Copy after login

3.对图片加水印效果

·获取要添加水印的图片的宽、高值

·确定图片大小是否满足水印文字大小

·确定水印效果在图片中的位置

·设定图像的混色模式

·生成水印效果

·释放资源

<?php function makeimagewatermark($image,$pos,$water_text,$font_size,$color){	$font_type="c://WINDOWS//Fonts//SIMYOU.TTF";	if(!empty($image)&& file_exists($image))	{		$img_info=getimagesize($image);		$g_w=$img_info[0];		$g_h=$img_info[1];		switch($img_info[2])		{			case 1:			$img=imagecreatefromgif($image);			break;			case 2:			$img=imagecreatefromjpeg($image);			break;			case 3:			$img=imagecreatefrompng($image);			break;			default:			die("Format Wrong");						}				}	else 	{		die("Not exists!");				}		$temp=imagettfbbox(ceil($font_size*2.5),0,$font_type,$water_text);	$w=$temp[2]-$temp[6];	$h=$temp[3]-$temp[7];	if(($g_w<$w) || ($g_h<$h))	{		echo "Too small!";		return;				}	switch($pos){	case 0:	$pos_x=rand(0,($g_w-$w));	$pos_y=rand(0,($g_h-$h));	break;	case 1:	$pos_x=0;	$pos_y=0;	break;	case 2:	$pos_x=($g_w-$w)/2;	$pos_y=($g_h-$h)/2;	break;	case 3:	$pos_x=$g_w-$w;	$pos_y=$g_h-$h;	break;	default:	$pos_x=rand(0,($g_w-$w));	$pos_y=rand(0,($g_h-$h));	break;		}			imagealphablending($img,true);//设置图像混色模式		if(!empty($color) && (strlen($color)==7)){	$R=hexdec(substr($color,1,2));	$G=hexdec(substr($color,3,2));	$B=hexdec(substr($color,5));		}		else 	{		die("Format wrong!");				}		$text_color=imagecolorallocate($img,$R,$G,$B);				imagettftext($img,$font_size,0,$pos_x,$pos_y,$text_color,$font_type,$water_text);				switch($img_info[2])		{			case 1 :			imagegif($img,$image);			break;			case 2 :			imagejpeg($img,$image);			break;			case 3:			imagepng($img,$image);			break;			default:			die("Formate unSupport!");						}	imagedestroy($img);		}if(isset($_FILES) && !empty($_FILES['userfile'])&& $_FILES['userfile']['size']>0){$uploadfile="./".time()."_".$_FILES['userfile']['name'];if(copy($_FILES['userfile']['tmp_name'],$uploadfile)){    makeimagewatermark($uploadfile,2,"Photo by Mac",16,"#43042A");	echo "<img  src="%5C%22%22.%24uploadfile.%22%5C%22" border='\"0\"' alt="PHP从0单排(十八)图片处理" >";		}else{	echo "uploadWrong!<br>";	}}?><title>19.9.php</title>
Copy after login
选择上传图片:

4.生成已有图片的缩略图

<?php header("Content-type:image/jpeg");$img_name="cc.jpg";$src_img=imagecreatefromjpeg($img_name);$ow=imagesx($src_img);$oh=imagesy($src_img);$nw=round($ow*200.0/$ow);$nh=round($oh*200.0/$oh);$desc_img=imagecreate($nw,$nh);imagecopyresized($desc_img,$src_img,0,0,0,0,$nw,$nh,$ow,$oh);imagejpeg($desc_img);imagedestroy($desc_img);imagedestroy($src_img);?>
Copy after login
第一个和第二个参数分别是目标图像、原图像的标识符,接下来4个参数是目的图像和原图像的复制位置的坐标,最后4个参数是目的图像和原图像的复制区域的宽高。
!!使用函数imagecopyresampled()函数

<?php header("Content-type:image/jpeg");$img_name="cc.jpg";$percent=0.2;$src_img=imagecreatefromjpeg($img_name);$ow=imagesx($src_img);$oh=imagesy($src_img);$nw=$ow*$percent;$nh=$oh*$percent;$desc_img=imagecreatetruecolor($nw,$nh);imagecopyresampled($desc_img,$src_img,0,0,0,0,$nw,$nh,$ow,$oh);imagejpeg($desc_img);imagedestroy($desc_img);imagedestroy($src_img);?>
Copy after login




Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open img file How to open img file Sep 18, 2023 am 09:40 AM

Methods to open img files include using virtual optical drive software, using compression software, and using special tools. Detailed introduction: 1. Use virtual optical drive software to open, download and install a virtual optical drive software, right-click the img file, select "Open with" or "Associated Program", select the installed virtual optical drive software in the pop-up dialog box, virtual The optical drive software will automatically load the img file and use it as a disc image in the virtual optical drive. Double-click the disc icon in the virtual optical drive to open the img file and access its contents, etc.

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

How to open img file How to open img file Jul 06, 2023 pm 04:17 PM

How to open the img file: 1. Confirm the img file path; 2. Use the img file opener; 3. Select the opening method; 4. View the picture; 5. Save the picture. The img file is a commonly used image file format, usually used to store picture data.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

What is the format of img? What is the format of img? Mar 17, 2023 am 10:33 AM

img is a file compression format, mainly used to create image files of floppy disks. It can be used to compress the contents of an entire floppy disk or an entire CD; files with the extension ".IMG" are created using this file format. ; The img file includes 3 basic nodes, namely "Ehfa_HeaderTag", "Ehfa_File" and "Ehfa_Entry".

How to use Bing Image Creator for free How to use Bing Image Creator for free Feb 27, 2024 am 11:04 AM

This article will introduce seven ways to get high-quality output using the free BingImageCreator. BingImageCreator (now known as ImageCreator for Microsoft Designer) is one of the great online artificial intelligence art generators. It generates highly realistic visual effects based on user prompts. The more specific, clear, and creative your prompts are, the better the results will be. BingImageCreator has made significant progress in creating high-quality images. It now uses Dall-E3 training mode, showing a higher level of detail and realism. However, its ability to consistently produce HD results depends on several factors, including fast

How to delete images from Xiaomi phones How to delete images from Xiaomi phones Mar 02, 2024 pm 05:34 PM

How to delete images on Xiaomi mobile phones? You can delete images on Xiaomi mobile phones, but most users don’t know how to delete images. Next is the tutorial on how to delete images on Xiaomi mobile phones brought by the editor. Interested users can come and join us. Let's see! How to delete images on Xiaomi mobile phone 1. First open the [Album] function in Xiaomi mobile phone; 2. Then check the unnecessary pictures and click the [Delete] button in the lower right corner; 3. Then click [Album] at the top to enter the special area , select [Recycle Bin]; 4. Then directly click [Empty Recycle Bin] as shown in the figure below; 5. Finally, directly click [Permanent Delete] to complete.

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

See all articles