显示,下载和保存jpeg图像从服务器到Windows Phone 8相机胶卷

时间:2014-02-27 12:49:15

标签: c# windows-phone-8

我正在尝试从特定网址检索图片,将其显示在我的图片框中,然后最终将其保存到我的相机胶卷。这是我尝试过但我得到一个目标调用异常。这表明了什么?

private void downloadImg()
    {
        String uri = "http://timenewsfeed.files.wordpress.com/2013/12/doge.jpg";
        Uri imgUri = new Uri(uri, UriKind.Absolute);
        ImageSource imgSource = new BitmapImage(imgUri);

        Dispatcher.BeginInvoke(() =>
        {
            imageBox.Source = imgSource;
        }
        );
            using (var mediaLibrary = new MediaLibrary())
            {
                using (var stream = new MemoryStream())
                {
                    Debug.WriteLine("trying to save photo...");
                    var fileName = "HELLOWORLD.jpg";
                    BitmapImage img = new BitmapImage(imgUri);
                    img.CreateOptions = BitmapCreateOptions.None;
                    img.ImageOpened += (s, e) =>
                    {
                        WriteableBitmap bmp = new WriteableBitmap((BitmapImage)s);
                        bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
                    };
                    stream.Seek(0, SeekOrigin.Begin);
                    Dispatcher.BeginInvoke(() =>
                    {
                        var picture = mediaLibrary.SavePicture(fileName, stream);
                    });
                    // or to cameraroll
                    Debug.WriteLine("photo saved");
                }
            }

    }

1 个答案:

答案 0 :(得分:1)

我发现您的代码至少存在一个潜在问题。我看到的主要问题是你的方法执行的顺序,当你试图保存它时可能导致流为空。您对填充流的ImageOpened进行处理,但该回调是异步执行的。换句话说,这个

stream.Seek(0, SeekOrigin.Begin);
Dispatcher.BeginInvoke(() =>
  {
      var picture = mediaLibrary.SavePicture(fileName, stream);
  });

可以在此之前执行

WriteableBitmap bmp = new WriteableBitmap((BitmapImage)s);
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);

如果您将用于保存的逻辑移到了ImageOpened处理程序,它可能会解决问题。所以你有这样的东西......

img.ImageOpened += (s, e) =>
  {
      WriteableBitmap bmp = new WriteableBitmap((BitmapImage)s);
      bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);

      stream.Seek(0, SeekOrigin.Begin);
      Dispatcher.BeginInvoke(() =>
      {
          var picture = mediaLibrary.SavePicture(fileName, stream);
      });
  };