Home » Magento, Magento 223 June 2016

Magento 2: Get Height Width of Image

This article shows how get height and width of the media images in Magento 2.

In this example, we will load product by id or sku and then fetch and display height and width of product small image.

To load the product, we will be using Magento 2’s Service Layer for this task. Use of Service Layer is highly encouraged by Magento.

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\ProductRepository class in the constructor of my module’s block class.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php

Now, we load the product by id and sku in template file. And then print the height and width of the product image. I have printed the height and width of product_small_image. Similarly, we can print the height and width value of product_base_image, product_thumbnail_image, and so on.

The height and width for different media images to be displayed in frontend can be adjusted from your frontend template’s view layout xml file. The default fromtend template for Magento 2 is LUMA. So, the view layout xml for this template is present in YOUR_MAGENTO_ROOT/vendor/magento/theme-frontend-luma/etc/view.xml.

Here is a sample content of view.xml file where media images’ height and width are defined:

Hope this helps. Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed