The use of header()
function produce output in the middle of the request and crash it.
To modify uploaded image you should use wp_handle_upload
filter instead of save_post
action. Also, ideally, you should use WP_Image_Editor
class, which will use the best image manipulation library available in the server (GD, Imagemagick) and triggers several filters and actions that can be used by another plugins:
add_filter( 'wp_handle_upload', 'cyb_handle_upload_callback' );
function cyb_handle_upload_callback( $data ) {
// get instance of WP_Image_Editor class
$image = wp_get_image_editor( $data['file'] );
if( ! is_wp_error( $image ) ) {
// Manipulate your image here
$stamp = imagecreatefrompng( 'path/to/stamp.png' );
$margin_right = 10;
$margeing_bottom = 10;
$sx = imagesx( $stamp );
$sy = imagesy( $stamp );
imagecopy(
$data['file'],
$stamp,
imagesx( $data['file'] ) - $sx - $margin_right,
imagesy( $data['file'] ) - $sy - $margin_bottom,
0,
0,
imagesx( $stamp ),
imagesy( $stamp )
);
// Save the modified image
$image->save();
}
return $data;
}
If we follow this implementation extending WP_Editor_Image
class:
add_filter( 'wp_handle_upload', 'cyb_handle_upload_callback' );
function cyb_handle_upload_callback( $data ) {
$image = wp_get_image_editor( $data['file'] );
if ( ! is_wp_error( $image ) && is_callable( [ $image, 'stamp_watermark' ] ) ) {
$stamp = imagecreatefrompng( '/path/to/stamp.png' );
$success = $editor->stamp_watermark( $stamp );
if ( ! is_wp_error( $success ) ) {
$image->save();
}
}
return $data;
}