2014-07-14 65 views
0

在我的asp.net mvc應用程序中,我上傳圖像並將其大小調整爲800x600像素大小,將其轉換爲PNG格式,然後將其保存到磁盤。我使用下面的代碼動態生成的圖像比asp.net中的原始圖像大mvc

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圖像尺寸變得比origianl大。

回答

0

我找到了解決方案。相反,在PNG甲保存圖像的,我在JPEG甲節省這樣的:

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

我不知道爲什麼,但它爲我工作。