我使用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;
我正在谷歌上搜索太多。但我找不到任何关于这个问题的消息来源。
答案 0 :(得分:0)
它显得很黑,因为你正在重写图像的整个内容,而不仅仅是几个像素。您的pixels
数组被声明为整个图像的大小,但您只设置了前四个字节的颜色数据中的两个。因此,当您调用WritePixels
时,它会使用提供者颜色数据重新绘制整个图像,这几乎全是0。
要纠正此问题,请仅将pixels
数组声明为您要写入的像素的大小。
答案 1 :(得分: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;