Click here to Skip to main content
15,895,192 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please can someone help me out? I have been trying to convert an image from picture box to grayscale and display the image in the same picture box but i keep getting an error "An unhandled exception of type 'System.NullReferenceException' occurred in imageCoordinateCapture.exe

Additional information: Object reference not set to an instance of an object." on the line "Bitmap returnMap = new Bitmap(image.Width, image.Height,System.Drawing.Imaging.PixelFormat.Format32bppArgb);"

Here is the method for converting the image to grayscale
C#
 public Bitmap processImage(Bitmap image)
{
    Bitmap returnMap = new Bitmap(image.Width, image.Height,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    System.Drawing.Imaging.BitmapData bitmapData1 = image.LockBits(new Rectangle(0, 0,image.Width, image.Height),System.Drawing.Imaging.ImageLockMode.ReadOnly,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    System.Drawing.Imaging.BitmapData bitmapData2 = returnMap.LockBits(new Rectangle(0, 0, returnMap.Width, returnMap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    int a = 0;
    unsafe
    {
        byte* imagePointer1 = (byte*)bitmapData1.Scan0;
        byte* imagePointer2 = (byte*)bitmapData2.Scan0;
        for (int i = 0; i < bitmapData1.Height; i++)
        {
            for (int j = 0; j < bitmapData1.Width; j++)
            {
                // write the logic implementation here
                a = (imagePointer1[0] + imagePointer1[1] +
                     imagePointer1[2]) / 3;
                imagePointer2[0] = (byte)a;
                imagePointer2[1] = (byte)a;
                imagePointer2[2] = (byte)a;
                imagePointer2[3] = imagePointer1[3];
                //4 bytes per pixel
                imagePointer1 += 4;
                imagePointer2 += 4;
            }//end for j
            //4 bytes per pixel
            imagePointer1 += bitmapData1.Stride -
                            (bitmapData1.Width * 4);
            imagePointer2 += bitmapData1.Stride -
                            (bitmapData1.Width * 4);
        }//end for i
    }//end unsafe
    returnMap.UnlockBits(bitmapData2);
    image.UnlockBits(bitmapData1);
    return returnMap;
}//end processImage 


And here is the code for the click event
C#
private void cmdGreyScale_Click(object sender, EventArgs e)
       {
          Bitmap img = null;
           //PictureBox oldImage = new PictureBox();
          // oldImage.Visible = false;
           //oldImage.Image = picImageDisplay.Image;

           // apply the filter
         //  Bitmap grayImage =  Grayscale.CommonAlgorithms.BT709.Apply(img);
          // Bitmap grayImage = Grayscale.CommonAlgorithms.BT709.Apply(img);
         // picImageDisplay.Image = grayImage;
         //  picPreview.Image = oldImage.Image;

           processImage(img);
           picImageDisplay.Image = img;

       }


please i need help
Posted

Under the debugger, you need to go to this line before the exception is thrown and examine the objects involved; probably, image is null at the moment of call. You told us where the exception is thrown; this is very good but not enough. You cannot ask question every time such things happen; it's important to learn how to cope with such a simple situations all by yourself.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object".

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx,
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx.

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx.

[EDIT]

As to the gray-scale conversion itself: there are many methods of doing it, and different quality results can be achieved, depending on the particular scene. Good artists making grey-scale images out color photographs rarely use default methods, such as changing saturation in all picture to zero. This is just one method of combining three (or four, with alpha) channels to a grey channel. They often parametrize it: use just one of two color channels, combine channels in different proportions, combine them dynamically (that is, not in constant proportion, but using more complex, non-linear function).

Good luck,
—SA
 
Share this answer
 
v2
You need to load a bitmap in your variable!
The img variable in the cmdGreyScale_Click function is null when you use it in the processImage.
 
Share this answer
 
I was able to solve the problem using this method after several hours of surfing the net and battling with the code
C#
//set the grayscale of the picturebox
     public void setGrayscale()
     {
         currentBitmap = (Bitmap)picImageDisplay.Image;
         Bitmap temp = (Bitmap)currentBitmap;
         Bitmap bmap = (Bitmap)temp.Clone();
         cloneImage =(Bitmap)temp.Clone() ;
         Color c;
           for(int i=0; i<bmap.width;>          {
               for (int j=0; j<bmap.height;>                {
                   c = bmap.GetPixel(i, j);
                   byte gray = (byte)(.299 * c.R + .587 * c.G + .114 * c.B);
                   bmap.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
               }// end of inner for loop
         } //end of outer for loop
           currentBitmap = (Bitmap)bmap.Clone();
           picImageDisplay.Image = bmap;
     }// end of setGrayscale method


where picImageDisplay is the name of the picturebox

Then on the click Event of the button
C#
private void cmdGreyScale_Click(object sender, EventArgs e)
      {

         //set the grayscale of the picture box
          //by calling the setGrayscale method
          setGrayscale();
         this.Invalidate();
      }


Thank you all for your contribution
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900