2016-06-26 60 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

相关问题