• UWP 保存音乐或视频缩略图图片到本地


     开发项目时,有时需要将本地媒体文件的缩略图保存到本地,下面是源码。

    需要打开Package.appxmanifest 功能 图片库 访问权限。

    <Page
        x:Class="SaveBitmap.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:SaveBitmap"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Image x:Name="image"/>
            <Button x:Name="filePicker_bt" Grid.Row="1" Content="FelePicker" Tapped="filePicker_bt_Tapped" HorizontalAlignment="Left"/>
            <Button x:Name="savePicture_bt" Grid.Row="1" Content="SavePicture" Tapped="savePicture_bt_Tapped" HorizontalAlignment="Right"/>
        </Grid>
    </Page>
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using System.Threading.Tasks;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Graphics.Display;
    using Windows.Graphics.Imaging;
    using Windows.Storage;
    using Windows.Storage.FileProperties;
    using Windows.Storage.Pickers;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Media.Imaging;
    using Windows.UI.Xaml.Navigation;
    
    // https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板
    
    namespace SaveBitmap
    {
        /// <summary>
        /// 可用于自身或导航至 Frame 内部的空白页。
        /// </summary>
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
            private StorageFile save_file;
            private async void filePicker_bt_Tapped(object sender, TappedRoutedEventArgs e)
            {
                FileOpenPicker file_picker = new FileOpenPicker();
                file_picker.FileTypeFilter.Add(".mp4");
                file_picker.FileTypeFilter.Add(".mp3");
                save_file = await file_picker.PickSingleFileAsync();
                try//防止专辑图片为空
                {
                    using (var thumbnail = await save_file.GetThumbnailAsync(ThumbnailMode.MusicView, 200))//获取媒体专辑image
                    {
                        var video_cover = new BitmapImage();
                        video_cover.SetSource(thumbnail);
                        image.Source = video_cover;
                    }
                }
                catch
                {
                }
            }
    
            private async void savePicture_bt_Tapped(object sender, TappedRoutedEventArgs e)
            {
                try
                {
                    await SaveImage(save_file, image);
                    bool result = await Windows.System.Launcher.LaunchFolderAsync(saved_folder);
                }
                catch (Exception error)
                {
                    var message = new MessageDialog(error.ToString());
                    await message.ShowAsync();
                }
                
            }
    
            private StorageFolder saved_folder;
            private async Task<StorageFile> SaveImage(StorageFile file,Image image)
            {
                string desiredName = file.DisplayName + ".jpg";
                saved_folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("Saved Picture", CreationCollisionOption.OpenIfExists);
                var saveFile = await saved_folder.CreateFileAsync(desiredName, CreationCollisionOption.GenerateUniqueName);
                try
                {
    
                    RenderTargetBitmap bitmap = new RenderTargetBitmap();
                    await bitmap.RenderAsync(image);
                    var pixelBuffer = await bitmap.GetPixelsAsync();
                    using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                            BitmapAlphaMode.Ignore,
                             (uint)bitmap.PixelWidth,
                             (uint)bitmap.PixelHeight,
                             DisplayInformation.GetForCurrentView().LogicalDpi,
                             DisplayInformation.GetForCurrentView().LogicalDpi,
                             pixelBuffer.ToArray());
                        await encoder.FlushAsync();
                    }
                }
                catch
                {
                }
                return saveFile;
            }
        }
    }
    

    运行截图

    源码链接https://github.com/singhwong/Save-Bitmap-uwp.git

  • 相关阅读:
    insert 语句后面的一些参数使用知识
    mysql通信协议的半双工机制理解
    整理超级全局变量与全局变量的知识
    php获取输入流
    插入数据sql使用“insert into set”形式的理解
    《LINUX与UNIX SHELL编程指南》学习笔记
    转载别人空间的一篇好文技术没有转换成生产力
    C# 查找打开的窗口
    sql:inner join,left join,right join,full join的用法及含义
    pc doctor启动到进度条的时候自动退出
  • 原文地址:https://www.cnblogs.com/singhwong/p/11918458.html
Copyright © 2020-2023  润新知