我正在编写一个程序,为用户上传的照片加水印。完成分层后,imagePNG() 将照片输出到浏览器,但不会将其保存到目录。路径都是正确的,文件权限更改为 0755。仅使用函数的第一个参数 ( imagePNG($image) ) 图像输出,但是当添加路径时 ( imagePNG($image, "photo_uploads/". $album_name ."/"))。
代码:
<?php
session_start();
use PHPImageWorkshop\ImageWorkshop;
$album_length = $_SESSION['album_length'];
$extension_array = $_SESSION['extension_array'];
$album_name = $_SESSION['album_name'];
chmod("photo_uploads/" . $album_name . "/", 0777);
for($i = 0; $i < $album_length; $i++) {
$path = 'photo_uploads/' . $album_name . '/' . $i . $extension_array[$i];
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('watermark.png');
//only works with png
$im = imagecreatefrompng($path);
// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);
// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
// Output and free memory
header('Content-type: image/png');
$save = "photo_uploads/" . $album_name . "/";
imagePNG($im, $save);
imagedestroy($im);
}
?>
我已经尝试了其他类似问题的所有解决方案。该函数将继续输出修改后的图像,除非将保存路径添加为第二个参数。
最佳答案
我不认为你的路径是正确的目录。原因是它应该保存文件或输出到浏览器,而不是两者。如果文件名是 NULL 那么它将输出到浏览器。尝试使用完整路径名。
文件名不以斜杠结尾
这是不正确的:
$save = "photo_uploads/" . $album_name . "/";
这有更多的工作机会:
imagePNG($im, $path);
使用完整路径:
/home/user/public_html/photo_uploads/something.png
我是这样做的:
ob_start();
imagepng($newPic, NULL, 9);
$png = ob_get_clean();
ob_clean();
ob_end_flush();
$fp = fopen($filename ,"w");
fwrite($fp, $png);
fclose($fp);
然后输出到浏览器(缩放):
$base64 = base64_encode($png);
echo "<img width=\"$newWidth\" height=\"$newHeight\" src=\"data:image/png;base64,$base64\" alt =\"profile photo\"/>";
关于PHP:imagePNG() 不会将文件保存到目录。文件权限都正确,还是不行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009995/