2009-12-30 118 views
7

我想縮放圖像,但我不希望圖像看起來偏斜。縮放圖像,但保持其比例

圖像必須是115x115(長x寬)。

圖像不能超過115像素高(長度),但如果需要,寬度可以小於115但不會更多。

這是棘手?

+0

這似乎類似於http://stackoverflow.com/questions/2823200/。看到我對這個問題的回答。 – 2010-11-04 03:26:45

回答

2

您正在尋找縮放圖像,並保留寬高比

float MaxRatio = MaxWidth/(float) MaxHeight; 
float ImgRatio = source.Width/(float) source.Height; 

if (source.Width > MaxWidth) 
return new Bitmap(source, new Size(MaxWidth, (int) Math.Round(MaxWidth/
ImgRatio, 0))); 

if (source.Height > MaxHeight) 
return new Bitmap(source, new Size((int) Math.Round(MaxWidth * ImgRatio, 
0), MaxHeight)); 

return source; 

應該幫助你,如果你有興趣的想法:Wikpedia article on Image Aspect Ratio

+0

剛剛嘗試過這段代碼(在搜索相同的基本問題時發現了其他地方),如果從寬度和高度均大於最大值的圖像開始,它實際上不會完成這項工作 - 您需要根據原始圖像的哪個尺寸最大來應用第一或第二縮放比例,否則最終尺寸中的一個大於任一縮放中允許的最大尺寸。 – Moo 2010-01-15 20:46:36

5

需要保留寬高比:

float scale = 0.0; 

    if (newWidth > maxWidth || newHeight > maxHeight) 
    { 
     if (maxWidth/newWidth < maxHeight/newHeight) 
     { 
      scale = maxWidth/newWidth; 
     } 
     else 
     { 
      scale = maxHeight/newHeight; 
     } 
     newWidth = newWidth*scale; 
     newHeight = newHeight*scale; 

    } 

在代碼中,最初newWidth/newHeight是圖像的寬度/高度。

+0

如果newHeight或newWidth是一個整數,它將無法正常工作,您將需要一個強制轉換爲'float'。 – BrunoLM 2010-11-04 10:44:13

4

基於的Brij的答案我做了這個擴展方法:

/// <summary> 
/// Resize image to max dimensions 
/// </summary> 
/// <param name="img">Current Image</param> 
/// <param name="maxWidth">Max width</param> 
/// <param name="maxHeight">Max height</param> 
/// <returns>Scaled image</returns> 
public static Image Scale(this Image img, int maxWidth, int maxHeight) 
{ 
    double scale = 1; 

    if (img.Width > maxWidth || img.Height > maxHeight) 
    { 
     double scaleW, scaleH; 

     scaleW = maxWidth/(double)img.Width; 
     scaleH = maxHeight/(double)img.Height; 

     scale = scaleW < scaleH ? scaleW : scaleH; 
    } 

    return img.Resize((int)(img.Width * scale), (int)(img.Height * scale)); 
} 

/// <summary> 
/// Resize image to max dimensions 
/// </summary> 
/// <param name="img">Current Image</param> 
/// <param name="maxDimensions">Max image size</param> 
/// <returns>Scaled image</returns> 
public static Image Scale(this Image img, Size maxDimensions) 
{ 
    return img.Scale(maxDimensions.Width, maxDimensions.Height); 
} 

容量調整方法:

/// <summary> 
/// Resize the image to the given Size 
/// </summary> 
/// <param name="img">Current Image</param> 
/// <param name="width">Width size</param> 
/// <param name="height">Height size</param> 
/// <returns>Resized Image</returns> 
public static Image Resize(this Image img, int width, int height) 
{ 
    return img.GetThumbnailImage(width, height, null, IntPtr.Zero); 
} 
+0

而不是img.Height,img.Source.Height爲我工作(VS 2010 .net 4)。另外,Source被用於Width – mnemonic 2013-01-23 19:47:58