46 lines
1.3 KiB
PHP
46 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
use Spatie\Image\Enums\ImageDriver;
|
|
use Spatie\Image\Image;
|
|
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
|
use Throwable;
|
|
|
|
/**
|
|
* Re-encodes an uploaded original photo without its metadata (EXIF/XMP: GPS position, camera, owner).
|
|
* The orientation is applied first, so the photo keeps its correct rotation. Failures never block an upload.
|
|
*/
|
|
class StripImageMetadata
|
|
{
|
|
private const TYPES = ['image/jpeg', 'image/png', 'image/webp'];
|
|
|
|
public static function strip(Media $media, bool $force = false): bool
|
|
{
|
|
if (! in_array($media->mime_type, self::TYPES, true) || ($media->getCustomProperty('metadata_stripped') && ! $force)) {
|
|
return false;
|
|
}
|
|
|
|
$path = $media->getPath();
|
|
if (! is_file($path)) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
// GD on purpose: Imagick (default when installed, e.g. on Strato) keeps the EXIF data when saving.
|
|
Image::useImageDriver(ImageDriver::Gd)->loadFile($path)->quality(90)->save($path);
|
|
} catch (Throwable $exception) {
|
|
report($exception);
|
|
|
|
return false;
|
|
}
|
|
|
|
clearstatcache(true, $path);
|
|
$media->size = (int) filesize($path);
|
|
$media->setCustomProperty('metadata_stripped', true);
|
|
$media->saveQuietly();
|
|
|
|
return true;
|
|
}
|
|
}
|