Convert 'Xamarin.Form.Image' type 'byt

2019-08-06 08:52发布

问题:

I am supposed to get an Image from a url and convert it into byte[]. The following is what I achieved

var webImage = new Image { Aspect = Aspect.AspectFit };
webImage.Source = ImageSource.FromUri(new    Uri("http://xamarin.com/content/images/pages/forms/example-app.png"));

but now I am unable to convert the Image type to byte[].

Is this the correct way to approach? Any kind of help would be appreciated.

回答1:

I haven't tried this but from my initial thought you will need a Stream. For that you could use StreamImageSource

From there you can use the code from this.



回答2:

Xamarin.Forms inside it uses IImageSourceHandler which has realizations like

  • ImageLoaderSourceHandler - for UriImageSource
  • StreamImagesourceHandler - for StreamImageSource
  • and so on

For reading data from UriImageSource You should use ImageLoaderSourceHandler which is platform class. So under each platform use code like

var handler = new ImageLoaderSourceHandler();
var uiimage = await handler.LoadImageAsync(source, new CancellationToken(), UIScreen.MainScreenScale);

Then you can reach any data from UIImage under iOS or from Bitmap under Android. There are a lot of tutorials how to get byte[] from them.



回答3:

FFImageLoading (https://github.com/molinch/FFImageLoading/) CachedImage has GetImageAsJPG and GetImageAsPNG methods. It's a direct Xamarin.Forms Image class replacement with a lot of additional features.

Here's the code used for image retrieving (it can be used in a Image class custom renderers):

  • Android
  • iOS
  • Windows


回答4:

It's posible to use WebClient to obtain byte array from a URL.

var webClient = new WebClient ();
byte[] byteImage = webClient.DownloadData (imageURL);