0
votes

I use WriteableBitmap to set pixel in Wpf. but when I used writePixels method to change the color of pixels it's change color to black :(. It's my code snap:

            ofdOpen.ShowDialog();
            BitmapImage img = new BitmapImage(new Uri(ofdOpen.FileName));
            WriteableBitmap wbmap = new
            WriteableBitmap(img);
             byte[] pixels = new byte[
   wbmap.PixelHeight*wbmap.PixelWidth*
      wbmap.Format.BitsPerPixel/8];
       pixels[0] =255;
       pixels[1] = 0;
       pixels[2] = 0;
       pixels[3] = 255;
       wbmap.WritePixels(
        new Int32Rect(0, 0,
         wbmap.PixelWidth, wbmap.PixelHeight),
        pixels,
        wbmap.PixelWidth * wbmap.
            Format.BitsPerPixel / 8, 0);

            image1.Source = wbmap;

I'm googling too much. but I couldn't find any source about this problem. enter image description here

2

2 Answers

0
votes

It's appearing black because you're rewriting the entire contents of the image, not just a few pixels. Your pixels array is declared to be to be the size of the entire image, but you are only setting two of the first four bytes of color data. So, when you call WritePixels, it's redrawing the entire image with the provider color data, which is almost all 0's.

To correct this, only declare the pixels array to be the size of the pixels you want to write.

0
votes

Finllay I found solution:

            BitmapImage originalIamge = new BitmapImage();
        originalIamge.BeginInit();
        originalIamge.UriSource = new Uri(ofdOpen.FileName);
        originalIamge.EndInit();
        BitmapSource bitmapSource = new FormatConvertedBitmap(originalIamge, PixelFormats.Bgr32, null, 0);
        wbmap = new WriteableBitmap(bitmapSource);

        h = wbmap.PixelHeight;
        w = wbmap.PixelWidth;
        pixelData = new int[w * h];
        widthInByte = 4 * w;

        wbmap.CopyPixels(pixelData, widthInByte, 0);
        image1.Source = wbmap;
        Point absoluteScreenPos = PointToScreen(Mouse.GetPosition((IInputElement)sender));
        Image img = new Image();
        BitmapImage point = new BitmapImage(
                      new Uri("Images/Dott.png",
                              UriKind.Relative));
        img.Source = point;

        var rt = ((UIElement)image1).RenderTransform;

        var offsetX = rt.Value.OffsetX;

        var offsetY = rt.Value.OffsetY;
        int newX = (int)Mouse.GetPosition((IInputElement)sender).X;
        int newY = (int)Mouse.GetPosition((IInputElement)sender).Y;

        for (int i = 0; i < 400; i++)
        {
            pixelData[i] = 0x000000ff;
        }

        wbmap.WritePixels(new Int32Rect(newX,newY,10,10), pixelData, widthInByte, 0);

        image1.Source = wbmap;