图像的解码与编码

本文介绍了UWP中使用BitmapDecoder和BitmapEncoder进行图像解码和编码的详细过程。通过示例展示了如何解码GIF图像并显示每一帧,以及如何将照片重新编码为PNG格式并保存。解码时利用BitmapDecoder获取帧数据,编码时使用BitmapEncoder写入像素数据。
摘要由CSDN通过智能技术生成

尽管使用BitmapImage等类型可以对图像文件进行解码,但是,如果图像文件包含多个帧(如Gif图像一般包含多个帧),或者需要对图像进行修改后并保存为新的文件,那么BitmapImage类是无法胜任的。因此在实际开发中,是需要用到图像的编码与解码技术的。

1. 图像解码

对图像文件进行解码需要使用BitmaDecoder类(位于Windows.Graphics.Imaging命名空间),该类包装了图像解码的一系列功能。

下面将用示例来演示如何对Gif图像文件进行解码,并显示Gif文件中各个帧的图像。

应用程序页面上的XAML代码如下:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button Content="解码图像" Tapped="Button_Tapped"/>
        <ListView x:Name="lvimgs" Grid.Row="1" Margin="1,6" ScrollViewer.HorizontalScrollMode="Disabled"
                  ScrollViewer.VerticalScrollMode="Auto">
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsWrapGrid Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Image MaxWidth="100" MaxHeight="100" Stretch="Uniform" Source="{Binding}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="Margin" Value="12"/>
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>
    </Grid>

然后向应用程序项目中添加一个Gif图像文件,然后处理Button的Tapped事件处理程序,对Gif图像文件进行解码,并显示每一帧的图像。

        private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button btn = sender as Button;
            btn.IsEnabled = false;
            //项目中的图像文件
            Uri gifuri = new Uri("ms-appx:///Assets/sample.gif");
            StorageFile gifFile = await StorageFile.GetFileFromApplicationUriAsync(gifuri);
            using (IRandomAccessStream inputStream = await gifFile.OpenReadAsync())
            {
                //创建图像解码器实例
                BitmapDecoder decoder = await BitmapD
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值