wp-media / imagify-plugin

Speed up your website with lighter images without losing quality.
https://imagify.io
69 stars 24 forks source link

Regenerate WebP when using Crop-Thumbnails plugin #616

Open markonikolic985 opened 2 years ago

markonikolic985 commented 2 years ago

Is your feature request related to a problem? Please describe. When using Crop-Thumbnails Plugin to crop images, WebP version is not regenerated by Imagify. This is a problem as users would have to regenerate it (whether by reoptimizing image or deleting WebP manually and then regenerating it)

Describe the solution you'd like It would be great if we could hook into crop_thumbnails_after_crop action and trigger image re-optimization or (ideally) only WebP regeneration.

Describe alternatives you've considered Tried to find a way to do it now but it's a bit more complex. Based on our Slack conversation, we came up with opening this Feature Request.

Additional context Here is a ticket related to the problem.

zetoun17fr commented 2 years ago

Hello you can directly crop the WebP version, add the code below in your themes's functions.php

add_action('crop_thumbnails_after_crop', 'crop_webp', 10,5);
function crop_webp($input, $croppedSize, $temporaryCopyFile, $currentFilePath, $resultWpCropImage) {
    // full size WebP image filename
    $source_webp=get_attached_file( $input->sourceImageId ).'.webp';
    if(!file_exists($source_webp)) {
        return;
    }
    // cropped WebP image filename
    $dest_webp_crop=$currentFilePath.'.webp';
    @unlink($dest_webp_crop);

    // do crop the WebP image
    wp_crop_image(               // * @return string|WP_Error|false New filepath on success, WP_Error or false on failure.
      $source_webp,              // * @param string|int $src The source file or Attachment ID.
      $input->selection->x,             // * @param int $src_x The start x position to crop from.
      $input->selection->y,             // * @param int $src_y The start y position to crop from.
      $input->selection->x2 - $input->selection->x, // * @param int $src_w The width to crop.
      $input->selection->y2 - $input->selection->y, // * @param int $src_h The height to crop.
      $croppedSize['width'],              // * @param int $dst_w The destination width.
      $croppedSize['height'],             // * @param int $dst_h The destination height.
      false,                      // * @param int $src_abs Optional. If the source crop points are absolute.
      $dest_webp_crop // * @param string $dst_file Optional. The destination file to write to.
    );
}