Thứ Hai, 22 tháng 1, 2024

Upload and Add Watermark to Image using PHP - Nhiều hình ảnh

 


## Dùng font: UTM Conestoga

<form method="post" action="javasript:void(0)">

<input type="file" name="txt_image[]" id="avatar-file" style="display:none;" multiple="multiple">

</form>

Lưu ý: hình phải to mới hiện logo lên được

## Cách 1: Upload tự chỉnh toạ độ ảnh

function upload__watermark($picname,$shoppath){

global $db,$adminfile,$site_live;

// Path configuration 
$targetDir = "../uploads/shop/pic/";


// $targetDir = "../uploads/";
$watermarkImagePath = '../admin/duynguyenshop.png'; 

 

// $statusMsg = ''; 

// if(isset($_POST["submit"])){ 

    if(!empty($_FILES["userfile"]["name"])){ 

        // File upload path 

    $picname=="";

        $fileName = basename($_FILES["userfile"]["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["userfile"]["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': 

                    # không cho nhập hình png

                        $im = imagecreatefrompng($targetFilePath);


                    #cho nhập hình png

                    #$im = imagecreatefromjpeg($targetFilePath);

                        break; 

                    default: 

                        $im = imagecreatefromjpeg($targetFilePath); 

                }                   

                // Set the margins for the watermark 

                // $marge_right = 10; 

                // $marge_bottom = 10;

                // nằm sát gốc phải



                $marge_right = 250; 

                $marge_bottom = 300;

                 

                // 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);

                imagepng($im, $targetFilePath);  

                imagedestroy($im);


                $picname = $fileName; 

     

                if(file_exists($targetFilePath)){ 

                    $statusMsg = "The image with watermark has been uploaded successfully."; 

                }else{ 

                    $statusMsg = "Image upload failed, please try again."; 

                }  


                return $picname;

            }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.'; 

    } 

    return $picname;

// } 

 

// Display status message 

// echo $statusMsg;

}


## Cách 1: Upload logo một ảnh canh giữa ảnh - max-width = 800px

function logo__watermark($picname){

if(isset($_FILES['userfile'])){     

    $max_size = 800; //max image size in Pixels     

    $destination_folder = "../uploads/shop/pic/";

    //path to watermark image
    // $watermark_png_file = '';

    $watermark_png_file = '../admin/duynguyenshop.png';       

    $image_name = $_FILES['userfile']['name']; //file name

    $image_size = $_FILES['userfile']['size']; //file size

    $image_temp = $_FILES['userfile']['tmp_name']; //file temp

    $image_type = $_FILES['userfile']['type']; //file type


    $picname = "";
    $picname = $image_name;


    switch(strtolower($image_type)){ 

    //determine uploaded image type

            //Create new image from file

            case 'image/png':

                $image_resource =  imagecreatefrompng($image_temp);

                break;

            case 'image/gif':

                $image_resource =  imagecreatefromgif($image_temp);

                break;         

            case 'image/jpeg': case 'image/pjpeg':

                $image_resource = imagecreatefromjpeg($image_temp);

                break;

            // default:

            //     $image_resource = false;

        }

   

    if($image_resource){


        //Copy and resize part of an image with resampling

        list($img_width, $img_height) = getimagesize($image_temp);

       

        //Construct a proportional size of new image

        $image_scale = min($max_size / $img_width, $max_size / $img_height);

        $new_image_width    = ceil($image_scale * $img_width);

        $new_image_height  = ceil($image_scale * $img_height);

        

        $new_canvas   = imagecreatetruecolor($new_image_width , $new_image_height);


        //Resize image with new height and width

        if(imagecopyresampled($new_canvas, $image_resource , 0, 0, 0, 0, $new_image_width, $new_image_height, $img_width, $img_height)){

           

            if(!is_dir($destination_folder)){

                mkdir($destination_folder);//create dir if it doesn't exist

            }

           

            //calculate center position of watermark image

            $watermark_left = ($new_image_width/2)-(300/2); //watermark left

            $watermark_bottom = ($new_image_height/2)-(100/2); //watermark bottom


            $watermark = imagecreatefrompng($watermark_png_file); //watermark image


            //use PHP imagecopy() to merge two images.

            // imagecopy($new_canvas, $watermark, $watermark_left, $watermark_bottom, 0, 0, 300, 100); 

            //merge image

            ## 300 ----- chiều dài ảnh watermark

            ## 100 ----- chiều cao hình ảnh watermark


            imagecopy($new_canvas, $watermark, $watermark_left, $watermark_bottom, 0, 0, 300, 32);

           

            //output image direcly on the browser.

            // header('Content-Type: image/jpeg');

            // imagejpeg($new_canvas, NULL ,90);

           

            //Or Save image to the folder

            imagejpeg($new_canvas, $destination_folder.'/'.$image_name , 90);

           

           

            //free up memory

            imagedestroy($new_canvas);

            imagedestroy($image_resource);

            // die();

            $picname = $image_name; 

            return $picname;

        }

    }

}

}


## Cách 3: Upload nhiều ảnh gắn logo & canh giữa ảnh - max-width = 800px

##┌────────────────────────────────────────────────┐     

  ## Note: watermark Logo nhiều hình ảnh cùng lúc.

<input type="file" name="txt_image[]" id="avatar-file" style="display:none;" multiple="multiple">


<div class="hien-icon">

<a onclick="$('#avatar-file').click();" id="choose-button-img" class="btn btn-primary">

    <i class="fa fa-picture-o" aria-hidden="true"></i>

    <span class="text font12">Chọn hình ảnh liên quan</span>

</a>

</div>

       ## Note: CSS:

        

## Note: File save ảnh

$time = time();

$files = $_FILES['txt_image'];

        $names      = $files['name'];

        $types      = $files['type'];

        $tmp_names  = $files['tmp_name'];

        $errors     = $files['error'];

        $sizes      = $files['size'];

        $path = "../uploads/shop/pic/";

        $numitems = count($names);

        $numfiles = 0;


    for ($i = 0; $i < $numitems; $i ++) {

        //Kiểm tra file thứ $i trong mảng file, up thành công không

        if ($errors[$i] == 0){

            $numfiles++;

$input_data2 = array(

"pid" => $id,

"images" => $time."_".$names[$i],

);


$sql2 ='INSERT INTO '.$prefix.'_shop_image '.$db->sql_build_array('INSERT', $input_data2).'';

if($db->sql_query($sql2)){

// move_uploaded_file($tmp_names[$i],$path.$time."_".$names[$i]);


$images = $time."_".$names[$i];

watermark__morepic($images,$tmp_names[$i],$types[$i]);

}

        }

    }

##└────────────────────────────────────────────────┘


function watermark__morepic($image_name,$image_temp,$image_type){


global $db,$site_live,$currentlang;


//max image size in Pixels    

        $max_size = 800;     

        $destination_folder = "../uploads/shop/pic/";

       //path to watermark image

       $watermark_png_file = '../admin/duynguyenshop.png';


    switch(strtolower($image_type)){ 

    //determine uploaded image type

        //Create new image from file

        case 'image/png':

            $image_resource =  imagecreatefrompng($image_temp);

            break;

        case 'image/gif':

            $image_resource =  imagecreatefromgif($image_temp);

            break;         

        case 'image/jpeg': case 'image/pjpeg':

            $image_resource = imagecreatefromjpeg($image_temp);

            break;

        // default:

        //     $image_resource = false;

    }

   

    if($image_resource){


        //Copy and resize part of an image with resampling

        list($img_width, $img_height) = getimagesize($image_temp);

       

        //Construct a proportional size of new image

        $image_scale = min($max_size / $img_width, $max_size / $img_height);

        $new_image_width    = ceil($image_scale * $img_width);

        $new_image_height  = ceil($image_scale * $img_height);

        

        $new_canvas   = imagecreatetruecolor($new_image_width , $new_image_height);


        //Resize image with new height and width

        if(imagecopyresampled($new_canvas, $image_resource , 0, 0, 0, 0, $new_image_width, $new_image_height, $img_width, $img_height)){

           

            if(!is_dir($destination_folder)){

                mkdir($destination_folder);//create dir if it doesn't exist

            }

           

            //calculate center position of watermark image

            $watermark_left = ($new_image_width/2)-(300/2); //watermark left

            $watermark_bottom = ($new_image_height/2)-(100/2); //watermark bottom


            $watermark = imagecreatefrompng($watermark_png_file); //watermark image


            //use PHP imagecopy() to merge two images.

            // imagecopy($new_canvas, $watermark, $watermark_left, $watermark_bottom, 0, 0, 300, 100); 

            //merge image

            ## 300 ----- chiều dài ảnh watermark

            ## 100 ----- chiều cao hình ảnh watermark

            ## chỉnh đúng kích thướt chiều dài + chiều cao. Nếu không bị đen phần dư ảnh 


            imagecopy($new_canvas, $watermark, $watermark_left, $watermark_bottom, 0, 0, 300, 32);

           

            //output image direcly on the browser.

            // header('Content-Type: image/jpeg');

            // imagejpeg($new_canvas, NULL ,90);

           

            //Or Save image to the folder

            imagejpeg($new_canvas, $destination_folder.'/'.$image_name , 90);

           

           

            //free up memory

            imagedestroy($new_canvas);

            imagedestroy($image_resource);

            // die();



            // $picname = $image_name; 

            // return $picname;


        }

    }

}

Không có nhận xét nào:

Đăng nhận xét