开发者

How to make a picture specific width and height without losing scale?

How to make a picture specific width and height without losing scale?

I have asp.net c# application where I'm using a handler to manipulate with the different size of images. For example if I need the image with width 200 or 300 etc..

but If I need to make image size with width 300 and height 300 and keep proportion how to mak开发者_运维问答e it? also if it's any way to find faces on images?

Is there any free component or specific ways how to accomplish it?


If you are controlling both the height and the width of the image, you can't keep the proportions, unless they happen to match the existing image proportions.

A work around will be to resize the image so the largest dimension fits into your selected size and add a background to the smallest dimension till it fits.


jQuery can get you close. Take a look at the code below. Also, here's a working Fiddle.

$(document).ready(function() {
    $('.story-small img').each(function() {
        var maxWidth = 100; // Max width for the image
        var maxHeight = 100;    // Max height for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height

        // Check if the current width is larger than the max
        if(width > maxWidth){
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }

        // Check if current height is larger than max
        if(height > maxHeight){
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }
    });
});

Code taken from: http://thejudens.com/eric/2009/07/jquery-image-resize/.

NOTE: This may not re-size the image exactly to your specified pixels. It will, however, get as close as possible while maintaining the aspect ratio.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜