Home > php教程 > php手册 > body text

使用gd库实现php服务端图片裁剪和生成缩略图功能分享

WBOY
Release: 2016-06-06 20:26:02
Original
1208 people have browsed it

一般用户上传头像时,都会让用户自行裁剪图片。那么php怎么实现这个功能呢?php中裁剪图片主要使用gd库的imagecopyresampled方法

裁剪示例:

使用gd库实现php服务端图片裁剪和生成缩略图功能分享

最终裁剪成的图片:

使用gd库实现php服务端图片裁剪和生成缩略图功能分享

其中虚线框内就是要裁剪出来的图片,最终保存成100宽的图片。代码如下:

复制代码 代码如下:


$src_path = '1.jpg';
//创建源图的实例
$src = imagecreatefromstring(file_get_contents($src_path));

//裁剪开区域左上角的点的坐标
$x = 100;
$y = 12;
//裁剪区域的宽和高
$width = 200;
$height = 200;
//最终保存成图片的宽和高,和源要等比例,否则会变形
$final_width = 100;
$final_height = round($final_width * $height / $width);

//将裁剪区域复制到新图片上,并根据源和目标的宽高进行缩放或者拉升
$new_image = imagecreatetruecolor($final_width, $final_height);
imagecopyresampled($new_image, $src, 0, 0, $x, $y, $final_width, $final_height, $width, $height);

//输出图片
header('Content-Type: image/jpeg');
imagejpeg($new_image);

imagedestroy($src);
imagedestroy($new_image);

其实如果坐标为(0,0),裁剪区域的宽高和源图的宽高一致,那么就是生成缩略图的功能了。

总结

这里只列出了php裁剪图片的示例,,属于服务端的功能。如果客户端有需要,推荐一个jquery的插件imageAreaSelect,兼容性非常不错。

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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!