Home » Magento

Magento: Resize Image

23 November 2009 5,443 views 20 Comments Popularity: 49% Share/Bookmark

You can resize image with fixed height and variable width. Or, you can resize with fixed width and variable height. Following code shows how you do it in Magento.

Fixed width of 600px

<?php echo $this->helper('catalog/image')->init($_product, 'image')
->constrainOnly(TRUE)
->keepAspectRatio(TRUE)
->keepFrame(FALSE)
->resize(600,null)
?>

Fixed height of 600px

<?php echo $this->helper('catalog/image')->init($_product, 'image')
->constrainOnly(TRUE)
->keepAspectRatio(TRUE)
->keepFrame(FALSE)
->resize(null,600)
?>

The following code will resize image proportionally and not let the image be greater than height and width specified.

<?php echo $this->helper('catalog/image')->init($_product, 'image')
->constrainOnly(TRUE)
->keepAspectRatio(TRUE)
->keepFrame(FALSE)
->resize(400,400)
?>

Description of the functions used above:-

constrainOnly(bool $flag)
Guarantee, that image picture will not be bigger, than it was. Applicable before calling resize() It is false by default

keepAspectRatio(bool $flag)
Guarantee, that image picture width/height will not be distorted. Applicable before calling resize() It is true by default.

keepFrame(bool $flag)
Guarantee, that image will have dimensions, set in $width/$height. Applicable before calling resize() Not applicable, if keepAspectRatio(false).

You can resize image with Varien_Image class as well. This is most suitable when you are resizing image that is not related with catalog product.

// actual path of image
$imageUrl = Mage::getBaseDir('media').DS."myimage".DS.$post->getThumbnail();

// path of the resized image to be saved
// here, the resized image is saved in media/resized folder
$imageResized = Mage::getBaseDir('media').DS."myimage".DS."resized".DS.$post->getThumbnail();

// resize image only if the image file exists and the resized image file doesn't exist
// the image is resized proportionally with the width/height 135px
if (!file_exists($imageResized)&&file_exists($_imageUrl)) :
	$imageObj = new Varien_Image($_imageUrl);
	$imageObj->constrainOnly(TRUE);
	$imageObj->keepAspectRatio(TRUE);
	$imageObj->keepFrame(FALSE);
	$imageObj->resize(135, 135);
	$imageObj->save($imageResized);
endif;

You can use the resized image now as:

<img src="<?php echo Mage::getBaseUrl('media')."myimage/resized/".$post->getThumbnail() ?>" />

Another Scenario

Suppose, you have an image link. Now, you want to resize it. The image might be from any place. In this example, I am supposing the image link to be like http://localhost/magento/media/catalog/category/test_image.jpg

Now, I have to resize it. To do so, I will create a directory called resized inside media/catalog/category. And, I will save the resized file into the newly created resized directory.


// my sample image

$imageUrl = "http://localhost/magento/media/catalog/category/test_image.jpg";

// create folder
 if(!file_exists("./media/catalog/category/resized"))     mkdir("./media/catalog/category/resized",0777);

 // get image name
 $imageName = substr(strrchr($imageUrl,"/"),1);

 // resized image path (media/catalog/category/resized/IMAGE_NAME)
 $imageResized = Mage::getBaseDir('media').DS."catalog".DS."category".DS."resized".DS.$imageName;

 // changing image url into direct path
 $dirImg = Mage::getBaseDir().str_replace("/",DS,strstr($imageUrl,'/media'));

 // if resized image doesn't exist, save the resized image to the resized directory
 if (!file_exists($imageResized)&&file_exists($dirImg)) :
 $imageObj = new Varien_Image($dirImg);
 $imageObj->constrainOnly(TRUE);
 $imageObj->keepAspectRatio(TRUE);
 $imageObj->keepFrame(FALSE);
 $imageObj->resize(120, 120);
 $imageObj->save($imageResized);
 endif;

 $newImageUrl = Mage::getBaseUrl('media')."catalog/category/resized/".$imageName;

Displaying newly created resized image.

<img src="<?php echo Mage::getBaseUrl('media')."catalog/category/resized/".$newImageUrl ?>" />

You can check other function for Varien_Image at
http://docs.magentocommerce.com/Varien/elementindex_Varien_Image.html

From Mukesh Chapagain's Blog | Post Magento: Resize Image

Related posts:

  1. Magento: Custom function to resize image proportionally
  2. Magento: Get width height of image using Varien_Image class
  3. Magento: Create Watermark Image
  4. Magento: Get height and width of Image
  5. Magento: Crop image

20 Comments »

  • Jacek said:

    This works well if you resize =< max. image space or switch off the zoom script, but have problem keeping an image center in the image space.

  • admin said:

    You can align the image at center from phtml file (template/catalog/product/media.phtml).

  • george said:

    Hello could you please tell me in wich file i have to put the code you gave above

  • Mukesh said:

    @george: you can keep it in any phtml or php file from where you want to display the resized image.

  • Vrnet said:

    Hi – this post is a great help, thanks Mukesh !
    As you guess, I’m here with a problem :)

    I’ve taken your second snippet to resize any image on the fly for displaying (without saving it) on custom modules. The source image is located at the root of the /media directory and when I print_r($imageObj) for testing, the object seems to be correct (resising is set to 120,119) :


    ...[_fileName:protected] => /vol/home/cotenat/www/media/image.jpg [_fileMimeType:protected] => image/jpeg [_fileSrcName:protected] => image.jpg [_fileSrcPath:protected] => /vol/home/cotenat/www/media [_imageHandler:protected] => Resource id #408 [_imageSrcWidth:protected] => 120 [_imageSrcHeight:protected] => 119 ...

    But I am stuck when it comes to displaying the image.

    As stated in the Varien_Image class, I’ve tried <img src="display() ;?>"/> but it returns those strange characters like “�x@9�?

  • Vrnet said:

    Sorry for double posting bu I guess the rest of my message has been truncated becasue of the use of strange keys. So, to end it : I would be so grateful if you could give me a clue on how to render the image correctly rather than with E.T. characters :)

    Thanks again !
    Hervé

  • Stephanie said:

    I am a newbie. My homepage is a 3 column layout. I want to resize the homepage product image so it does not overlap the right column. I am not a programmer. Where can I resize it?

    Pls help.

    Regards
    Stephanie

  • jazkat said:

    Thanks Mukesh!!!
    you saved my day!!

  • Ryodin said:

    Thank you for this, es muy helpful!

  • Krishna said:

    hello guys i need to know how we can resize category image in front-end of magento 1.4.0.1
    if any one knows plz tell me

  • min said:

    I love you! Your last example worked beautifully to resize my categories into thumbnail size for my grid! Thank you much.

  • min said:

    Oops, meant to mention that in that last example, to display, I had to change it to just say:
    <img src="" />
    The display code you have above gave an error, but when I looked at the source, I saw that it was just because it was trying to echo the path twice. Thanks again. You saved me a lot of time and frustration.

  • Vijay Vishwakarma said:

    Hi,

    I am getting one error when using this custom image resize in my custom module. I am I need to call the reference but not sure how to do that in magento.

    Fatal error: Call to a member function getThumbnail() on a non-object in C:\Inetpub\vhosts\domain.com\subdomains\demo\httpdocs\app\design\frontend\default\default\template\module\module_details.phtml on line 117

    // actual path of image
    $imageUrl = Mage::getBaseDir(‘media’).DS.”module”.DS.$post->getThumbnail();

    // path of the resized image to be saved
    // here, the resized image is saved in media/resized folder
    $imageResized = Mage::getBaseDir(‘media’).DS.”module”.DS.”resized”.DS.$post->getThumbnail();

    // resize image only if the image file exists and the resized image file doesn’t exist
    // the image is resized proportionally with the width/height 135px
    if (!file_exists($imageResized)&&file_exists($_imageUrl)) :
    $imageObj = new Varien_Image($_imageUrl);
    $imageObj->constrainOnly(TRUE);
    $imageObj->keepAspectRatio(TRUE);
    $imageObj->keepFrame(FALSE);
    $imageObj->resize(135, 135);
    $imageObj->save($imageResized);
    endif;

    How to set the reference in magento ?

    Sorry I am asp.net programmer :)

  • Vijay Vishwakarma said:

    Hi,

    the code // my sample image

    is creating the resized folder for me but is not saving the image. Can you help ?

  • Vijay Vishwakarma said:

    I got this working, thanks for the code.

  • Vijay Vishwakarma said:

    New Problem.

    How I can use this image resize function in a loop ?

    I am getting this error – Warning: getimagesize(C:\Inetpub\vhosts\domain.com\subdomains\demo\httpdocs) [function.getimagesize]: failed to open stream: Permission denied in C:\Inetpub\vhosts\domain.com\subdomains\demo\httpdocs\lib\Varien\Image\Adapter\Abstract.php on line 84

    I have all the necessary permissions.

    Any idea ?

  • Chuck said:

    I am fairly new to Magento after suffering thru osCommerce hell for several years.

    So far Magento is everything I want in a CMS system and more. My ONLY complaint is when it decides to resize all my carefully crafted images to some mysterious sizing dimension buried deep in the code somewhere in Magento’s backend.

    How do I prevent his from happening or at least define the parameters to where the images are resized to my standards (usually 600×600)?

  • Deepak said:

    Hello Mukesh,
    I want to increst size of image uploaded,not image resizing.My requirement to upload 500X500 images so i want to disable to image resizing.Is it possible in magento on some way to do it ,i am serching too long but sill not get any solution yet…..

    Please Help Me

  • trish said:

    Dude, I love you!
    Thanks, this is perfect! =)

  • Jeff said:

    Fantastic code snippet thanks! Really helped me out when developing a magento theme from scratch for the first time!

    + Bookmarked

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.