在 Windows 运行时将文件缩略图另存为图像 [英] Save File Thumbnail as image in windows runtime
本文介绍了在 Windows 运行时将文件缩略图另存为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取存储在 Videos 文件夹中的文件的缩略图,并将它们作为图像保存在我的本地文件夹中.这是我获取文件的代码.
I want to get Thumbnail of files stored in Videos folder and save them as image in my local folder . here is my code to get files .
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# 应用程序.
my project is a Windows Phone 8.1 Runtime C# app .
推荐答案
您需要处理两件事情:
- 你不需要BitmapImage,因为缩略图提供了一个你可以直接写入文件的流,
- 您没有处理创建文件方法失败(文件存在)的情况,
- create folder 方法将抛出异常,因为文件夹是用 foreach 中的第一个文件创建的(或已经存在).而不是在 foreach 之外创建/打开文件夹,
- 还使用
file.Name
创建图像不是一个好主意,因此这些是视频,它们的扩展名可能是 mp4/mpg/other 而不是 jpg/png/其他, - 记得在 packageappx.manifest 文件中添加 capabilities.
- you don't need BitmapImage, as thumbnail provides a stream which you can write directly to file,
- you are not handling the case when create file method fails (file exists),
- create folder method will throw exception as the folder is created (or already exists) with the first file in foreach. Rather than that, create/open folder outside foreach,
- also creating image with
file.Name
is not a good idea, hence those are videos and their extension will likely be mp4/mpg/other not jpg/png/other, - remember to add capabilities in packageappx.manifest file.
我认为下面的代码应该可以完成这项工作:
I think the below code should do the job:
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);
}
}
这篇关于在 Windows 运行时将文件缩略图另存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文