如何下载图像URL切换到byte [] up并读取它WP8 c#


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();
}

相关内容

  • 没有找到相关文章

最新更新