0

我使用 WriteableBitmap 在 Wpf 中设置像素。但是当我使用 writePixels 方法来更改像素的颜色时,它会将颜色更改为黑色:(。这是我的代码快照:

            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;

我在谷歌上搜索太多了。但我找不到有关此问题的任何来源。 在此处输入图像描述

4

2 回答 2

0

Finllay 我找到了解决方案:

            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;
于 2013-07-21T10:15:36.887 回答
0

它看起来是黑色的,因为您正在重写图像的全部内容,而不仅仅是几个像素。您的pixels数组被声明为整个图像的大小,但您只设置了颜色数据的前四个字节中的两个。因此,当您调用 时WritePixels,它会使用提供者颜色数据重新绘制整个图像,这些数据几乎全为 0。

要更正此问题,只需将pixels数组声明为您要写入的像素的大小。

于 2013-07-21T03:18:43.187 回答