如何在不丢失刻度的情况下制作特定宽度和高度的图片?

时间:2011-08-15 13:38:09

标签: c# jquery asp.net image-resizing

如何在不丢失比例的情况下制作特定宽度和高度的图片?

我有asp.net c#应用程序,我使用处理程序来处理不同大小的图像。例如,如果我需要宽度为200或300等的图像。

但如果我需要制作宽度为300且高度为300的图像尺寸并保持比例如何制作呢?如果有任何方法可以在图像上找到面孔吗?

是否有任何免费组件或具体方法如何实现它?

2 个答案:

答案 0 :(得分:2)

如果您同时控制图像的高度和宽度,则无法保持比例,除非它们恰好与现有图像比例相匹配。

解决方法是调整图像大小,使最大尺寸适合您选择的尺寸,并将背景添加到最小尺寸,直到它适合。

答案 1 :(得分:1)

jQuery可以让你接近。看看下面的代码。另外,这是一个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
        }
    });
});

代码取自:http://thejudens.com/eric/2009/07/jquery-image-resize/

注意:这可能无法将图像重新调整为指定像素的大小。但是,它会在保持纵横比的同时尽可能接近。