Home > Backend Development > PHP Tutorial > PHP generates image thumbnails and displays them in the browser, flexible and practical

PHP generates image thumbnails and displays them in the browser, flexible and practical

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-29 09:01:22
Original
1174 people have browsed it

Because I personally need to upload pictures to the website album and display them in the form of thumbnails, Baidu searched a lot of source codes and tried and failed. I wrote a function myself and it has run successfully. The way to display thumbnails in the browser is to point the src address of the image to a PHP file and call this function to display it.

/**
 *  _thumb()生成缩略图的函数
 */

function _thumb($_filename,$_max_size){  //(图片源地址,最大宽or高)
	//获取文件后缀
	$_n = explode('.', $_filename);
	//生成png表头文件
	header('Content-type:image/png');
	//获取文件的长和高
	list($_width,$_height) = getimagesize($_filename);
	//生成微缩的长和高
	$_percent = $_max_size / (($_width > $_height) ? $_width:$_height);
	$_new_width = $_width * $_percent;
	$_new_height = $_height * $_percent;
	//创建一个微缩画布
	$_new_image = imagecreatetruecolor($_new_width, $_new_height);
	//按照已有的图片创建一个画布
	switch ($_n[1]) {
		case 'jpg':
			$_image = imagecreatefromjpeg($_filename);
			break;
		case 'png':
			$_image = imagecreatefrompng($_filename);
			break;
		case 'gif':
			$_image = imagecreatefromgif($_filename);
			break;
	}
	//将原图采集后重新复制到图上,就缩略了
	imagecopyresampled($_new_image, $_image, 0,0,0,0, $_new_width, $_new_height, $_width, $_height);
	imagepng($_new_image);
	imagedestroy($_new_image);
	imagedestroy($_image);
}
Copy after login

The above introduces how to generate image thumbnails with PHP and display them in the browser. It is flexible and practical, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Latest Issues
Image tag editing
From 1970-01-01 08:00:00
0
0
0
Modify image size
From 1970-01-01 08:00:00
0
0
0
How to load default image on Twitter?
From 1970-01-01 08:00:00
0
0
0
​Image cannot be previewed
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template