我们在UWP,经常使用的图片,数据结构就是 BitmapImage 和 WriteableBitmap。关于 BitmapImage 和 WriteableBitmap 区别,我就不在这里说。主要说的是 BitmapImage 和 WriteableBitmap 、二进制 byte 的互转。
我们先写一个简单的xaml
<Image x:Name="Img" Height="200" Width="200"
HorizontalAlignment="Center" Source="Assets/SplashScreen.png" ></Image>
<Button Margin="10,300,10,10" Content="确定" Click="Button_OnClick" ></Button>
用到的图片是我新建自带的。
保存 WriteableBitmap 到文件
private static async Task SaveWriteableBitmapImageFile(WriteableBitmap image, StorageFile file)
{
//BitmapEncoder 存放格式
Guid bitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
string filename = file.Name;
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;
}
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
{
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);
//Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(imgstream);