2016-04-01 48 views
0

アスペクト比を考慮せずに画像を特定のサイズにリサイズする必要があります。このコードではアスペクト比を考慮しています。アスペクト比を維持しない画像のサイズを変更する

public Image resizeImage(int newWidth, int newHeight, string stPhotoPath) 
{ 
    Image imgPhoto = Image.FromFile(stPhotoPath); 

    int sourceWidth = imgPhoto.Width; 
    int sourceHeight = imgPhoto.Height; 

    //Consider vertical pics 
    if (sourceWidth < sourceHeight) 
    { 
     int buff = newWidth; 

     newWidth = newHeight; 
     newHeight = buff; 
    } 

    int sourceX = 0, sourceY = 0, destX = 0, destY = 0; 
    float nPercent = 0, nPercentW = 0, nPercentH = 0; 

    nPercentW = ((float)newWidth/(float)sourceWidth); 
    nPercentH = ((float)newHeight/(float)sourceHeight); 
    if (nPercentH < nPercentW) 
    { 
     nPercent = nPercentH; 
     destX = System.Convert.ToInt16((newWidth - 
        (sourceWidth * nPercent))/2); 
    } 
    else 
    { 
     nPercent = nPercentW; 
     destY = System.Convert.ToInt16((newHeight - 
        (sourceHeight * nPercent))/2); 
    } 

    int destWidth = (int)(sourceWidth * nPercent); 
    int destHeight = (int)(sourceHeight * nPercent); 


    Bitmap bmPhoto = new Bitmap(newWidth, newHeight, 
        PixelFormat.Format24bppRgb); 

    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, 
       imgPhoto.VerticalResolution); 

    Graphics grPhoto = Graphics.FromImage(bmPhoto); 
    grPhoto.Clear(Color.Black); 
    grPhoto.InterpolationMode = 
     System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 

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

    grPhoto.Dispose(); 
    imgPhoto.Dispose(); 
    return bmPhoto; 
} 

答えて

2

すべての計算を削除し、ここで

grPhoto.DrawImage(imgPhoto, 
    new Rectangle(0, 0, newWidth, newHeight), 
    new Rectangle(0, 0, sourceWidth, sourceHeight), 
    GraphicsUnit.Pixel); 

を使用し、全体の方法です:

public static Image Resize(Image source, int width, int height) 
{ 
    if (source.Width == width && source.Height == height) return source; 
    var result = new Bitmap(width, height, PixelFormat.Format24bppRgb); 
    result.SetResolution(source.HorizontalResolution, source.VerticalResolution); 
    using (var g = Graphics.FromImage(result)) 
     g.DrawImage(source, new Rectangle(0, 0, width, height), new Rectangle(0, 0, source.Width, source.Height), GraphicsUnit.Pixel); 
    return result; 
} 
+0

おかげでたくさんの..あなたはメソッドとしてこれを追加することができますしてください... – techno

+0

確かに。上のようなパスか 'Image'だけのパスが必要ですか? –

+0

ビットマップの戻り値の型と3つのパラメータsource、width、heightを持つメソッドが好きです。 – techno

関連する問題