WP添加图片上传水印

Published
2023-08-14
浏览次数 :  32

function add_watermark_to_uploaded_images($file) {
    $watermark_path = get_template_directory() . '/你的logo地址'; // Change this to the actual path of your watermark image
    $watermark = imagecreatefrompng($watermark_path);
    
    $image = wp_get_image_editor($file['file']);
    if (!is_wp_error($image)) {
        $image_size = $image->get_size();
        $watermark_size = getimagesize($watermark_path);
        
        // Calculate the position to overlay the watermark (you might need to adjust these values)
        $x = $image_size['width'] - $watermark_size[0] - 10;
        $y = $image_size['height'] - $watermark_size[1] - 10;
        
        $image->image_copy_resampled($watermark, $x, $y, 0, 0, $watermark_size[0], $watermark_size[1], $watermark_size[0], $watermark_size[1]);
        $image->save($file['file']);
    }
    
    return $file;
}

add_filter('wp_handle_upload', 'add_watermark_to_uploaded_images');

添加文字水印

function add_text_watermark_to_uploaded_images($file) {
    $text = 'Your Watermark Text'; // Change this to the text you want to use as the watermark
    $font_path = get_template_directory() . '/path-to-your-font.ttf'; // Change this to the actual path of your TTF font file
    $font_size = 20; // Adjust the font size as needed
    $font_color = imagecolorallocate($image, 255, 255, 255); // Adjust the color (white in this case)

    $image = wp_get_image_editor($file['file']);
    if (!is_wp_error($image)) {
        $image_size = $image->get_size();

        $image_resource = imagecreatefromjpeg($file['file']); // Change this to the appropriate imagecreatefrom* function based on the image type

        imagettftext($image_resource, $font_size, 0, 10, $image_size['height'] - 10, $font_color, $font_path, $text);

        // Save the watermarked image back
        imagejpeg($image_resource, $file['file']);

        imagedestroy($image_resource);
    }

    return $file;
}

add_filter('wp_handle_upload', 'add_text_watermark_to_uploaded_images');

文字水印修改字体

function add_text_watermark_to_uploaded_images($file) {
$text = 'Your Watermark Text';
$font_path = get_template_directory() . '/fonts/your-new-font.ttf'; // Change the path to your new font file
$font_size = 20;
$font_color = imagecolorallocate($image, 255, 255, 255);

$image = wp_get_image_editor($file['file']);
if (!is_wp_error($image)) {
    $image_size = $image->get_size();

    $image_resource = imagecreatefromjpeg($file['file']);

    imagettftext($image_resource, $font_size, 0, 10, $image_size['height'] - 10, $font_color, $font_path, $text);

    imagejpeg($image_resource, $file['file']);

    imagedestroy($image_resource);
}

return $file;

}

add_filter('wp_handle_upload', 'add_text_watermark_to_uploaded_images');


  • 标签1
  • 标签1
  • 标签1
Top