OutofMemory异常(裁剪图像时)

时间:2012-07-13 09:15:32

标签: c# asp.net

我正在尝试裁剪来自字节数组的图像。不幸的是,我在cropImage函数中得到了OutofMemory异常。这一部分展示了我如何在一个文件上写它。

System.IO.MemoryStream ms = new System.IO.MemoryStream(strArr);

System.Drawing.Rectangle oRectangle = new System.Drawing.Rectangle();
oRectangle.X = 50;
oRectangle.Y = 100;
oRectangle.Height = 180;
oRectangle.Width = 240;

System.Drawing.Image oImage = System.Drawing.Image.FromStream(ms);
cropImage(oImage, oRectangle);
name = DateTime.Now.Ticks.ToString() + ".jpg";
System.IO.File.WriteAllBytes(context.Server.MapPath(name), strArr);
context.Response.Write("http://local.x.com/test/" + name);

这部分是我的裁剪图像功能,这显然是它正在做什么..

private static System.Drawing.Image cropImage(System.Drawing.Image img, System.Drawing.Rectangle cropArea)
{
    System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img);
    System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea,
    bmpImage.PixelFormat);
    return (System.Drawing.Image)(bmpCrop);
}

这就是我构建strArr的方式

System.IO.Stream str = context.Request.InputStream;
int strLen = Convert.ToInt32(str.Length);
byte[] strArr = new byte[strLen];
str.Read(strArr, 0, strLen);
string st = String.Concat(Array.ConvertAll(strArr, x => x.ToString("X2"))); // try 4

2 个答案:

答案 0 :(得分:0)

不建议在ASP.NET中使用System.Drawing命名空间。 MSDN:

  

不支持在Windows或ASP.NET服务中使用System.Drawing命名空间中的类。尝试在其中一种应用程序类型中使用这些类可能会产生意外问题,例如服务性能下降和运行时异常。有关支持的替代方法,请参阅Windows Imaging Components。

答案 1 :(得分:0)

我直接从字节数组裁剪它,它只是工作:)感谢所有尽力帮助我的人。

public byte[] CropImage(int x, int y, int w, int h, byte[] imageBytes)
    {
        using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
        {
            ms.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms, true);
            Bitmap bmpCropped = new Bitmap(w, h);
            Graphics g = Graphics.FromImage(bmpCropped);

            Rectangle rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height);
            Rectangle rectCropArea = new Rectangle(x, y, w, h);

            g.DrawImage(img, rectDestination, rectCropArea, GraphicsUnit.Pixel);
            g.Dispose();

            MemoryStream stream = new MemoryStream();
            bmpCropped.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            return stream.ToArray();
        }
    }