25

I have ImageField in my model and I'm able to display the image in a template. However, how do I retrieve the image's height and width?

bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
olegmil
  • 347
  • 1
  • 4
  • 10
  • Here is one of the solution by @Nifled, hope that helps - [ImageField image_width and image_height auto fill for existing database?](https://stackoverflow.com/questions/47064339/imagefield-image-width-and-image-height-auto-fill-for-existing-database) – Radek Jul 09 '19 at 19:49

2 Answers2

39

See the documentation for ImageField.

In addition to the special attributes that are available for FileField, an ImageField also has height and width attributes.

So just do the following:

<img src="{{ image.url }}" width="{{ image.width }}" height="{{ image.height }}"/>
Ryan Allen
  • 5,414
  • 4
  • 26
  • 33
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
  • hmmm.. it doesn't work on my end. `{% with post.postimage_set.all as image %}` `{{ alt }}` `{% endwith %}` – bonbon.langes Oct 03 '13 at 11:57
  • @bonbon.langes responding 10 years later, but your example wouldn't work because you are trying to get width and height from a queryset, not a single image object. – Jarad Jan 31 '23 at 03:07
8

In my case, for the width and height fields to work, I need to set the width_field and height_field of the ImageField

E.g.

class Product(models.Model):
    image = models.ImageField(width_field='image_width', height_field='image_height')
    image_width = models.IntegerField()
    image_height = models.IntegerField()
Ron
  • 7,588
  • 11
  • 38
  • 42