在Windows运行时中将文件缩略图另存为图像

阿里·恩加梅(Ali Ngame)

我想获取存储在“视频”文件夹中的文件的缩略图,并将它们另存为本地文件夹中的图像。这是我获取文件的代码。

var v = await KnownFolders.VideosLibrary.GetFilesAsync();
foreach (var file in v)
{
    var thumb = await file.GetScaledImageAsThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem);
    BitmapImage Img = new BitmapImage();
    Img.SetSource(thumb);
    await ApplicationData.Current.LocalFolder.CreateFolderAsync("VideoThumb");
    var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
              "VideoThumb\\" + file.Name, CreationCollisionOption.FailIfExists);
    var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
    //I don't know how to save thumbnail on this file !
}

我的项目是Windows Phone 8.1运行时C#应用程序。

罗马斯

您需要处理以下几件事:

  • 您不需要BitmapImage,因为缩略图提供了可以直接写入文件的流,
  • 您无法处理创建文件方法失败(文件存在)的情况,
  • 当使用foreach中的第一个文件创建(或已经存在)文件夹时,create folder方法将引发异常。而是在foreach外部创建/打开文件夹,
  • 同时创建图片file.Name也不是一个好主意,因此,这些都是视频,其扩展名可能是mp4 / mpg / other而不是jpg / png / other
  • 请记住packageappx.manifest文件中添加功能

我认为以下代码可以完成这项工作:

private async Task SaveViedoThumbnails()
{
    IBuffer buf;
    StorageFolder videoFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("VideoThumb", CreationCollisionOption.OpenIfExists);
    Windows.Storage.Streams.Buffer inputBuffer = new Windows.Storage.Streams.Buffer(1024);

    var v = await KnownFolders.VideosLibrary.GetFilesAsync();
    foreach (var file in v)
    {
        var thumb = await file.GetScaledImageAsThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem);
        var imageFile = await videoFolder.CreateFileAsync(file.DisplayName + ".jpg", CreationCollisionOption.ReplaceExisting);
        using (var destFileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
            while ((buf = (await thumb.ReadAsync(inputBuffer, inputBuffer.Capacity, Windows.Storage.Streams.InputStreamOptions.None))).Length > 0)
                await destFileStream.WriteAsync(buf);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章