0

Actually it's a grey-scale picture and I want to copy the pixel value into an array then return it.I've tried a lot and there is always wrong as I click the button.

public class toarray  //class1
{
    public byte[,] bitmaptoarray(System.Drawing.Bitmap img)
    {   //sentence below is always wrong with:Object reference not set to an instance of an object.
        System.Drawing.Rectangle lockRect = new System.Drawing.Rectangle(0, 0, img.Width, img.Height);
        BitmapData imgData = img.LockBits(lockRect, ImageLockMode.ReadWrite, img.PixelFormat);
        byte[,] rband = new byte[img.Height, img.Width];   
        int rowOffset = imgData.Stride - img.Width * 3;
        unsafe
        {
            byte* imgPtr = (byte*)imgData.Scan0.ToPointer();
            for (int i = 0; i < img.Height; i++)
            {
                for (int j = 0; j < img.Width; j++)
                {
                    rband[i, j] = imgPtr[2];
                    imgPtr += 3;   
                }
                imgPtr += rowOffset;   
            }
            img.UnlockBits(imgData);
            img.Dispose();
        }
        return rband;
    }
}//public class toarray end

my test code

private void button3_Click(object sender, RoutedEventArgs e)
{
    toarray test1 = new toarray();
    byte[,] newarray = test1.bitmaptoarray(altitudeMap);
}
DENGKE
  • 1
  • 2
  • Did you check if `img` itself is null? – Suresh Nov 27 '15 at 23:17
  • yes, this is where I don't understand. In the test code I put the bitmap sorce (altitudeMap) into the method. – DENGKE Nov 27 '15 at 23:23
  • that means `altitudeMap` is null. Are you sure, that's not null? – Suresh Nov 27 '15 at 23:24
  • Why are you using all this WinForms stuff in a WPF application? Use a WPF BitmapSource instead and call its CopyPixels method. – Clemens Nov 27 '15 at 23:30
  • altitudeMap.Save("c:\\button.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg); I use this but still the same situation, I think the bitmap is null – DENGKE Nov 27 '15 at 23:37
  • If and when you have debugged your problem sufficiently enough that you can present your question in a more specific way than "there is a `NullReferenceException`", then please post a new question in which is included a good [mcve] with a precise explanation of what that code does and how that's different from what you want. Without a complete code example, nothing more than "`altitudeMap` is null` can be said, and even with one you should already have a good idea of _why_ the variable is null and be asking about whatever _specific_ issue you're having figuring out how to get it not to be null – Peter Duniho Nov 28 '15 at 01:55

0 Answers0