2010-10-02 57 views
1

我有一个绘图应用程序在winforms C#开发,它在整个代码中使用许多System.Drawing.Bitmap对象。C#winforms代码到C#wpf代码

现在我正在用c#将它写入WPF。我已经完成了近90%的转换。

来到这个问题......我有被使用的像素

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); 

它使用System.Drawing中的为宗旨,以遍历图像像素下面的代码。

是否可以在wpf中实现这个功能,并保持简单?

回答

1

除了Chris的anwser,你可能想看看WriteableBitmap。这是处理图像像素的另一种方法。
Example

1

您可以使用BitmapImage.CopyPixels来复制像素缓冲区中的图像。

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

谢谢。我在计算索引时遇到了麻烦。 [index =(row * bmpData.Stride)+(col * pixelBytes);] ?? – 2010-10-02 08:58:19

+0

@Vinod,stride = img.PixelWidth * bytesPerPixel。 – 2010-10-02 09:28:43