7

I have svg xml that i can convert to ImageSource or FileImageSource by using XamSVG library in the PCL project of my xamarin.forms.

I want to convert the ImageSource / FileImageSource to byte array (to get the bitmap).

Is this possible ?

asaf
  • 958
  • 1
  • 16
  • 38
  • Just refer https://stackoverflow.com/questions/27532462/is-there-a-cross-platform-solution-to-imagesource-to-byte/27532867#27532867 – Abdul Muhaymin May 23 '16 at 10:25
  • this link isn't what i need since i am not using the camera. all i have is image with imagesource that i want to get the bitmap (byte array) from it – asaf May 23 '16 at 13:02

3 Answers3

6

ImageSource doesn't expose any mechanism to retrieve the original image source. Instead, you will need to manually keep a reference to the original source you use to create the image.

Jason
  • 86,222
  • 15
  • 131
  • 146
  • I dont have original source - i have svg xml file that converts to imagefile, i need the byte array of the bitmap... – asaf May 23 '16 at 13:02
  • You will need to look at the XamSVG library to see if it produces an intermediary bitmap you can access, or modify it to produce one. – Jason May 23 '16 at 13:05
5

I've found the solution.

StreamImageSource streamImageSource  = (StreamImageSource) some image source...
System.Threading.CancellationToken cancellationToken = System.Threading.CancellationToken.None;
Task<Stream> task = streamImageSource.Stream(cancellationToken);
Stream stream = task.Result;
Rafael
  • 1,281
  • 2
  • 10
  • 35
asaf
  • 958
  • 1
  • 16
  • 38
  • and what is "a"? (3rd line) –  Aug 08 '16 at 14:28
  • a is streamImageSource – asaf Aug 09 '16 at 08:21
  • I juest tried that and I get: "Unable to cast object of type 'Xamarin.Forms.FileImageSource' to type 'Xamarin.Forms.StreamImageSource'." –  Aug 09 '16 at 08:26
  • 9
    This is not a solution - it only works if the `ImageSource` *is* of type `StreamImageSource`. It is not away to create an output stream of any `ImageSource` – noelicus Mar 20 '17 at 09:39
3

Another solution:

public static byte[] ReadFully(Stream input)
{
    using (MemoryStream ms = new MemoryStream())
    {
        input.CopyTo(ms);
        return ms.ToArray();
    }          
}

Stream and MemoryStream are System.IO classes.

Then use it like this:

byte[] TargetImageByte = ReadFully(_data.Source);

_data.source is MediaFile type.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Hix
  • 41
  • 1