带水印的PHP图片上传

标签 php image upload watermark

我有这段代码可以上传带水印的图片。该代码工作正常,但水印功能将所有上传的图像重新调整为较小的宽度和高度。我想在添加水印后保留大小。我相信问题出在功能上,但我不知道如何解决。

if(isset($_FILES)){
    $file = $_FILES['image'];
    $allowedExts = array('jpg','png','gif','jpeg');
    $uploadsDirectory = "imgupload/";
    $maxSize = 2000000;

    for($i = 0; $i < count($file['name']); $i++){
        $filetmpname = $file['tmp_name'][$i];       
        $errors = array();
        $filename = $file['name'][$i];
        $filetext = strtolower(end(explode('.',$filename)));
        $filesize = $file['size'][$i];
        $filetmpname = $file['tmp_name'][$i];

        if(in_array($filetext, $allowedExts) === FALSE){
            $errors[] = "Extension is not allowed"; 
        }

        if($filesize > $maxSize){
            $errors[] = "File Size must be less than {$maxSize} KB";
        }

        if(empty($errors)){   
            $random = rand(0,199);
            $destination = $file['name'][$i] = $uploadsDirectory. $random."_".date("d-m-Y") . "_" . $file['name'][$i];
            $upload_status = move_uploaded_file($filetmpname, $destination);  

            if($upload_status){
                $new_name = $uploadsDirectory.$random."_".date("d-m-Y") . "_" .".jpg";
                if(watermark_image($destination, $new_name))
                    $demo_image = $new_name;
            }
        }
    }
}

水印功能:

$image_path = "images/water.png"; 

function watermark_image($oldimage_name, $new_image_name)
    {
        global $image_path;
        list($owidth,$oheight) = getimagesize($oldimage_name);
        $width = $height = 300;    
        $im = imagecreatetruecolor($width, $height);
        $img_src = imagecreatefromjpeg($oldimage_name);
        imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
        $watermark = imagecreatefrompng($image_path);
        list($w_width, $w_height) = getimagesize($image_path);        
        $pos_x = $width - $w_width; 
        $pos_y = $height - $w_height;
        imagecopy($im, $watermark, $pos_x, $pos_y, 0, 0, $w_width, $w_height);
        imagejpeg($im, $new_image_name, 100);
        imagedestroy($im);
        unlink($oldimage_name);
        return true;
    } 

最佳答案

您将在此处获取现有图像的大小:

list($owidth,$oheight) = getimagesize($oldimage_name);
$width = $height = 300;    

这是制作不同尺寸图像的地方:

imagecopyresampled($im, $img_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);

http://php.net/manual/en/function.imagecopyresampled.php

关于带水印的PHP图片上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36027083/

相关文章:

php - 尝试在我的网站上注册时的密码长度情况

javascript - 在 vue 组件中检索配置和环境变量

php - 使用 php 将图像保存到不同的 url

python - gem 迷阵风格的游戏比赛

php - 从 wordpress 帖子中排除类别

c# - 如何使用 C# 和 ASP.NET 从网页截取 div 的屏幕截图?

html - Camtasia html 页面视频上传到服务器时不播放

PHP 上传给定名称的图像

javascript - JQuery 上传、预览、裁剪

php - Laravel 查询生成器 - 联合 - 未找到列错误