调整图像大小GDI +图形.NET [英] Resize image gdi+ graphics .net

查看:152
本文介绍了调整图像大小GDI +图形.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法倒缩图像的一个网站,我的工作:

I have this method for shrinking down an image for a website that I'm working on:

static byte[] createSmallerImage(
   BlogPhoto blogPhoto, 
   int newMaxWidth, 
   int newMaxHeight)
{
  Image img;
  using (MemoryStream originalImage = 
           new MemoryStream(blogPhoto.BlogPhotoImage))
  {
    img = Image.FromStream(originalImage);
  }

  int newWidth;
  int newHeight;
  byte[] arr;

  if (img.Width > img.Height)
  {
    if (img.Width <= newMaxWidth)
    {

      using (MemoryStream thumbStr = new MemoryStream())
      {
        img.Save(thumbStr, ImageFormat.Jpeg);
        img.Dispose();
        arr = thumbStr.ToArray();
      }
      return arr;
    }

    newWidth = newMaxWidth;
    newHeight = 
       (int)(((float)newWidth / (float)img.Width) * (float)img.Height);
  }
  else
  {
    if (img.Height <= newMaxHeight)
    {

      using (MemoryStream thumbStr = new MemoryStream())
      {
        img.Save(thumbStr, ImageFormat.Jpeg);
        img.Dispose();
        arr = thumbStr.ToArray();
      }
      return arr;
    }

    newHeight = newMaxHeight;
    newWidth = 
      (int)(((float)newHeight / (float)img.Height) * (float)img.Width);
  }

  Image thumb = new Bitmap(newWidth, newHeight);

  Graphics g = Graphics.FromImage(thumb);
  g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  g.SmoothingMode = SmoothingMode.HighQuality;
  g.PixelOffsetMode = PixelOffsetMode.HighQuality;
  g.CompositingQuality = CompositingQuality.HighQuality;

  g.DrawImage(img, 0f, 0f, (float)newWidth, (float)newHeight);


  using (MemoryStream thumbStr = new MemoryStream())
  {
    thumb.Save(thumbStr, ImageFormat.Jpeg);
    arr = thumbStr.ToArray();
  }

  g.Dispose();
  img.Dispose();

  return arr;
}

大多数它的伟大工程,但有时它给了我这个异常的时候:在GDI +中发生一般性错误。错误code -2147467259。资料来源:System.Drawing中。这发生在Image.Save(...我试图让这个code防御性越好,但我仍然没有得到什么造成这一点。如果有人知道那简直太好了答案,批评也欢迎。

Most of the time it works great but sometimes it gives me this exception:A generic error occurred in GDI+. Error Code -2147467259. Source: "System.Drawing". This occurs on the Image.Save(... I tried to make this code as defensive as possible but am still not getting whats causing this. If someone knows the answer that'd be great, critiques are welcome too.

推荐答案

看一下Image.FromStream()

Look at the documentation for Image.FromStream()

http://msdn.microsoft.com/en-us/library/ 93z9ee4x.aspx

您需要保持流打开图像的寿命。保持第一的MemoryStream打开更长的时间,并且它应该工作。

You need to keep the stream open for the lifetime of the Image. Keep the first MemoryStream open longer, and it should work.

这篇关于调整图像大小GDI +图形.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆