问题描述
我目前正在尝试将包含我从相机返回的 jpeg 图像的流保存到本地存储文件夹.正在创建文件,但不幸的是根本不包含任何数据.这是我尝试使用的代码:
I'm currently trying to save an stream containing a jpeg image I got back from the camera to the local storage folder. The files are being created but unfortunately contain no data at all. Here is the code I'm trying to use:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteBytes(UsefulOperations.StreamToBytes(file));
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
public static class UsefulOperations
{
public static byte[] StreamToBytes(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
以这种方式保存文件的任何帮助将不胜感激 - 我在网上找到的所有帮助都是指保存文本.我正在使用 Windows.Storage 命名空间,因此它也应该适用于 Windows 8.
Any help saving files this way would be greatly appreciated - all help I have found online refer to saving text. I'm using the Windows.Storage namespace so it should work with Windows 8 too.
推荐答案
您的方法 SaveToLocalFolderAsync
运行良好.我在我传入的 Stream
上试用了它,它按预期复制了其完整内容.
Your method SaveToLocalFolderAsync
is working just fine. I tried it out on a Stream
I passed in and it copied its complete contents as expected.
我猜这是您传递给该方法的流状态的问题.也许你只需要事先用 file.Seek(0, SeekOrigin.Begin);
将它的位置设置到开头.如果这不起作用,请将该代码添加到您的问题中,以便我们为您提供帮助.
I guess it's a problem with the state of the stream that you are passing to the method. Maybe you just need to set its position to the beginning beforehand with file.Seek(0, SeekOrigin.Begin);
. If that doesn't work, add that code to your question so we can help you.
此外,您可以使代码更简单.如果没有中间类,以下内容完全相同:
Also, you could make your code much simpler. The following does exactly the same without the intermediate classes:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}
这篇关于将包含图像的流保存到 Windows Phone 8 上的本地文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!