0

I am generating avatars from an image file upload. When running the function, WordPress does create the first image image-32x32.gif but fails on the remainder of the loop. I suspect it's due to concurrency.

public function process_uploaded_file($file)
  {
    $editor = wp_get_image_editor($file);
    $sizes = [32, 64, 128, 256, 512];
    foreach ($sizes as $size) {
      $result = $editor->resize($size, $size, true);  //LINE 217
      if (!is_wp_error($result)) {
        $editor->save($editor->generate_filename());
      }
    }
  }

What am I doing wrong?

Fatal error: Uncaught Error: Call to undefined method WP_Error::resize() in /Users/.../class-gf-avatar-field.php on line 217
( ! ) Error: Call to undefined method WP_Error::resize() in /.../class-gf-avatar-field.php on line 217

Update 09-11-2019 I added a few checks, and create a new editor each time.

foreach ($sizes as $size) {
    $editor = wp_get_image_editor($file);
    if (!is_wp_error($editor)) {
      $result = $editor->resize($size, $size, true);
    if (!is_wp_error($result)) {
      $editor->save($editor->generate_filename());
    }
  }
}
1
  • Does $editor actually change throughout the loop? (Try a var_dump() of it to error log) Given the error message, I would presume your $editor = wp_get_image_editor(.. line is already returning a WP_Error.
    – kero
    Commented Nov 7, 2019 at 12:19

1 Answer 1

0

wp_get_image_editor can return a WP_Error object, which appears to be what's happening in the code. The code never checks for this and tries to resize an image, thinking it's calling resize on an image editing object.

You need to make 2 adjustments:

  • check if $editor is a WP_Error object
  • add code to print out the error objects message so you know what the error is

But finally, there's another bug you've yet to encounter which will come next due to how you're resizing. Consider the following:

  • we load file.png into memory, it's 512x512
  • we now resize our image in memory from 512 to 32
  • we save the 32x32 image
  • we now resize our 32x32 image in memory to 64x64
  • we save the 64x64 image
  • the 64 image in memory gets resized to 128
  • etc..

All your resized images will be upscaled versions of the 32x32, not the original.

Also, consider that the resize might return neither true or an error object, but false

1
  • 1
    Thank you, this makes sense. I will alter the loop and update this question sometime today.
    – Simon
    Commented Nov 8, 2019 at 0:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.