GrayScale (by ColorMatrix) causes OutOfMemoryException. Why?

戏子无情 提交于 2019-12-11 03:29:42

问题


I have 2 forms, A and B. On the Form A, I click a button and an Image is being loaded to a PictureBox located ona the Form B. And, I want to set GrayScale to this image by:

   public void SetGrayScale(PictureBox pb)
    {
        ColorMatrix matrix = new ColorMatrix(new float[][]
        {
            new float[] {0.299f, 0.299f, 0.299f, 0, 0},
            new float[] {0.587f, 0.587f, 0.587f, 0, 0},
            new float[] {0.114f, 0.114f, 0.114f, 0, 0},
            new float[] {     0,      0,      0, 1, 0},
            new float[] {     0,      0,      0, 0, 0}
        });

        Image image = (Bitmap)pb.Image.Clone();

        ImageAttributes attributes = new ImageAttributes();
        attributes.SetColorMatrix(matrix);

        Graphics graphics = Graphics.FromImage(image);

        graphics.DrawImage(image,
                            new Rectangle(0, 0, image.Width, image.Height),
                            0,
                            0,
                            image.Width,
                            image.Height,
                            GraphicsUnit.Pixel,
                            attributes);

        graphics.Dispose();

        pb.Image = image;
    }

This code works properly when the PictureBox is on the same form (A). But, when it is on the Form B, the OutOfMemoryException is raised. Why ?


回答1:


More questions/things for you to investigate rather than an actual answer I'm afraid:

  1. As in the comment to your answer - is the Image object correct?

  2. If not then that implies that there's something wrong with the PictureBox object passed into this method, or that you can't access the PictureBox's Image properly.

My first thought was threading, but both forms should be in the UI thread.




回答2:


Ok, I've Fixed it :) The solution is, I had to created a Bitmap object from the OpenDialog.FileName, and later set PictureBox.Image = myBitmap

I didn't do it at the beginning, I was just setting PictureBox.Load(OpenDialog.FileName). And that was my mistake.

Ok, thank's for Your cooperation, ChrisF ! :)



来源:https://stackoverflow.com/questions/925568/grayscale-by-colormatrix-causes-outofmemoryexception-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!