Skip to content

Instantly share code, notes, and snippets.

@Mativve
Created January 15, 2020 09:14
Show Gist options
  • Save Mativve/8c65eeb29a36ebb70e5e9b02bc5d5b9a to your computer and use it in GitHub Desktop.
Save Mativve/8c65eeb29a36ebb70e5e9b02bc5d5b9a to your computer and use it in GitHub Desktop.
Wordpress Watermark system (use Regenerate Thumbnail after apply)
<?php
//
// Source: https://wordpress.org/support/article/debugging-in-wordpress/
//
function register_watermarked_size() {
add_theme_support( 'post-thumbnails' );
add_image_size( 'watermarked', 550, 550, true );
}
add_action( 'init', 'register_watermarked_size' );
function save_watermarked_image( $image_resource, $original_image_path ) {
$image_data = pathinfo( $original_image_path );
$new_filename = $image_data['filename'] . '-watermarked.' . $image_data['extension'];
$watermarked_image_path = str_replace($image_data['basename'], $new_filename, $original_image_path);
if ( ! $image_resource->writeImage( $watermarked_image_path ) )
return $image_data['basename'];
unlink( $original_image_path );
return $new_filename;
}
function watermark_image( $filename, $upload_dir ) {
$original_image_path = trailingslashit( $upload_dir['path'] ) . $filename;
$image_resource = new Imagick( $original_image_path );
// $image_resource->blurImage( 20, 10 );
$watermark_resource = new Imagick( URL_ASSETS . '/img/waterh.png' );
$watermark_resource->scaleImage(300, 300, true);
// $image_resource->compositeImage( $watermark_resource, Imagick::COMPOSITE_DEFAULT, 100, 250 );
$image_resource = $image_resource->textureImage($watermark_resource);
return save_watermarked_image( $image_resource, $original_image_path );
}
function generate_watermarked_image( $meta ) {
$time = substr( $meta['file'], 0, 7); // Extract the date in form "2015/04"
$upload_dir = wp_upload_dir( $time );
$filename = $meta['sizes']['watermarked']['file'];
$meta['sizes']['watermarked']['file'] = watermark_image( $filename, $upload_dir );
return $meta;
}
add_filter( 'wp_generate_attachment_metadata', 'generate_watermarked_image' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment