上传图像并使用PHP添加水印(Upload.php)
“upload.php”文件处理图像上传和水印添加功能。
- 使用PHP PathInfo()函数获取文件扩展并检查所选文件类型是否在允许的文件格式中。
- 使用PHP中的MOVE_UPLOADED_FILE()函数将文件上传到服务器。
- 使用imageCreatefropng()函数加载并从水印镜像创建一个新印章。
- 加载并根据文件类型从上载的图像创建新图像。
- 设置水印图像的右下边距。
- 获得水印图像的高度和宽度。
- 使用ImageCopy()函数将水印图像复制到上传的照片上。
- 使用裕度偏移和图像宽度来计算水印的定位。
- 使用imagepng()函数使用水印保存图像。
- 使用imagedestroy()函数与图像资源关联的释放内存。
- 显示水印图像上传状态。
<?php
//Path configuration
$targetDir = "uploads/";
$watermarkImagePath = 'onitroad-logo.png';
$statusMsg = '';
if(isset($_POST["submit"])){
if(!empty($_FILES["file"]["name"])){
//File upload path
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
//Allow certain file formats
$allowTypes = array('jpg','png','jpeg');
if(in_array($fileType, $allowTypes)){
//Upload file to the server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
//Load the stamp and the photo to apply the watermark to
$watermarkImg = imagecreatefrompng($watermarkImagePath);
switch($fileType){
case 'jpg':
$im = imagecreatefromjpeg($targetFilePath);
break;
case 'jpeg':
$im = imagecreatefromjpeg($targetFilePath);
break;
case 'png':
$im = imagecreatefrompng($targetFilePath);
break;
default:
$im = imagecreatefromjpeg($targetFilePath);
}
//Set the margins for the watermark
$marge_right = 10;
$marge_bottom = 10;
//Get the height/width of the watermark image
$sx = imagesx($watermarkImg);
$sy = imagesy($watermarkImg);
//Copy the watermark image onto our photo using the margin offsets and
//the photo width to calculate the positioning of the watermark.
imagecopy($im, $watermarkImg, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($watermarkImg), imagesy($watermarkImg));
//Save image and free memory
imagepng($im, $targetFilePath);
imagedestroy($im);
if(file_exists($targetFilePath)){
$statusMsg = "The image with watermark has been uploaded successfully.";
}else{
$statusMsg = "Image upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, and PNG files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
}
//Display status message
echo $statusMsg;
水印是保护图像免受被盗或者被另一个人重新使用的最佳选择。
我们可以通过将水印添加到图像来显示所有权。
水印有助于识别图像/照片的创建者。
主要是,水印戳在受版权保护的图像中使用。
通常,徽标或者创建者名称被添加到图像中作为水印。
使用PHP可以轻松实现将图像上传到服务器。
我们还可以使用PHP将水印添加到上传图像。
PHP GD库提供了一种简单的方法,将水印图像添加到使用Alpha通道的照片。
动态水印功能对于上传管理部分非常有用。
在本教程中,我们将展示如何将图像上传到服务器并使用PHP将水印添加到图像。
文件上传表单
创建一个HTML表单,允许选择要上载的文件。
- 确保<form>标记包含以下属性。
- method="post"
- enctype="multipart/form-data"
- 此外,请确保<input>标记包含'type =“file”'属性。
<form action="upload.php" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
在表单提交后,文件数据将发布到“upload.php”文件以使用PHP将水印添加到图像上。
日期:2020-06-02 22:16:00 来源:oir作者:oir
