views:

54

answers:

2

Hi,

I have a drawing application developed in winforms C# which uses many System.Drawing.Bitmap object throughout the code.

Now I am writing it into WPF with c#. I have done almost 90% of the conversion.

Coming to the problem... I have the following code which is used to traverse the image pixel by pixel

Bitmap result = new Bitmap(img); // img is of System.Drawing.Image
result.SetResolution(img.HorizontalResolution, img.VerticalResolution);
BitmapData bmpData = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.ReadWrite, img.PixelFormat);

int pixelBytes = System.Drawing.Image.GetPixelFormatSize(img.PixelFormat) / 8;
System.IntPtr ptr = bmpData.Scan0;

int size = bmpData.Stride * result.Height;
byte[] pixels = new byte[size];

int index = 0;
double R = 0;
double G = 0;
double B = 0;

System.Runtime.InteropServices.Marshal.Copy(ptr, pixels, 0, size);

for (int row = 0; row <= result.Height - 1; row++)
  {
   for (int col = 0; col <= result.Width - 1; col++)
   {
     index = (row * bmpData.Stride) + (col * pixelBytes);
     R = pixels[index + 2];
     G = pixels[index + 1];
     B = pixels[index + 0];
    .
    .// logic code
    .
    }
  }

result.UnlockBits(bmpData); 

It uses System.Drawing's for the purpose.

Is it possible to achieve this thing in wpf as well keeping it simple as it is?

+1  A: 

You can use BitmapImage.CopyPixels to copy the image your pixel buffer.

BitmapImage img= new BitmapImage(...); // This is your image

int bytePerPixel = (img.Format.BitsPerPixel + 7) / 8;
int stride = img.PixelWidth * bytesPerPixel;
int size = img.PixelHeight * stride;
byte[] pixels = new byte[size];

img.CopyPixels(pixels, stride, 0);

// Now you can access 'pixels' to perform your logic
for (int row = 0; row < img.PixelHeight; row++) 
{ 
   for (int col = 0; col < img.PixelWidth; col++) 
   { 
     index = (row * stride) + (col * bytePerPixel ); 
     ...
   } 
} 
Chris Taylor
Thanks. I am having trouble while calculating the index. [ index = (row * bmpData.Stride) + (col * pixelBytes);]??
Vinod Maurya
@Vinod, stride = img.PixelWidth * bytesPerPixel.
Chris Taylor
+1  A: 

In addtion to Chris's anwser you might want to look at WriteableBitmap. It's another way to manipulate images pixels.
Example

Walt Ritscher