Angular Directive – Setting image height and width without changing the image aspect ratio

In case if you are showing an image in an web application and images are random and dynamic in nature with varying sizes, then we usually hit in to a challenge where we want to display these images in fix width and height. So quickest thing that you would do is set height and width of image to desired height and width, but this is going to cause your image to be rendered in distorted manner. Image’s aspect ratio is going to go for toss. So instead of setting image height and width set the max width and height of the image.

As an example have created a sample angular directive which does that.

In angular template below is image tag with custom attributes

<img src="" image-resizing 
       image-Height="200px" image-Width="200px" />

Image which gets sent is of the size Height:240 and Width:320.

But image size is changed based on parameter which are passed image-height and image-height which are part of directive scope elements. Below is the code snippet for the directive

var imageResizing = angular.module('imageResizingModule', [])
// Image Resizing...
imageResizing.directive('imageResizing', [function () {
    return {
        restrict: 'A',
        scope: {
            imageHeight: '@',
            imageWidth: '@',
        link: function (scope, element, attrs) {
            element.bind('load', function () {
                var imageElement = element[0];
                console.log("Image Height:" + imageElement.height);
                console.log("Image Width:" + imageElement.width);
                var imageSizeCSSClass = {};
                imageSizeCSSClass["max-width"] = scope.imageWidth;
                imageSizeCSSClass["max-height"] = scope.imageHeight;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s