Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Alpha blending two bitmaps using color matrix and imaging attributes

0.00/5 (No votes)
17 Jan 2007 1  
Here is another alpha blend that is truly a blend at pixel level.

Introduction

I know there are numerous examples of alpha blending stuff, but many are not true blends, such as the in one of my articles. Others call managing transparencies as blends, and some are truly complicated transforms and merges.

I have been convinced there would be a simple .NET solution like 5 lines of code... This is it..

Public Sub SetAlphaRGB(ByRef abm As Image)

Dim bitm As New Bitmap(abm)

' I actually got help on this from using visual studio F1
' Initialize the color matrix.

Dim mxItems As Single()() = { _
New Single() {1, 0, 0, 0, 0}, _
New Single() {0, 1, 0, 0, 0}, _
New Single() {0, 0, 1, 0, 0}, _
New Single() {0, 0, 0, 128, 0}, _ Note that sets alpha at 128 50%
New Single() {0, 0, 0, 0, 1}}

Dim colorMatrix As New System.Drawing.Imaging.ColorMatrix(mxItems)

' Create an ImageAttributes object and set its color matrix.

Dim imageAtt As New System.Drawing.Imaging.ImageAttributes()

imageAtt.SetColorMatrix(colorMatrix, _
                        System.Drawing.Imaging.ColorMatrixFlag.Default, _
                        System.Drawing.Imaging.ColorAdjustType.Bitmap)

' look at properties of imageattributes also can set threshold and gamma
so this routine can handle most of your image manipulations

Dim r1 As RectangleF
r1.X = 0
r1.Y = 0
r1.Width = abm.Width
r1.Height = abm.Height

Dim r2 As RectangleF
r2.X = 0
r2.Y = 0
r2.Width = bm.Width
r2.Height = bm.Height 

'
graphics1.Dispose()
graphics1 = Graphics.FromImage(bm)

Dim brush3 As New TextureBrush(bitm, r1, imageAtt)
brush3.WrapMode = Drawing2D.WrapMode.Tile ' if you want to tile else delete

graphics1.CompositingMode = Drawing2D.CompositingMode.SourceOver
graphics1.FillRectangle(brush3, r2) ' I didnt test but fill path should allow
                                    ' overlay in irregular polygon etc.

'draw image could be used, but if you want to tile a fill option is needed
graphics1.DrawImage(bitm, New Rectangle(0, 0, 1700, 1700), 0, 0,_
                    bitm.Width, bitm.Height, GraphicsUnit.Pixel, imageAtt)

brush3.Dispose()
graphics1.Dispose()
MainForm.PictureBox1.Refresh() ' Required by my project
SetGraphics(MainForm.PictureBox1) ' Required by my project

End Sub

My granddaughter tiled over a DesignLab(c) 2007 design. This is at 128 Alpha (50%). This truly is about 5 lines of code. If you play with the image attributes, you can manage the threshold and gamma as well.

Sample image

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here