A と B の 2 つのフォームがあります。フォーム A でボタンをクリックすると、フォーム B にある PictureBox に画像が読み込まれます。次の方法で、GrayScale をこの画像に設定します。
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;
}
このコードは、PictureBox が同じフォーム (A) にある場合に正しく機能します。ただし、フォーム B にある場合は、OutOfMemoryException が発生します。なんで ?