2009-06-17 66 views
4

用戶將能夠上傳圖像。如果圖像大於設定的尺寸,我想將其縮小到該尺寸。很顯然,由於比例的緣故,它不必完全匹配,寬度將是關鍵尺寸,因此高度可能會變化。ASP.Net MVC圖像上傳通過縮小或填充來調整大小

如果圖像小於設置的尺寸,我想用定義顏色的背景創建一個新的圖像到設置的尺寸,然後將上傳的圖像居中,因此結果是帶有填充顏色的原始圖像。

任何的代碼示例或鏈接不勝感激

+1

只有一行代碼[與此lib](http://imageresizing.net)。如果圖像較大,則將圖像調整爲指定的寬度,如果圖像較小,則簡單地展開畫布。 `ImageBuilder.Current.Build(postedFile,destination,new ResizeSettings(「width = 500&scale = upscalecanvas&bgcolor = green」));`[這是一個實例](http://img.imageresizing.net/red-leaf.jpg ;寬度= 1680;標度= upscalecanvas; BGCOLOR =綠色)。 – 2011-05-28 16:15:40

回答

10

下面是我根據寬度快速調整大小的代碼片段。我相信你可以弄清楚如何爲Bitmap添加背景顏色。這不是完整的代碼,而只是一個如何做事的想法。

public static void ResizeLogo(string originalFilename, string resizeFilename) 
{ 
    Image imgOriginal = Image.FromFile(originalFilename); 

    //pass in whatever value you want for the width (180) 
    Image imgActual = ScaleBySize(imgOriginal, 180); 
    imgActual.Save(resizeFilename); 
    imgActual.Dispose(); 
} 

public static Image ScaleBySize(Image imgPhoto, int size) 
{ 
    int logoSize = size; 

    float sourceWidth = imgPhoto.Width; 
    float sourceHeight = imgPhoto.Height; 
    float destHeight = 0; 
    float destWidth = 0; 
    int sourceX = 0; 
    int sourceY = 0; 
    int destX = 0; 
    int destY = 0; 

    // Resize Image to have the height = logoSize/2 or width = logoSize. 
    // Height is greater than width, set Height = logoSize and resize width accordingly 
    if (sourceWidth > (2 * sourceHeight)) 
    { 
     destWidth = logoSize; 
     destHeight = (float)(sourceHeight * logoSize/sourceWidth); 
    } 
    else 
    { 
     int h = logoSize/2; 
     destHeight = h; 
     destWidth = (float)(sourceWidth * h/sourceHeight); 
    } 
    // Width is greater than height, set Width = logoSize and resize height accordingly 

    Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight, 
           PixelFormat.Format32bppPArgb); 
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); 

    Graphics grPhoto = Graphics.FromImage(bmPhoto); 
    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; 

    grPhoto.DrawImage(imgPhoto, 
     new Rectangle(destX, destY, (int)destWidth, (int)destHeight), 
     new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight), 
     GraphicsUnit.Pixel); 

    grPhoto.Dispose(); 

    return bmPhoto; 
} 
+4

需要異常處理和Jpeg編碼設置.... http://nathanaeljones.com/163/20-image-resizing-pitfalls/ – 2010-01-04 19:13:42