Created
November 3, 2020 11:09
-
-
Save GaryJones/06ccee417b94f15cb9176871547a1157 to your computer and use it in GitHub Desktop.
WordPress: Strip image meta data (except ICC profile) on file upload
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', 'foo_strip_metadata_from_images_on_upload' ); | |
/** | |
* Overwrite the uploaded image with a new version that has no metadata. | |
* | |
* @param array $upload Array containing: | |
* - file: The path to the image file. | |
* - url: The URL to the image. | |
* - type: The MIME type of the image. | |
* | |
* @return array Unmodified $upload array. | |
*/ | |
function foo_strip_metadata_from_images_on_upload( array $upload ): array { | |
// Return if the file is not an image. | |
if ( ! in_array( $upload['type'], [ 'image/jpeg', 'image/png', 'image/gif' ], true ) ) { | |
return $upload; | |
} | |
try { | |
foo_strip_metadata_from_image( $upload['file'] ); | |
} catch ( \GmagickException $e ) { /* nothing */ } | |
return $upload; | |
} | |
/** | |
* Strip metadata from an image file, but keep the ICC color profile data | |
* | |
* @param string $file Path to the image file. | |
* @param string|null $output Path to write the image to, leave null to overwrite the original. | |
* | |
* @return bool | |
*/ | |
function foo_strip_metadata_from_image( string $file, ?string $output = null ):bool { | |
$image = new \Gmagick( $file ); | |
// Check if we have an ICC profile, so we can restore it later | |
try { | |
$profile = $image->getimageprofile( 'icc' ); | |
} catch ( \GmagickException $exception ) { /* it 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 ); | |
} | |
// Replace the uploaded image with the stripped down version | |
if ( empty( $output ) ) { | |
$output = $file; | |
} | |
$image->writeimage( $output, true ); | |
$image->destroy(); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment