【发布时间】:2019-11-18 07:28:36
【问题描述】:
我有3种存储文件,照片,视频和音频,我想将它们作为字节数组保存到数据库中。我尝试这样做并且成功了,但是当我将它们从byte[] 转换回StorageFile,然后我尝试获取他们的缩略图时,我得到的只是一个白色文件图标,而不是正确的缩略图图像。
StorageFile 到 Byte[]:
public static async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
if (file is null)
{
return null;
}
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}
byte[] 到 StoragFile:
public static async Task<StorageFile> GetStorageFileAsync(byte[] byteArray, string fileName)
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sampleFile, byteArray);
return sampleFile;
}
所以我在我的数据库中创建了一个新列,并认为我可以将我的缩略图作为字节 [] 单独存储在其中。
public static async Task<byte[]> GetBytesForImageAsync(StorageFile mediafile)
{
WriteableBitmap bb = null;
using (var imgSource = await mediafile.GetScaledImageAsThumbnailAsync(ThumbnailMode.VideosView, Constants._thumbnailReqestedSize, ThumbnailOptions.UseCurrentScale))
{
if (!(imgSource is null))
{
bb = new WriteableBitmap(Convert.ToInt32(imgSource.OriginalWidth), Convert.ToInt32(imgSource.OriginalHeight));
await bb.SetSourceAsync(imgSource);
}
}
return bb is null ? new byte[] { } : bb.PixelBuffer.ToArray();
}
我尝试使用BitmapImage 和WriteableBitmapImage 执行此操作,但是当我尝试从该字节中取回缩略图时,没有任何效果[]
带位图:
public async static Task<BitmapImage> GetImageFromBytesAsync(byte[] bytes)
{
var image = new BitmapImage();
using (var stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(bytes.AsBuffer());
stream.Seek(0);
await image.SetSourceAsync(stream);
}
return image;
}
与writeableBitmap:
public static async Task<WriteableBitmap> GetImageFromBytesAsync(byte[] bytes)
{
using (var image = bytes.AsBuffer().AsStream().AsRandomAccessStream())
{
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
return output;
}
}
最终,我的目标是使用 FileOpenPicker 从本地设备中挑选音频、视频或照片文件(这也是我目前正在做的事情),然后将这些文件保存到 SQL Server 以及稍后从我的 web api 获取它们时我想使用它们(播放音频或视频并显示图像),并且在所有 3 种类型中,我都需要在我的网格视图中显示缩略图。
【问题讨论】:
标签: c# sql-server image uwp storagefile