简体   繁体   中英

How to convert Image to Bitmap or Byte Array

I want to translate an Image into a MemoryStream or an array of bytes, but this does not work, I used to translate in Windows Forms in the same way as I did in Xamarin.Forms?

MemoryStream ms = new MemoryStream();
img.Save(ms, img.Image.RawFormat);
byte[] byteimg = ms.ToArray();

Unlike Windows.Forms or WPF where the Image class has direct access to pixels and can provide the entirety of image manipulation APIs, Image class in Xamarin Forms is just an abstraction for multiple platform views across OSes (Android, iOS, macOS etc.) It provides limited capabilities when compared to any of the platform controls and basically is tasked with creating a platform view, loading picture from one of predefined sources (embedded resource, file, byte stream etc.), placing it somewhere in the visual tree. That's it, XF Image class is not tasked with low level pixel manipulation and doesn't provide access to the actual bit data of a native image. You won't find methods that give you access to pixel and as such don't allow you to create a Stream from a loaded into memory byte data.

In order to get access to individual bytes you can:

  • Look at the direction of 3rd party controls, that provide access to pixels. EG you can use Skia and use it's Canvas
  • Trace the source XF Image (file, resource) and load it into memory as .NET stream
  • Write own native code for any of the target platforms (eg create a platform service and use dependency service OR create own visual element with platform renderers) which will have access to image data of native image view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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