for (int i = 3; i < 10; i++)
{
Uri uriimg = new Uri("http://i.msdn.microsoft.com/dynimg/IC53593" + i + ".jpg", UriKind.RelativeOrAbsolute);
SaveToLocalStorage(ImageToArray(uriimg), "anh1.jpg");
}
private byte[] ImagesToArray(Uri uriimg)
{
var image = new BitmapImage(uriimg);
MemoryStream ms = new MemoryStream();
image.ImageOpened += (s, e) =>
{
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
};
return ms.ToArray();
}
public async void SaveToLocalStorage(byte[] _imageBytes, string fileName)
{
if (_imageBytes == null)
{
return;
}
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists("dataImages"))
{
isoFile.CreateDirectory("dataImages");
}
string filePath = System.IO.Path.Combine("dataImages", fileName);
using (var stream = isoFile.CreateFile(filePath))
{
await stream.WriteAsync(_imageBytes, 0, _imageBytes.Length);
}
}
public ImageSource LoadFromLocalStorage(string fileName)
{
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
ImageSource imageSource = null;
if (isoFile.DirectoryExists("dataImages"))
{
string filePath = System.IO.Path.Combine("dataImages", fileName);
using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
imageSource = PictureDecoder.DecodeJpeg(imageStream);
}
}
return imageSource;
}
我得到的值为byte [0]
,它不能转换为byte []
。
我看到的问题是在ImagesToArray
。您创建一个新的MemoryStream
,订阅一个设置它的事件,然后立即返回它。我很确定ms
返回时将有0字节。
您不应该使用image.ImageOpened
,而只需将该代码直接放在ImagesToArray
方法中:
private byte[] ImagesToArray(Uri uriimg)
{
var image = new BitmapImage(uriimg);
MemoryStream ms = new MemoryStream();
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
return ms.ToArray();
}