Asp.net图像调整质量

时间:2014-01-26 17:50:00

标签: asp.net image-processing thumbnails

我有这个代码用于调整大小并保存用户发布的文件。 问题是,当我重新调整到480px宽度时,图像会失去很多质量,而kb的大小仍然很大。

例如,当我使用像Paint这样的软件“手动”将相同的图像调整为480px时,质量仍然与原始图像一样好(从我的眼睛可以看出)并且kb的尺寸要小得多而不是使用GetThumbNailImage方法调整大小。

Mdn说“如果您从具有嵌入式缩略图的图像请求大型缩略图图像(例如,300 x 300),缩略图图像中的质量可能会明显下降。可能会更好通过调用DrawImage方法来扩展主图像(而不是缩放嵌入的缩略图)。,但这似乎适用于Windows窗体,我需要一个Web应用程序。

我应该使用什么代码来执行此操作?

System.IO.Stream st = FileUploadPost.PostedFile.InputStream;

myImage = System.Drawing.Image.FromStream(st);
thumb = myImage.GetThumbnailImage(newWidth, newHeight, null, System.IntPtr.Zero);

thumb.Save(myPath);

3 个答案:

答案 0 :(得分:2)

以下代码对我有用。您可以设置新的位图分辨率:

using System.Drawing;

Bitmap img = (Bitmap)Bitmap.FromStream(FileUploadPost.PostedFile.InputStream);
Bitmap newImg = new Bitmap(maxWidth, maxHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newImg.SetResolution(72, 72);
Graphics newGraphic = Graphics.FromImage(newImg);
newGraphic.Clear(Color.Transparent);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(img, 0, 0, maxWidth, maxHeight);
System.Drawing.Imaging.ImageFormat format = default(System.Drawing.Imaging.ImageFormat);
string ext = Path.GetExtension(FileUploadPost.PostedFile.FileName);
switch (ext.ToLower())
{
    case ".gif":
        format = System.Drawing.Imaging.ImageFormat.Gif;
        break;
    case ".png":
        format = System.Drawing.Imaging.ImageFormat.Png;
        break;
    default:
        format = System.Drawing.Imaging.ImageFormat.Jpeg;
        break;
}
newImg.Save(myPath, format);

您可以将其包装在全局类的void函数中:

public static void UploadImage(HttpPostedFileBase file, int maxWidth, int maxHeight)
{
  //paste all the above code in here and replace FileUploadPost.PostedFile with file
}

然后你可以从项目的任何地方调用它:

ClassName.UploadImage(FileUploadPost.PostedFile, 300, 300);

答案 1 :(得分:0)

这回答是否充分?

Resizing an image in asp.net without losing the image quality

这是一个经常出现的问题。

答案 2 :(得分:0)

试试这个

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public static System.Drawing.Image ResizeImage( System.Drawing.Image image, int percent ) {
  // percent is the actual integer percent of the original size

  System.Drawing.Bitmap imgThumb = new System.Drawing.Bitmap( image.Width * percent / 100, image.Height * percent / 100 );

  Rectangle sourceRect = new Rectangle( 0, 0, image.Width, image.Height );
  Rectangle destRect = new Rectangle( 0, 0, imgThumb.Width, imgThumb.Height );


  System.Drawing.Graphics g = System.Drawing.Graphics.FromImage( imgThumb );
  g.CompositingQuality = CompositingQuality.HighQuality;
  g.SmoothingMode = SmoothingMode.HighQuality;
  g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  g.DrawImage( image, destRect, sourceRect, GraphicsUnit.Pixel );
  return ( imgThumb );
}