簡體   English   中英

內存不足異常(裁剪圖像時)

[英]OutofMemory Exception (when cropping an Image)

我正在嘗試裁剪來自字節數組的圖像。 不幸的是,我的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);

這部分是我的crop Image函數,很明顯它在做什么。

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

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

Windows或ASP.NET服務中不支持使用System.Drawing命名空間中的類。 嘗試從這些應用程序類型之一中使用這些類可能會產生意外問題,例如服務性能下降和運行時異常。 有關支持的替代方法,請參見Windows Imaging Components。

我直接從字節數組中裁剪了它,然后它就可以工作了:)感謝所有盡力幫助我的人。

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();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM