Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

New in Symfony 3.1: Strict Image Validation

Contributed by
Konstantin Myakshin in #17458.

The Image constraint is one of the most powerful constraints defined by the Validator component. It allows you to validate the max/min height and width, the max/min ratio of images, whether the format should be portrait or landscape, etc.

However, it lacked a very important check: validate that the image is not corrupted and therefore, that it will be displayed correctly in your application. That's why Symfony 3.1 includes a new detectCorrupted configuration option and its corresponding corruptedMessage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use Symfony\Component\Validator\Constraints as Assert;

class Product
{
    /**
     * @Assert\Image(
     *     detectCorrupted = true,
     *     corruptedMessage = "Product photo is corrupted. Upload it again."
     * )
     */
    protected $photo;
}

Internally this feature uses PHP's imagecreatefromstring() function to check that the provided contents can create a valid image. Therefore, before using this new validation, make sure that the GD extension is installed and enabled in your PHP engine.

As you can imagine, this option makes the validation be slower and consume more memory, but that's a reasonable trade-off when some images are critical for your application.

Comments

Great!

Will there be a provider using ImageMagick? I think it could be more powerful actually.
Espectacular!!
Wow, this is handy. Thanks Konstantin :) Cheers!!!

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.