Home > Back-end >  How does ImageSource return bytes to the application
How does ImageSource return bytes to the application

Time:09-22

I would like to implement my own subclass of ImageSource. Xamarin Forms has FileImageSource, UriImageSource and several other subclasses of ImageSource, but none of them meets my needs.

To see how to implement an ImageSource subclass, I looked at implementation of FileImageSource on github (https://github.com/xamarin/Xamarin.Forms/blob/5.0.0/Xamarin.Forms.Core/FileImageSource.cs)

I expected to find that the subclass would override one or more ImageSource methods to actually read the image file and provide the bytes from the file to the calling platform. But source code of FileImageSource contains no such thing! In fact, they use the File only to override ImageSource.IsEmpty. How can this be? If an image is contained in a file, you need to read the file to display this image, don't you?

What am I missing? And if I want to implement my own subclass of ImageSource, how can my sublass return image data to the platform?

Edit Thank you to everyone who proposed solving the issue in a different way and inquiring why exactly existing ImageSource subclasses do not serve my needs.

Even if there is a different way to solve my immediate issue, from an educational perspective it is still interesting to know how Xamarin Forms displays an image file without reading the file. The source code for FileImageSource is quite short and does not appear to use the file, other than to implement IsEmpty. This will bug me until I know how this works.

CodePudding user response:

[Resolve the issue using converters]

Instead of creating a new ImageSource, you could create a Converter (if you are working with bindings).

So if you have something like a byte array, and you want that to be shown as an image, you can do the conversion from byte array into a StreamImageSource

[EDIT: Knowing how it works]

If you want to know how it works internally and how it transforms the File into the actual Image, you will have to go deeper into the code, and check the platform implementations. For example here you have the android renderers. You will find the IImageSourceHandler.cs and the FontImageSourceHandler and the FileImageSourceHandler and so on.

  • Related