为什么在访问WriteableBitmap图像中的像素时发生AccessViolationException?

为什么在访问WriteableBitmap图像中的像素时发生AccessViolationException?

问题描述:

我有一个视频流从相机到WPF中的图像。我正在尝试在显示它之前逐个像素地访问WritableBitMap图像。作为一项测试,我试图将整个图像设置为白色或黑色。但是,在这两种情况下,我都会遇到AccessViolationException错误。为什么在访问WriteableBitmap图像中的像素时发生AccessViolationException?

我查了其他帖子,似乎这个错误是非常广泛的,而不是针对我的情况。我似乎无法知道为什么我没有得到这个工作。

那么在我的情况下玩像素的最佳方式是什么?或为什么这不起作用?任何帮助表示赞赏

 private async void UpdateMasterCameraPreview(IdsFrame frame) 
    { 
     if (masterImage != null) 
      frame.Image.CopyTo(masterImage); 
     else 
      masterImage = frame.Image.ToWriteableBitmap(); 

     //BitmapImage temp = ConvertWriteableBitmapToBitmapImage(masterImage); 
     WriteableBitmap temp = masterImage; 

     // Here I get the exception, on every pixel access 
     for (int y = 0; y < temp.PixelHeight; y++) 
      for (int x = 0; x < temp.PixelWidth; x++) 
       temp.SetPixel(x, y, 255); 

     masterImage = temp; 

     masterImage.Lock(); 
     masterImage.AddDirtyRect(new Int32Rect(0, 0, masterImage.PixelWidth, masterImage.PixelHeight)); 
     masterImage.Unlock(); 

     if (OnMasterFrameCaptured != null) 
      OnMasterFrameCaptured(this, new CameraFrameCapturedArgs(CameraType.Master, masterImage)); 
    } 
+0

还请包括临时变量声明。 –

+0

我刚刚做到了。谢谢 –

我结束了使用this后的回答。现在我可以在将任何WriteableBitmap图像的原始像素数据发送给WPF中的图像控件之前编辑它。下面是我究竟使用,但在这里,我只是每帧转换为某种透明的条件下:

 public void ConvertImage(ref WriteableBitmap Wbmp) 
    { 
     int width = Wbmp.PixelWidth; 
     int height = Wbmp.PixelHeight; 
     int stride = Wbmp.BackBufferStride; 
     int bytesPerPixel = (Wbmp.Format.BitsPerPixel + 7)/8; 

     unsafe 
     { 
      byte* pImgData = (byte*)Wbmp.BackBuffer; 

      // set alpha to transparent for any pixel with red < 0x88 and invert others 
      int cRowStart = 0; 
      int cColStart = 0; 
      for (int row = 0; row < height; row++) 
      { 
       cColStart = cRowStart; 
       for (int col = 0; col < width; col++) 
       { 
        byte* bPixel = pImgData + cColStart; 
        UInt32* iPixel = (UInt32*)bPixel; 

        if (bPixel[2 /* bgRa */] < 0x44) 
        { 
         // set to 50% transparent 
         bPixel[3 /* bgrA */] = 0x7f; 
        } 
        else 
        { 
         // invert but maintain alpha 
         *iPixel = *iPixel^0x00ffffff; 
        } 

        cColStart += bytesPerPixel; 
       } 
       cRowStart += stride; 
      } 
     } 
    } 

,并用它的常规是这样的:

 masterImage.Lock(); 
     ConvertImage(ref masterImage); 
     masterImage.AddDirtyRect(new Int32Rect(0, 0, masterImage.PixelWidth, masterImage.PixelHeight)); 
     masterImage.Unlock(); 

你交换X和Y,我代表高度,j表示宽度,那么你shouldcall SetPixel喜欢:

temp.SetPixel(j, i, 255); 

在这样的情况下,最好使用有意义的名称变量,如X和Y.

+0

你是对的,我也只是看过函数原型。我换了它们,但是,但是,我仍然得到相同的错误,AcessViolationException –

+0

SetPixel不是WriteableBitmap的一部分,所以你有一个扩展或组件,发布函数的代码。 – Gusman

+0

但我们都只是用它。它怎么不是WritableBitmap的一部分? –