开发者

C# winforms code to c# wpf code

I have a drawing application developed in winforms C# which uses many System.Drawing.Bitmap object throu开发者_StackOverflow社区ghout 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?


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


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 ); 
     ...
   } 
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜