上一篇
场景引入:
凌晨3点,你盯着电脑屏幕上的用户头像上传功能发呆——用户传了张10MB的风景照,而你的网站只需要100×100的小圆头像,这时,后台的PHP-GD库正摩拳擦掌:"让我来!" ✨
PHP内置的图像处理瑞士军刀,能完成:
💡 自1994年诞生至今(参考2025-08数据),仍是PHP生态最轻量高效的图像处理方案。
检查你的PHP环境:
<?php echo 'GD库已' . (extension_loaded('gd') ? '启用🎉' : '未安装😢'; print_r(gd_info()); // 查看支持的功能(如PNG/JPG支持) ?>
如果未安装,在php.ini
中取消注释extension=gd
即可~
function make_thumbnail($src_path, $max_size=200) { list($width, $height) = getimagesize($src_path); $ratio = min($max_size/$width, $max_size/$height); $new_width = (int)($width * $ratio); $new_height = (int)($height * $ratio); $src_image = imagecreatefromjpeg($src_path); $dst_image = imagecreatetruecolor($new_width, $new_height); // 保持透明色(PNG/GIF适用) imagecolortransparent($dst_image, imagecolorallocatealpha($dst_image, 0, 0, 0, 127)); imagefill($dst_image, 0, 0, IMG_COLOR_TRANSPARENT); imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagejpeg($dst_image, 'thumbnail.jpg', 85); // 85%质量 imagedestroy($src_image); }
function circle_avatar($image_path) { $src = imagecreatefromstring(file_get_contents($image_path)); $width = imagesx($src); $mask = imagecreatetruecolor($width, $width); imagealphablending($mask, false); $transparent = imagecolorallocatealpha($mask, 0, 0, 0, 127); imagefill($mask, 0, 0, $transparent); // 画个圆⚪ imagefilledellipse($mask, $width/2, $width/2, $width, $width, imagecolorallocate($mask, 0, 0, 0)); // 应用蒙版 imagealphablending($src, true); imagesavealpha($src, true); imagecopy($src, $mask, 0, 0, 0, 0, $width, $width); header('Content-Type: image/png'); imagepng($src); imagedestroy($src); }
session_start(); $code = substr(md5(uniqid()), 0, 6); $_SESSION['captcha'] = $code; $img = imagecreatetruecolor(150, 50); $bg_color = imagecolorallocate($img, rand(200,255), rand(200,255), rand(200,255)); imagefill($img, 0, 0, $bg_color); // 画干扰线🔄 for ($i=0; $i<5; $i++) { imageline($img, rand(0,150), rand(0,50), rand(0,150), rand(0,50), imagecolorallocate($img, rand(100,200), rand(100,200), rand(100,200))); } // 写入扭曲文字✍️ for ($i=0; $i<strlen($code); $i++) { imagettftext($img, 20, rand(-15,15), 20+$i*25, 35, imagecolorallocate($img, rand(0,100), rand(0,100), rand(0,100)), 'arial.ttf', $code[$i]); } header('Content-Type: image/jpeg'); imagejpeg($img);
imagedestroy()
释放资源 imagefilter()
实现老照片效果/浮雕化 🎯 GD库虽不如专业软件强大,但足够让PHP开发者变身"图片魔术师"!下次遇到图像需求,不妨先问问自己:"能用GD解决吗?"
(完)
本文由 公叔宏盛 于2025-08-01发表在【云服务器提供商】,文中图片由(公叔宏盛)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/508543.html
发表评论