Last active
October 27, 2023 13:53
-
-
Save neverything/06ccf157ef94e25e0be5550ce948a208 to your computer and use it in GitHub Desktop.
WordPress: Strip image metadata on upload to the media library using Imagick. Learn more https://silvanhagen.com/strip-image-meta-data-wordpress/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'wp_handle_upload', 'yourprefix_strip_metadata_from_images_on_upload' ); | |
function yourprefix_strip_metadata_from_images_on_upload( array $upload ): array { | |
if ( ! in_array( $upload['type'], array( 'image/jpeg', 'image/png', 'image/gif' ), true ) ) { | |
return $upload; | |
} | |
try { | |
yourprefix_strip_metadata_from_image( $upload['file'] ); | |
} catch ( \ImagickException $e ) { | |
// Do nothing. | |
} | |
return $upload; | |
} | |
function yourprefix_strip_metadata_from_image( string $file, ?string $output = null ) { | |
$image = new \Imagick( $file ); | |
// Check if we have an ICC profile, so we can restore it later. | |
$profile = null; | |
try { | |
$profile = $image->getImageProfile( 'icc' ); | |
} catch ( \ImagickException $exception ) { | |
// Raises an exception if no profile is found. | |
} | |
// Strip all image metadata. | |
$image->stripImage(); | |
// Restore the ICC profile if we have one. | |
if ( ! empty( $profile ) ) { | |
$image->setImageProfile( 'icc', $profile ); | |
} | |
if ( empty( $output ) ) { | |
$output = $file; | |
} | |
$image->writeImage( $output ); | |
$image->clear(); | |
$image->destroy(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment