Hello,
In Visual Basic, the for loop includes the end value so your code is
stepping outside the bounds of the image.
Your code should read:
For y = 0 To bm.Height-1
For x = 0 To bm.Width-1
Dim c As Color = source.GetPixel(x, y)
Dim luma As Integer = CInt(c.R * 0.3 + c.G * 0.59 + c.B * 0.11)
bm.SetPixel(x, y, Color.FromArgb(luma, luma, luma))
Next
Next
However, this is not the best way to do it. That part of the article was
left in to illustrate the mechanics of the process rather than provide a
good solution. GetPixel and SetPixel is very slow.
The preferred method would be to copy the image using a ColorMatrix that
sets the gray scals for you such as:
protected function GetGrayImage(ByVal bm as Bitmap) as Bitmap
dim temp as new Bitmap(bm.Width, bm.Height)
dim ia as new ImageAttributes()
Dim cm As ColorMatrix = New ColorMatrix(New Single()() _
{New Single() {0.3, 0.3, 0.3, 0, 0}, _
New Single() {0.59, 0.59, 0.59, 0, 0}, _
New Single() {0.11, 0.11, 0.11, 0, 0}, _
New Single() {0, 0, 0, 1, 0}, _
New Single() {0, 0, 0, 0, 1}})
ia.SetColorMatrix(cm)
dim g as Graphics=Graphics.FromImage(temp)
g.Clear(Color.White)
g.DrawImage(bm,new Rectangle(0,0,temp.Width,temp.Height), 0, 0,
bm.Width, bm.Height, GraphicsUnit.Pixel, ia)
g.Dispose()
return temp
end function
Hope this helps.
--
Bob Powell [MVP]
C#, System.Drawing
The November edition of Well Formed is now available.
Learn how to create Shell Extensions in managed code.
http://www.bobpowell.net/currentissue.htm
Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm
Read my Blog at
http://bobpowelldotnet.blogspot.com