Intersept image upload and generate retina image from source
My goal is to make a retina and non-retina image when user uploads a photo. This is doable like so:
add_action('init', function() {
// Get the original image sizes and duplicate
$thumb_w = get_option('thumbnail_size_w') * 2;
$thumb_h = get_option('thumbnail_size_h') * 2;
$thumb_crop = get_option('thumbnail_crop');
$medium_w = get_option('medium_size_w') * 2;
$medium_h = get_option('medium_size_h') * 2;
$large_w = get_option('large_size_w') * 2;
$large_h = get_option('large_size_h') * 2;
// Register the actual sizes
add_image_size('thumbnail-retina', $thumb_w, $thumb_h, $thumb_crop);
add_image_size('medium-retina', $medium_w, $medium_h);
add_image_size('large-retina', $large_w, $large_h);
});
This is good, but the most optimal would be to chop half the full image, then use the original as the retina and the new as non-retina.
Here's my rationale on it:
- Intercept the image upload process with a hook,
add_attachment
- Measure the img and chop half with
wp_get_image_editor
- Suffix it with "1x"
- Save the new image
What I have so far (this works, but it's a bit faulty):
add_filter('add_attachment', function ($attachment_id) {
$src = get_attached_file($attachment_id);
if (!$src) {
return;
}
$img_info = pathinfo($src);
$image_editor = wp_get_image_editor($src);
// Get image sizes
$size = $image_editor-get_size($src);
$width = $size['width'];
$height = $size['height'];
// Chop the image in half and save
$image_editor-resize($width / 2, $height / 2, false);
$image_editor-save("{$img_info['dirname']}/{$img_info['filename']}-1x.{$img_info['extension']}");
return $attachment_id;
}, 10, 2);
How does that look to you, am I doing it right?
The fault is: WordPress doesn't know anything about the new 1x
image, so when the image is deleted, the 1x
copy stays behind. Any ideas how to approach that?
Here's a similar post, but it doesn't really deal with the full image.
Topic retina media-library images Wordpress
Category Web