Sourav
Sourav

Reputation: 17530

Reading pixel value of an image

Q> If showing all the RGB pixel value of a 60*66 PNG image takes 10-34 seconds then how Image Viewer shows image instantly ?

        Dim clr As Integer ' or string
        Dim xmax As Integer
        Dim ymax As Integer
        Dim x As Integer
        Dim y As Integer
        Dim bm As New Bitmap(dlgOpen.FileName)

        xmax = bm.Width - 1
        ymax = bm.Height - 1

        For y = 0 To ymax
            For x = 0 To xmax
                With bm.GetPixel(x, y)
                    clr = .R & .G & .B
                    txtValue.AppendText(clr)
                End With
            Next x
        Next y

Edit

Dim bmp As New Bitmap(dlgOpen.FileName)
Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(rect,Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat)
Dim ptr As IntPtr = bmpData.Scan0
Dim bytes As Integer = Math.Abs(bmpData.Stride) * bmp.Height
Dim rgbValues(bytes - 1) As Byte

System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)

For counter As Integer = 0 To rgbValues.Length - 1
       txtValue.AppendText(rgbValues(counter))
Next

System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes)
bmp.UnlockBits(bmpData)

The first code takes 10 seconds and the 2nd one around 34 seconds for showing all the value in a textbox for a 59*66 PNG image on AMD A6 3500 with 4 GB RAM !

The problem exist when reading from file and writing to a textbox takes place in same time !

Upvotes: 1

Views: 10794

Answers (1)

Rob Volgman
Rob Volgman

Reputation: 2114

The problem is that the feature you're using, GetPixel, is very slow if you need to access a lot of pixels. Try using LockBits. You can use that to gather image data nearly instantly.

Using the LockBits method to access image data.

Upvotes: 1

Related Questions