2016-06-26 61 views
-2

您好我想用openfiledialog打開一個圖像文件並調整大小以上傳到數據庫,所以請幫我使用這個代碼,我從一些地方獲得,但我不知道如何製作它工作感謝C#Winforms如何調整圖像大小並保存

private void ResizeImg(double scaleFactor, Stream sourcePath, string tragetPath) 
{ 
    using (var image = System.Drawing.Image.FromStream(sourcePath)) 
    { 

     var newWidth = (int)(image.Width * scaleFactor); 
     var newHeight = (int)(image.Height * scaleFactor); 
     var resizingImg = new Bitmap(newWidth, newHeight); 
     var resizeGraph = Graphics.FromImage(resizingImg); 
     resizeGraph.CompositingQuality = CompositingQuality.HighQuality; 
     resizeGraph.SmoothingMode = SmoothingMode.HighQuality; 
     resizeGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; 
     var imageRectangle = new Rectangle(0, 0, newWidth, newHeight); 
     resizeGraph.DrawImage(image, imageRectangle); 
     resizingImg.Save(targetPath, image.RawFormat); 
    } 
} 

回答

0

沒有指定源矩形和目標矩形,它不會拉伸。

變化

resizeGraph.DrawImage(image, imageRectangle); 

var srcRectangle = new Rectangle(0, 0, image.Width, image.Height); 
resizeGraph.DrawImage(image, imageRectangle,srcRectangle, GraphicsUnit.Pixel); 

BTW:考慮ImageFormat.Jpeg或png格式的保存,因爲你不能寫所有的圖像格式,你可以閱讀。

+0

感謝您的回覆和更正,所以現在請告訴我如何通過按下上傳按鈕和打開文件對話框來調用此函數請給我完整的代碼,因爲我已經嘗試了很多,但仍然無法做到這一點 – user2933102

相關問題