Skip to content

Instantly share code, notes, and snippets.

@joshuafredrickson
Created September 7, 2023 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuafredrickson/1ebaac426bb4ad81ee0e9e116911775f to your computer and use it in GitHub Desktop.
Save joshuafredrickson/1ebaac426bb4ad81ee0e9e116911775f to your computer and use it in GitHub Desktop.
WordPress MU Plugin: Strip EXIF data from images
<?php
/**
* Remove EXIF data from .jpg when uploaded.
*/
use Imagick;
/**
* Strip EXIF using Imagick, fallback to gd
*
* @param array $upload
* @return array
*/
add_action('wp_handle_upload', function ($upload) {
if (! is_array($upload)) {
return $upload;
}
if ($upload['type'] !== 'image/jpeg' && $upload['type'] !== 'image/jpg') {
return $upload;
}
$filename = $upload['file'];
// Attempt Imagick first; fallback to gd
if (class_exists('Imagick')) {
$im = new Imagick($filename);
if (! $im->valid()) {
return $upload;
}
try {
$im->stripImage();
$im->writeImage($filename);
$im->clear();
$im->destroy();
} catch (\Exception $e) {
error_log('Unable to strip EXIF data: ' . $filename);
}
} elseif (function_exists('imagecreatefromjpeg')) {
$image = imagecreatefromjpeg($filename);
if ($image) {
imagejpeg($image, $filename, '100');
imagedestroy($image);
}
}
return $upload;
});
@bdenie
Copy link

bdenie commented Jan 12, 2024

What dependency is Imagick used ?

@joshuafredrickson
Copy link
Author

@bdenie I generally prefer Imagick to GD as it tends to create higher-quality images. YMMV though.

reference: https://support.pagely.com/hc/en-us/articles/115000052451-Imagick-vs-GD-in-WordPress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment