2010-10-02 6 views
1

J'ai une application de dessin développée dans winforms C# qui utilise de nombreux objets System.Drawing.Bitmap dans tout le code.C# winforms code à C# code wpf

Maintenant, je l'écris dans WPF avec C#. J'ai fait près de 90% de la conversion.

En venant au problème ... Je le code suivant qui est utilisé pour traverser le pixel d'image par 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); 

Il utilise dans le but de System.Drawing.

Est-il possible de réaliser cette chose dans wpf aussi bien que cela reste simple comme il est?

Répondre

1

au addtion En anwser Chris vous pourriez vouloir regarder WriteableBitmap. C'est une autre façon de manipuler les pixels des images.
Example

1

Vous pouvez utiliser BitmapImage.CopyPixels pour copier l'image de votre tampon de pixels.

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

Merci. J'ai des problèmes lors du calcul de l'index. [index = (ligne * bmpData.Stride) + (col * pixelBytes);] ?? –

+0

@Vinod, stride = img.PixelWidth * octetsPerPixel. –