简体   繁体   English

如何从硬盘上的Internet保存BitmapImage? (C#UniversalApp)

[英]How to save BitmapImage from Internet on hard drive? (C# UniversalApp)

This might sound simple but I'v noticed that it's not to me! 这听起来很简单,但我注意到这对我来说不是! I want to save a simple jpg or other format image from internet to hard drive. 我想将一个简单的jpg或其他格式的图像从Internet保存到硬盘。 I use the following code to get an image from the net. 我使用以下代码从网上获取图像。 How do I save it to HDD ? 如何将其保存到HDD?

BitmapImage posterBitmap = new BitmapImage(new Uri(imageLocationOnNet, UriKind.Absolute));

I'd appreciate lot if someone could give me a simple code example and explain how it works. 如果有人能给我一个简单的代码示例并解释其工作原理,我将不胜感激。
Preferably in C# and Windows Universal App compatible, thank you. 最好在C#和Windows Universal App兼容的情况下,谢谢。

EDIT. 编辑。 I'm also interested to know if it is possible to convert BitmapImage to JSON and read it back from there? 我也想知道是否有可能将BitmapImage转换为JSON并从那里读回?

I'm guessing the reason it doesn't seem simple to you is that you are looking in the wrong place 我猜这对您来说似乎并不简单的原因是您在错误的位置看

Bitmap source and Bitmap image are only for loading images, the saving functionality is in the encoder classed such as PngEncoder 位图源和位图图像仅用于加载图像,保存功能在编码器中分类,例如PngEncoder

once you have selected the correct encoder then you just need to add the image to it as a frame and then save it to a stream 一旦选择了正确的编码器,则只需将图像作为帧添加到其中,然后将其保存到流中

encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);

Found here . 这里找到。 When you create that image it takes some time to download it. 创建该图像时,需要花费一些时间来下载它。 You can check if it's downloading with 您可以检查是否正在下载

posterBitmap.IsDownloading

after it's done, add the handler 完成后,添加处理程序

posterBitmap.DownloadCompleted += posterBitmap_DownloadCompleted;

and then write the function to save the image 然后写函数保存图片

private void objImage_DownloadCompleted(object sender, EventArgs e)
{
  JpegBitmapEncoder encoder = new JpegBitmapEncoder();
  Guid photoID = System.Guid.NewGuid();
  String photolocation = photoID.ToString() + ".jpg";  //file name 

  encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender));

  using (var filestream = new FileStream(photolocation, FileMode.Create))
    encoder.Save(filestream);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM