簡體   English   中英

帶水印的PHP圖片上傳

[英]PHP image upload with 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM