动态生成的图像比asp.net mvc中的原始图像大

时间:2014-07-14 13:51:53

标签: asp.net-mvc image resize

在我的asp.net mvc应用程序中,我上传图像并将其大小调整为800x600像素大小,将其转换为PNG格式,然后将其保存到磁盘。我正在使用以下代码

public void ResizeImg(HttpPostedFileBase UploadImg)
{
    if (UploadImg != null)
    {
       Stream s = UploadImg.InputStream;
       Image UploadedImg = Image.FromStream(s);
       int Width = UploadedImg.Width;
       int Height = UploadedImg.Height;

    int ResizeWidth = 800, ResizeHeight = 600;

    using (var newImage = new Bitmap(ResizeWidth, ResizeHeight))
    using (var graphics = Graphics.FromImage(newImage))
    using (var stream = new MemoryStream())
    {
        /* Resizing */
        graphics.SmoothingMode = SmoothingMode.AntiAlias;
        graphics.InterpolationMode = InterpolationMode.Default;
        graphics.PixelOffsetMode = PixelOffsetMode.Default;
        graphics.DrawImage(UploadedImg, new Rectangle(0, 0, ResizeWidth, ResizeHeight));
        newImage.Save(stream, ImageFormat.Png);

        /* Saving resized image */
        FileStream fileStream = File.Create(HttpContext.Current.Server.MapPath("~/Images/GeneratedBarcode/testing.png"), (int)stream.Length);

        byte[] bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, bytesInStream.Length);

        fileStream.Write(bytesInStream, 0, bytesInStream.Length);           
    }
}

}

代码正常运行。但问题是原始图像是1024x768 jpg图像,这是858 KB,调整后它是800x600 png图像,1.16MB 为什么在调整到较小尺寸并转换为png图像尺寸后变得比原始尺寸大。

1 个答案:

答案 0 :(得分:0)

我找到了解决该问题的方法。我没有将图像保存在PNG格式中,而是将其保存为JPEG格式,如下所示:

 //newImage.Save(stream, ImageFormat.Png);
 newImage.Save(stream, ImageFormat.Jpeg);

我不知道为什么,但它对我有用。