我正在开发一个UWP Windows 10的图像处理应用程序。我正在使用文件选择器打开图像,如下所示:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.FileTypeFilter.Clear();
openPicker.FileTypeFilter.Add(".bmp");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".jpg");
StorageFile file = await openPicker.PickSingleFileAsync();
if(file!=null)
{
IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
myImage.Source = bitmapImage;
// code to retrieve bytes of bitmap image
}
在上述的if语句中,我会像下面展示的那样从这张图片中检索字节。
//Fetching pixel data
using (IRandomAccessStream fileStreams = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStreams);
BitmapTransform transform = new BitmapTransform()
{
ScaledWidth = Convert.ToUInt32(bitmapImage.PixelWidth),
ScaledHeight = Convert.ToUInt32(bitmapImage.PixelHeight)
};
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.IgnoreExifOrientation,// This sample ignores Exif orientation
ColorManagementMode.DoNotColorManage
);
// byte[] , a global variable
sourcePixels = pixelData.DetachPixelData();
// uint , a global variable
width = decoder.PixelWidth;
// uint , a global variable
height = decoder.PixelHeight;
}
现在我需要操作这个字节数组以生成不同的效果。但是为了测试目的,我将这个字节数组再次转换为位图图像,并将其值设置为主图像源(在按钮点击事件中)。但是它没有正确地工作。
WriteableBitmap scaledImage = new WriteableBitmap((int)width, (int)height);
using (Stream stream = scaledImage.PixelBuffer.AsStream())
{
await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
myImage.Source = scaledImage;
}
打开图片时,它是这样的。
将其转换为字节数组并将字节数组转换为图像源后再次应用时,它会改变图像颜色,尽管我没有更改字节数组的任何值。
问题出在哪里?转换为字节数组的位置不对还是字节数组转换为位图的位置有误?