Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Reference
  4. Constraints
  5. Image
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Basic Usage
  • Options
    • mimeTypes
    • mimeTypesMessage
    • minWidth
    • maxWidth
    • minHeight
    • maxHeight
    • minPixels
    • maxPixels
    • maxRatio
    • minRatio
    • allowSquare
    • allowLandscape
    • allowPortrait
    • detectCorrupted
    • sizeNotDetectedMessage
    • maxWidthMessage
    • minWidthMessage
    • maxHeightMessage
    • minHeightMessage
    • maxPixelsMessage
    • minPixelsMessage
    • maxRatioMessage
    • minRatioMessage
    • allowSquareMessage
    • allowLandscapeMessage
    • allowPortraitMessage
    • corruptedMessage
    • groups

Image

Edit this page

Warning: You are browsing the documentation for Symfony 3.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

Image

The Image constraint works exactly like the File constraint, except that its mimeTypes and mimeTypesMessage options are automatically setup to work for image files specifically.

Additionally it has options so you can validate against the width and height of the image.

See the File constraint for the bulk of the documentation on this constraint.

Applies to property or method
Options
  • mimeTypes
  • minWidth
  • maxWidth
  • maxHeight
  • minHeight
  • maxRatio
  • minRatio
  • allowSquare
  • allowLandscape
  • allowPortrait
  • detectCorrupted
  • mimeTypesMessage
  • sizeNotDetectedMessage
  • maxWidthMessage
  • minWidthMessage
  • maxHeightMessage
  • minHeightMessage
  • maxRatioMessage
  • minRatioMessage
  • allowSquareMessage
  • allowLandscapeMessage
  • allowPortraitMessage
  • corruptedMessage
  • See File for inherited options
  • groups
Class Image
Validator ImageValidator

Basic Usage

This constraint is most commonly used on a property that will be rendered in a form as a FileType field. For example, suppose you're creating an author form where you can upload a "headshot" image for the author. In your form, the headshot property would be a file type. The Author class might look as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

use Symfony\Component\HttpFoundation\File\File;

class Author
{
    protected $headshot;

    public function setHeadshot(File $file = null)
    {
        $this->headshot = $file;
    }

    public function getHeadshot()
    {
        return $this->headshot;
    }
}

To guarantee that the headshot File object is a valid image and that it is between a certain size, add the following:

  • Annotations
  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\Image(
     *     minWidth = 200,
     *     maxWidth = 400,
     *     minHeight = 200,
     *     maxHeight = 400
     * )
     */
    protected $headshot;
}
1
2
3
4
5
6
7
8
9
# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\Author:
    properties:
        headshot:
            - Image:
                minWidth: 200
                maxWidth: 400
                minHeight: 200
                maxHeight: 400
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- src/AppBundle/Resources/config/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="AppBundle\Entity\Author">
        <property name="headshot">
            <constraint name="Image">
                <option name="minWidth">200</option>
                <option name="maxWidth">400</option>
                <option name="minHeight">200</option>
                <option name="maxHeight">400</option>
            </constraint>
        </property>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('headshot', new Assert\Image([
            'minWidth' => 200,
            'maxWidth' => 400,
            'minHeight' => 200,
            'maxHeight' => 400,
        ]));
    }
}

The headshot property is validated to guarantee that it is a real image and that it is between a certain width and height.

You may also want to guarantee the headshot image to be square. In this case you can disable portrait and landscape orientations as shown in the following code:

  • Annotations
  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\Image(
     *     allowLandscape = false,
     *     allowPortrait = false
     * )
     */
    protected $headshot;
}
1
2
3
4
5
6
7
# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\Author:
    properties:
        headshot:
            - Image:
                allowLandscape: false
                allowPortrait: false
1
2
3
4
5
6
7
8
9
<!-- src/AppBundle/Resources/config/validation.xml -->
<class name="AppBundle\Entity\Author">
    <property name="headshot">
        <constraint name="Image">
            <option name="allowLandscape">false</option>
            <option name="allowPortrait">false</option>
        </constraint>
    </property>
</class>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('headshot', new Assert\Image([
            'allowLandscape' => false,
            'allowPortrait' => false,
        ]));
    }
}

You can mix all the constraint options to create powerful validation rules.

Options

This constraint shares all of its options with the File constraint. It does, however, modify two of the default option values and add several other options.

mimeTypes

type: array or string default: image/*

You can find a list of existing image mime types on the IANA website.

mimeTypesMessage

type: string default: This file is not a valid image.

minWidth

type: integer

If set, the width of the image file must be greater than or equal to this value in pixels.

maxWidth

type: integer

If set, the width of the image file must be less than or equal to this value in pixels.

minHeight

type: integer

If set, the height of the image file must be greater than or equal to this value in pixels.

maxHeight

type: integer

If set, the height of the image file must be less than or equal to this value in pixels.

minPixels

3.4

The minPixels option has been introduced in Symfony 3.4.

type: integer

If set, the amount of pixels of the image file must be greater than or equal to this value.

maxPixels

3.4

The maxPixels option has been introduced in Symfony 3.4.

type: integer

If set, the amount of pixels of the image file must be less than or equal to this value.

maxRatio

type: float

If set, the aspect ratio (width / height) of the image file must be less than or equal to this value.

minRatio

type: float

If set, the aspect ratio (width / height) of the image file must be greater than or equal to this value.

allowSquare

type: Boolean default: true

If this option is false, the image cannot be a square. If you want to force a square image, then leave this option as its default true value and set allowLandscape and allowPortrait both to false.

allowLandscape

type: Boolean default: true

If this option is false, the image cannot be landscape oriented.

allowPortrait

type: Boolean default: true

If this option is false, the image cannot be portrait oriented.

detectCorrupted

type: boolean default: false

If this option is true, the image contents are validated to ensure that the image is not corrupted. This validation is done with PHP's imagecreatefromstring function, which requires the PHP GD extension to be enabled.

sizeNotDetectedMessage

type: string default: The size of the image could not be detected.

If the system is unable to determine the size of the image, this error will be displayed. This will only occur when at least one of the size constraint options has been set.

This message has no parameters.

maxWidthMessage

type: string default: The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.

The error message if the width of the image exceeds maxWidth.

You can use the following parameters in this message:

Parameter Description
{{ width }} The current (invalid) width
{{ max_width }} The maximum allowed width

minWidthMessage

type: string default: The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.

The error message if the width of the image is less than minWidth.

You can use the following parameters in this message:

Parameter Description
{{ width }} The current (invalid) width
{{ min_width }} The minimum required width

maxHeightMessage

type: string default: The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.

The error message if the height of the image exceeds maxHeight.

You can use the following parameters in this message:

Parameter Description
{{ height }} The current (invalid) height
{{ max_height }} The maximum allowed height

minHeightMessage

type: string default: The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.

The error message if the height of the image is less than minHeight.

You can use the following parameters in this message:

Parameter Description
{{ height }} The current (invalid) height
{{ min_height }} The minimum required height

maxPixelsMessage

3.4

The maxPixelsMessage option has been introduced in Symfony 3.4.

type: string default: The image has to many pixels ({{ pixels }} pixels). Maximum amount expected is {{ max_pixels }} pixels.

The error message if the amount of pixels of the image exceeds maxPixels.

You can use the following parameters in this message:

Parameter Description
{{ pixels }} The current amount of pixels
{{ max_pixels }} The maximum allowed amount of pixels
{{ height }} The current image height
{{ width }} The current image width

minPixelsMessage

3.4

The minPixelsMessage option has been introduced in Symfony 3.4.

type: string default: The image has too few pixels ({{ pixels }} pixels). Minimum amount expected is {{ min_pixels }} pixels.

The error message if the amount of pixels of the image is less than minPixels.

You can use the following parameters in this message:

Parameter Description
{{ pixels }} The current amount of pixels
{{ min_pixels }} The minimum required amount of pixels
{{ height }} The current image height
{{ width }} The current image width

maxRatioMessage

type: string default: The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}

The error message if the aspect ratio of the image exceeds maxRatio.

You can use the following parameters in this message:

Parameter Description
{{ ratio }} The current (invalid) ratio
{{ max_ratio }} The maximum allowed ratio

minRatioMessage

type: string default: The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}

The error message if the aspect ratio of the image is less than minRatio.

You can use the following parameters in this message:

Parameter Description
{{ ratio }} The current (invalid) ratio
{{ min_ratio }} The minimum required ratio

allowSquareMessage

type: string default: The image is square ({{ width }}x{{ height }}px). Square images are not allowed

The error message if the image is square and you set allowSquare to false.

You can use the following parameters in this message:

Parameter Description
{{ width }} The current width
{{ height }} The current height

allowLandscapeMessage

type: string default: The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed

The error message if the image is landscape oriented and you set allowLandscape to false.

You can use the following parameters in this message:

Parameter Description
{{ width }} The current width
{{ height }} The current height

allowPortraitMessage

type: string default: The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed

The error message if the image is portrait oriented and you set allowPortrait to false.

You can use the following parameters in this message:

Parameter Description
{{ width }} The current width
{{ height }} The current height

corruptedMessage

type: string default: The image file is corrupted.

The error message when the detectCorrupted option is enabled and the image is corrupted.

This message has no parameters.

groups

type: array | string

It defines the validation group or groups this constraint belongs to. Read more about validation groups.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Get your Sylius expertise recognized

    Get your Sylius expertise recognized

    Code consumes server resources. Blackfire tells you how

    Code consumes server resources. Blackfire tells you how

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Mouad ZIANI, a Symfony contributor

    Thanks Mouad ZIANI (@mouadziani) for being a Symfony contributor

    4 commits • 32 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia