将BitmapImage转换为字节数组并反之。

3

我正在开发一个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;
            }

打开图片时,它是这样的。
enter image description here
将其转换为字节数组并将字节数组转换为图像源后再次应用时,它会改变图像颜色,尽管我没有更改字节数组的任何值。
enter image description here
问题出在哪里?转换为字节数组的位置不对还是字节数组转换为位图的位置有误?

3
似乎 b/g/r 被交换了,尝试使用 BitmapPixelFormat.Bgra8 替代。 - Hans Passant
1个回答

1
解决方案: 好的,我已经找到了这个问题的解决方案,原因是在 PixelDataProvider 中(获取像素数据时)我使用的是 BitmapPixelFormat.Rgba8,而应该使用 BitmapPixelFormat.Bgra8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接