views:

114

answers:

1

The method below, takes a colour matrix and applies it to the supplied image. There are a couple of things to note:

(1) It is not a function
(2) The same image is used to create the graphics object, and as the source of the DrawImage method.

Public Sub ApplyMatrixToImage(ByVal matrix As ColorMatrix, ByVal image As Image)
    Using atts As New ImageAttributes
        atts.SetColorMatrix(matrix)
        Using g As Graphics = Graphics.FromImage(image)
            Dim width As Integer = image.Width
            Dim height As Integer = image.Height
            Dim rect As New Rectangle(0, 0, width, height)
            g.DrawImage(image, rect, 0, 0, width, height, GraphicsUnit.Pixel, atts)
        End Using
    End Using
End Sub

I don't know if it's bad practice not to create another bitmap to render the final image into, but the strange thing is the method works fine for a colour balance adjustment (Matrix30, 31 and 32), but does nothing for an opacity adjustment (Matrix33).

What's going on?

+2  A: 

If I understand your question correctly: you are asking why you cannot alter the alpha channel with this method? (Why it should be a function instead of a sub elludes me completely.)

But why it doesn't work as you may expect with opactiy/transparency I understand perfectly. :-)

The .DrawImage method (combined with the ImageAttributes) will DRAW each altered pixel onto itself (since the width and height are the same). Note that it will draw - not replace. This means that the original pixel value will blend with the newly calculated pixel value. Among other things, this means that if the original pixel if completely opaque, there is no way that that will change. Painting with a partially transpararent color over something opaque will still yieald an opaque color.

danbystrom
Ah, thanks that explains it. Thanks also to nobugz for the warning.
Jules
+1. I didn't know that, good to know!
Otaku