Adi Drumea

Tuesday, November 01, 2005

[.NET] Out of Memory with Graphics.DrawImage and ImageAttributes

I am developing some user controls in .NET using Forms. I need to transparently draw a bitmap on a button, so I'm using ImageAttributes to specify the transparent color. Still, a problem appeard: having many of these buttons shown on the screen would sometimes crash with OutOfMemoryException in the DrawImage method. Removing the ImageAttributes-based rendering would also prevent the creash. Dug the net, found nothing. I remembered a while ago that the best Bitmap format to use in terms of speed was 32bit PARGB. So I converted my Bitmaps to this format and the crash went away. My guess is that during the rendering with specified ImageAttributes, it performs some kind of expensive conversion (both time and resource wise) if not 32bit PARGB. Having the bitmaps in this format, prevents this expensive operation.

6 Comments:

  • How do you convert to PArgb?
    I have Argb and can't convert it at all.

    By Anonymous Anonymous, at 3:13 AM  

  • Thank you for your post!!! You save several hours of my time!!!

    By Anonymous Anonymous, at 9:43 AM  

  • damn thanks dude it really improve image processing! its so faster!

    By Anonymous Anonymous, at 2:57 PM  

  • I have the same problem, but it reproduces only on some kind of bitmaps. I use this method to draw highlighted items in custom control:
    float alpha = 0.3f;
    float invA = 1.0f - alpha;
    float addR = (float)SystemColors.Highlight.R * 0.0039f * alpha;
    float addG = (float)SystemColors.Highlight.G * 0.0039f * alpha;
    float addB = (float)SystemColors.Highlight.B * 0.0039f * alpha;
    ImageAttributes imgAttrs = new ImageAttributes();
    ColorMatrix matrix = new ColorMatrix(new float[][] {
    new float[] {invA, 0.0f, 0.0f, 0.0f, 0.0f},
    new float[] {0.0f, invA, 0.0f, 0.0f, 0.0f},
    new float[] {0.0f, 0.0f, invA, 0.0f, 0.0f},
    new float[] {0.0f, 0.0f, 0.0f, 1.0f, 0.0f},
    new float[] {addR, addG, addB, 0.0f, 1.0f},
    imgAttrs.SetColorMatrix(matrix);
    graphics.DrawImage(..., imgAttrs);

    The size of my image is 32 x 32 pixels. And OutOfMemoryException occurs....how could it be?!?! Goddamn .NET Framework!
    Thanks, bro :) I'll try your solution.

    By Anonymous Anonymous, at 1:55 AM  

  • This comment has been removed by the author.

    By Blogger Rajesh, at 7:41 PM  

  • From MSDN, the remark about the Bitmap.FromStream says:

    You must keep the stream open for the lifetime of the Image.
    See this
    http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=1406323&SiteID=1

    By Blogger Rajesh, at 7:42 PM  

Post a Comment

<< Home