上传图片水印是指在图片上传到服务器后,为其添加一个或多个水印,以保护图片版权或增加品牌标识。水印可以是文字、图片或者两者的组合。
以下是一个简单的PHP上传图片并添加文字水印的实例:
<?php
// 检查是否有文件上传
if (isset($_FILES['image'])) {
$image = $_FILES['image'];
$image_tmp_name = $image['tmp_name'];
$image_size = $image['size'];
$image_error = $image['error'];
$image_type = $image['type'];
$image_name = $image['name'];
// 允许的文件类型
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($image_type, $allowed_types)) {
// 移动上传的文件到指定目录
$destination_folder = 'uploads/';
move_uploaded_file($image_tmp_name, $destination_folder . $image_name);
// 添加水印
$image_path = $destination_folder . $image_name;
$watermark_text = 'Watermark';
$font_size = 30;
$font_color = imagecolorallocatealpha(imagecreatefromstring(file_get_contents($image_path)), 255, 255, 255, 50);
$font_path = 'arial.ttf'; // 确保字体文件存在
$image = imagecreatefromstring(file_get_contents($image_path));
$text_width = imagettfbbox($font_size, 0, $font_path, $watermark_text);
$text_height = $text_width[1] - $text_width[7];
$x = imagesx($image) - $text_width[4] - 10;
$y = imagesy($image) - $text_height - 10;
imagettftext($image, $font_size, 0, $x, $y, $font_color, $font_path, $watermark_text);
// 保存带水印的图片
$output_image_path = $destination_folder . 'watermarked_' . $image_name;
imagepng($image, $output_image_path);
imagedestroy($image);
echo '图片上传并添加水印成功!';
} else {
echo '不支持的文件类型!';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>上传图片并添加水印</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/jpeg, image/png, image/gif">
<input type="submit" value="上传">
</form>
</body>
</html>
通过以上步骤,你可以实现一个简单的PHP上传图片并添加文字水印的功能。
领取专属 10元无门槛券
手把手带您无忧上云