win10 uwp 读取保存WriteableBitmap 、BitmapImage

这篇博客介绍了在UWP中如何处理BitmapImage和WriteableBitmap,包括它们的互转、保存加载、转换为byte数组、从文件读取和保存,以及获取图片中鼠标点击颜色和Dpi的方法。提供了相关的代码示例和资源链接。
摘要由CSDN通过智能技术生成

我们在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);
   
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值