How do I read a 512x512 8-bit grey scale raw image file into a picturebox and display it in a small window?

I have a 512x512 pixel, 8-bit raw, greyscale bitmap image file and would like to display and fit it in a small window.  How do I do it?
Who is Participating?
The following code will build a byte array with 262144 (512x512)  elements..

It then displays it onto a graphics device... it can be scaled using the parameters passed into the DrawImage method.

      byte[] id=new byte[512*512];
      int ThisPixel;
      int c1,c2;
      for (c1=0 ; c1<512 ; c1++)
            for (c2=0 ; c2<512 ; c2++)
      // We now have a nice pattern in the data
      Bitmap bm=new Bitmap(512,512,System.Drawing.Imaging.PixelFormat.Format24bppRgb);
      for (c1=0 ; c1<512 ; c1++)
            for (c2=0 ; c2<512 ; c2++)
                  bm.SetPixel(c1,c2,Color.FromArgb(ThisPixel,ThisPixel,ThisPixel)); // Grayscale equivalent
      e.Graphics.DrawImage(bm,50,50,100,100); // The size
      bm.Dispose(); // Tidy up

Bob LearnedCommented:
Where did this image come from?

Is this a web app or a windows app?  And is the image a standard image file type (ie bmp, gif, jpg)?

If this is a web app, you can use client side script (javascript) to force a to your specifications.  If the images change repeatedly, the script can easily be instantiated from server side code.

In the event method where you want to launch the image, use:

string script = @"<script language='javascript'>'<image path>','windowName','width=512,height=512,scrollbars=false,toolbar=false,statusbar=false');</script>";
RegisterStartupScript("showimage", script);

On a button "submit" event, this will open a new window sized to your image with no toolbars, statusbar or scollbars.

Hope this helps.

pcssecureAuthor Commented:
Thanks smegghead.  Your code works but the SetPixel call is too slow.  Takes about 1-2s to load a 512x512 image file.  I found some unmanaged code as well that does a better job.  Anyway, I'll give you points.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.