Search code examples
symfonysonatasonata-media-bundle

SonataMediaBundle get image width and height


I have an image in my template:

{% media picture.media, 'reference' %}

How can I get width and height of that image?


Solution

  • I dunno which answer you are looking for, since this question can be answered in different ways, so I'm trying to answer all of those ways.


    Getters on Media objects

    If you're just interested in getting the values from your media object, you can just simply call:

    {{ picture.media.width }}
    {{ picture.media.height }}
    

    Media rendering

    Sonata's twig-extension for rendering medias will automatically add width/height to your html.

    <!-- twig -->
    {% media picture.media, 'reference' %}
    
    <!-- renders -->
    <img src="path/to/media" alt="media" width="256" height="256" />
    

    Media Contexts

    It will always render the full media file, regardless of it's size. Doing the same with the thumbnail-tag provided by SonataMedia lets you define different sizes which than will be rendered in size you would have configured. Take a look at introduction to SonataMedia's context configuration.

    # app/config/config.yml
    
    sonata_media:
        contexts:
            news:
                formats:
                    small: { width: 100 , quality: 70}
                    big:   { width: 500 , quality: 70}
    
    <!-- twig -->
    {% thumbnail picture.media, 'small' %}
    
    <!-- renders (note, height will be recalculated automatically by it's ratio) -->
    <img src="path/to/media" alt="media" width="100" height="100" />