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 !
}
my project is a Windows Phone 8.1 Runtime C# app .
There are couple of things you need to handle:
- 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);
}
}