我正在尝试制作一个上传功能,为上传到内存中的每个文件添加水印,然后将文件保存到特定文件夹。但是,我无法使代码中的水印部分工作。我确信上传功能在没有添加水印代码的情况下工作。我认为错误必须是水印代码将临时文件“传输”到将文件移动到硬盘驱动器的代码。我该如何解决这个问题?
代码如下:
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
//$file_type=$_FILES['files']['type'][$key];
//if($file_size > 2097152){
//$errors[]='File size must be less than 2 MB';
//}
// echo '<img src="../images/watermark.gif">';
$q = "INSERT INTO media (file_name, album_id, file_size) VALUES ('$file_name','$album_id', '$file_size')";
$r = mysqli_query ($dbc, $q);
$desired_dir = '../../customers/' . $customerFolder . '/';
// load the watermark and the photo
$watermark = imagecreatefromgif('../images/watermark.gif');
$photo = imagecreatefromjpeg($file_tmp);
// center watermark on the photo
$wx = imagesx($photo)/2 - imagesx($watermark)/2;
$wy = imagesy($photo)/2 - imagesy($watermark)/2;
imagecopy($photo, $watermark, $wx, $wy, 0, 0, imagesx($watermark), imagesy($watermark));
if(empty($errors)==true){
move_uploaded_file($photo,"$desired_dir".$file_name);
//mysql_query($q);
}else{
print_r($errors);
}
}
答案 0 :(得分:1)
我提出了以下解决方案:
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefromgif('../images/watermark.gif');
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
//if($file_size > 2097152){
//$errors[]='File size must be less than 2 MB';
//}
// echo '<img src="../images/watermark.gif">';
$q = "INSERT INTO media (file_name, album_id, file_size) VALUES ('$file_name','$album_id', '$file_size')";
$r = mysqli_query ($dbc, $q);
$desired_dir = '../../customers/' . $customerFolder . '/';
$im = imagecreatefromjpeg($file_tmp);
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);
$newPath = "$desired_dir".$file_name;
imagepng($im, $newPath);
if(empty($errors)==true){
move_uploaded_file($newPath,"$desired_dir".$file_name);
imagedestroy($im);
//mysql_query($q);
}else{
print_r($errors);
}
}
if(empty($error)){
return 'ok';
}else {
return 'Kunne ikke uploade!';
}
}
答案 1 :(得分:0)
您正在尝试将move_uploaded_file
与resource
变量一起使用。
move_uploaded_file接受一个字符串,该字符串是临时文件的绝对路径。
因为您已经将临时文件读入资源,所以您只需将资源写入磁盘:
imagejpeg($photo,$desired_dir.$file_name);
临时文件会自动清理。