php 怎么图片

在 PHP 中处理图片,你可以使用 GD 库或者 ImageMagick 等库。以下是一些基本的图片处理操作:
创建图片
:
$im = imagecreatetruecolor(100, 100);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, ‘A Simple Text String’, $text_color);
header(‘Content-type: image/png’);
imagepng($im);
imagedestroy($im);
读取图片
:
$image = imagecreatefromjpeg(‘path_to_image.jpg’);
输出图片
:
header(‘Content-type: image/jpeg’);
imagejpeg($image);
imagedestroy($image);
图片缩放
:
$new_width = 80;
$new_height = 80;
$thumb = imagecreatetruecolor($new_width, $new_height);
$source_image = imagecreatefromjpeg(‘path_to_image.jpg’);
imagecopyresized($thumb, $source_image, 0, 0, 0, 0, $new_width, $new_height, imagesx($source_image), imagesy($source_image));
imagejpeg($thumb);
imagedestroy($thumb);
imagedestroy($source_image);
图片裁剪
:
$dst_img = imagecreatetruecolor($dst_width, $dst_height);
$src_img = imagecreatefromjpeg(‘path_to_image.jpg’);
imagecopyresampled($dst_img, $src_img, 0, 0, $src_x, $src_y, $dst_width, $dst_height, $src_width, $src_height);
imagejpeg($dst_img);
imagedestroy($dst_img);
imagedestroy($src_img);
图片旋转
:
$image = imagecreatefromjpeg(‘path_to_image.jpg’);
$rotated = imagerotate($image, 90, 0);
imagejpeg($rotated);
imagedestroy($rotated);
imagedestroy($image);
图片添加文字
:
$image = imagecreatefromjpeg(‘path_to_image.jpg’);
$white = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 1, 5, 5, ‘Hello World!’, $white);
imagejpeg($image);
imagedestroy($image);
图片添加水印
:
$image = imagecreatefromjpeg(‘path_to_image.jpg’);
$watermark = imagecreatefrompng(‘path_to_watermark.png’);
imagecopy($image, $watermark, 10, 10, 0, 0, imagesx($watermark), imagesy($watermark));
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
确保在运行这些代码之前,你的服务器已经安装了 GD 库,并且 PHP 配置文件(php.ini)中已经启用了 GD 扩展。
如果你需要更高级的图片处理功能,可以考虑使用 ImageMagick 库,它提供了更多功能和灵活性。