user20493
user20493

Reputation: 5804

Boolean bitmap operation in .NET?

I have two 8bpp bitmaps. I want to do a bitwise AND of one to the other, but I don't see any obvious way to do this in .NET. Is it possible to do this without using non-.NET methods? Thanks!

Upvotes: 0

Views: 382

Answers (4)

James
James

Reputation: 9975

You could try converting the Bitmap to a Byte array and then loop through the bytes anding them together

Edit : Ran a Time Test on the loop idea:

Example Code:

DateTime StartTime = DateTime.Now;
Image Image1 = Image.FromFile("C:\\Image1.bmp");
Image Image2 = Image.FromFile("C:\\Image2.bmp");
DateTime AfterLoad = DateTime.Now;
MemoryStream S = new MemoryStream();
Image1.Save(S, System.Drawing.Imaging.ImageFormat.Bmp);
Byte[] I1 = S.ToArray();
Image2.Save(S, System.Drawing.Imaging.ImageFormat.Bmp);
Byte[] I2 = S.ToArray();
DateTime AfterConvert = DateTime.Now;
DateTime AfterLoop = DateTime.Now;
if (I1.Length == I2.Length)
{
    Byte[] I3 = new Byte[I1.Length];
    for (int i = 0; i < I1.Length; i++)
        I3[i] = Convert.ToByte(I1[i] & I2[i]);
    AfterLoop = DateTime.Now;
    FileStream F = new FileStream("C:\\Users\\jamesb\\desktop\\Image3.bmp", FileMode.OpenOrCreate);
    F.Write(I3, 0, I3.Length);
    F.Close();
}
DateTime Finished = DateTime.Now;
MessageBox.Show("Load Time: " + (AfterLoad - StartTime).TotalMilliseconds.ToString() + " ms" + "\r\n" +
                "Convert Time: " + (AfterConvert - AfterLoad).TotalMilliseconds.ToString() + " ms"+ "\r\n" +
                "Loop Time: " + (AfterLoop - AfterConvert).TotalMilliseconds.ToString() + " ms"+ "\r\n" +
                "Save Time: " + (Finished - AfterLoop).TotalMilliseconds.ToString() + " ms"+ "\r\n" +
                "Total Time: " + (Finished - StartTime).TotalMilliseconds.ToString() + " ms");

with the following results :

Load Time: 30.003 ms
Convert Time: 94.0094 ms
Loop Time: 128.0128 ms
Save Time: 177.0177 ms
Total Time: 429.0429 ms

The images "Image1" and "Image2" were 4000 x 2250 (From a digital camera converted to 8 bit bmp)

Upvotes: 3

t0mm13b
t0mm13b

Reputation: 34592

You can use the 'BitBlt' function, in which you can AND the source and destination (SRCAND), the pinvoke signature is here.

Here is an article on Codeproject that uses a BitBlt wrapper here.

Hope this helps, Best regards, Tom.

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284816

I think you're looking for Bitmap.LockBits.

Upvotes: 3

Pavel Alexeev
Pavel Alexeev

Reputation: 6081

If performance is not important, use Bitmap.GetPixel and Bitmap.SetPixel

Upvotes: 1

Related Questions