
Originally Posted by
tscorpio
I am using VB 2008 & drawimage function to copy certain colored parts of image A to Image B. My problem is image A has many different colored patches on it and I only want to copy the ones that have a certain RGB value. I was going to set the masking color to the RGB value but remembered that defines the color to ignore - I’m interested in the opposite.
Basically I'm looking for a "Copy only pixels of certain color" technique.
I know I could loop through all the pixels and check it’s color, but it’s way slow and I’m hoping there’s something better.
Thanks in advance!
P.S. As a side note, after getting the copy function working, my next requirements will be to change all the colors on a image to be the same, then overlay that resulting image onto a second image, perferalby with about 50% transparency. I think I have that figured out though...
Hi tscorpio,
I can's see any alternative to looping through the pixels. Since you say looping through the pixels is slow, perhaps you are not yet familiar with the LockBits method which allows you to treat the image as a byte or integer array. The integer version could easily provide speed gains of over 100x over GetPixel/SetPixel for large images. The speed gain depends partly on how efficient you make your inner loop.
I posted a LockBits wrapper class (FastPix) to the CodeBank which makes it simpler to apply the LockBits method. See the "rapid pixel processing" link in my signature below. Assuming you have downloaded the FastPix class and added it to your project, and includeColor is the color you want to keep, you could code what you want to do optimally like this:
vb Code:
Dim colorValue As Integer = includeColor.ToARGB
Dim alphaMaskValue As Integer = &HFFFFFF
Dim alphaValue As Integer = &H80000000
Dim bmpA As New Bitmap(ImageA)
Using fp As New FastPix(bmpA)
Dim pixels() As Integer = fp.PixelArray
For i As Integer = 0 To pixels.Length - 1
Dim pixelValue As Integer = pixels(i)
If pixelValue = colorValue Then
pixels(i) = pixelValue And alphaMaskValue Or alphaValue
Else
pixels(i) = 0
End If
Next
End Using
The effect of this is to set the pixels of the wanted color to 50% opacity and all other pixels to 0% opacity. You can then paint bmpA onto ImageB using Graphics.DrawImage (which GDI+ does pretty efficiently).
BB