Tuesday 7 May 2013

Customize Magento’s Image Resize Functionality

Untitled Document

Need to remove the white border around your images? Don't want everything to be square? Here is how to customize the ->resize functionality in Magento. Here is what the default image resize code looks like:

<?php echo $this->helper('catalog/image')->init($_product, 'image')->resize(350) ?>

The problem is this will always give you a 350 x 350 pixel square. If your image is rectangular, you will get a white frame around it to make it square. The resize() command can be quickly and easily customized to work better with rectangular images.

->constrainOnly(true) This will not resize an image that is smaller than the dimensions inside the resize() part.

->keepAspectRatio(true) This will not distort the height/width of the image.

->keepFrame(false) This will not put a white frame around your image.

Here is what your image code would look like with all these set:

<?php echo $this->helper('catalog/image')->init($_product, 'image')->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->resize(350, null) ?>

This would resize your images to a max 350 width and constrain the height. If your image is taller than it is wide, you will end up with a nicely resized vertical image.

Here are the various places that images are used:

/app/design/frontend/default/yourtheme/catalog/product/view/media.phtml  (displays the image on your product view page)
/app/design/frontend/default/yourtheme/catalog/product/list.phtml  (displays the image on category view)

This has helped us out many times. Let us know in the comments if you use it!

No comments:

Post a Comment