天天看點

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;
        }
    }
}
           

運作截圖

UWP 儲存音樂或視訊縮略圖圖檔到本地

源碼連結https://github.com/singhwong/Save-Bitmap-uwp.git