如何使图片的特定宽度和高度不失去比例
本文关键字:高度 失去 何使图 | 更新日期: 2023-09-27 18:05:31
如何使图片特定的宽度和高度而不失去比例?
我有asp.net c#应用程序,我使用处理程序来操纵不同大小的图像。例如,如果我需要图像宽度为200或300等。
但如果我需要使图像大小与宽度300和高度300,并保持比例如何使它?还有,有没有办法在图片上找到人脸?
是否有任何免费的组件或具体的方法来完成它?
如果你同时控制图像的高度和宽度,你不能保持比例,除非它们恰好与现有的图像比例相匹配。
一个解决方法是调整图像的大小,使最大的尺寸适合您选择的尺寸,并在最小的尺寸上添加背景,直到它适合。
jQuery可以让您接近。看看下面的代码。还有,这是一个工作小提琴。
$(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/.
注意:这可能不会将图像精确地重新调整到指定的像素。但是,它将在保持长宽比的同时尽可能接近。