C#Winforms如何调整图像大小和保存

时间:2016-06-26 23:59:13

标签: image

嗨我想用openfiledialog打开一个图像文件并调整大小以上传到数据库所以请帮我解决这个从某些地方获得的代码,但我不知道如何让它工作谢谢

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);
    }
}

1 个答案:

答案 0 :(得分: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进行保存,因为您无法编写可以阅读的所有图像格式。