最近做一个小app遇到一个问题,到目前还没有比较好的解决方法(可能是我查的资料不够多)

需求如下:

1.把一个Image中的图像保存到字节数组;

2.把字节数组转换为ImageSource,通过Image控件展示图像.

上面两个需求恰恰是相反的过程,为了实现这个,我倒网上找了好多,但基本都是wp7,wp8,wpf的方案,在win10上没法用。。纠结。

后来在知乎日报uwp的源码中发现了一个把ImageSource存储为文件的方法。(github:https://github.com/sherlockchou86/ZhiHuDaily.UWP),感谢作者为win10生态圈的贡献。

代码如下:

public async Task SaveImageAsync(WriteableBitmap image, string filename)
        {
            try
            {
                if (image == null)
                {
                    return;
                }
                Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                if(filename.EndsWith("jpg"))
                        BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                else if(filename.EndsWith("png"))
                        BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
                else if(filename.EndsWith("bmp"))
                        BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
                else if(filename.EndsWith("tiff"))
                        BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
                else if(filename.EndsWith("gif"))
                        BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
                var folder = await _local_folder.CreateFolderAsync("images_cache", CreationCollisionOption.OpenIfExists);
                var file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
                    Stream pixelStream = image.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                              (uint)image.PixelWidth,
                              (uint)image.PixelHeight,
                              96.0,
                              96.0,
                              pixels);
                    await encoder.FlushAsync();
                }
            }
            catch
            {

            }
        }
SaveImageAsync

相关文章: