Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MAUI: Convert FileImageSource to byte[]

I want to convert an image read like this ImageSource.FromFile("hole_in_wall.jpg") to a byte[] so I can store the image in a database and use to byte[] later on to display the image.

I first tried this method I found in this post, but this did not work out for me becuase it could not convert FileImageSource to StreamImageSource.

public static async Task<byte[]> ImageSourceToByteArrayAsync(ImageSource imageSource)
{

    Stream stream = await ((StreamImageSource)imageSource).Stream(CancellationToken.None);
    byte[] bytesAvailable = new byte[stream.Length];
    stream.Read(bytesAvailable, 0, bytesAvailable.Length);

    return bytesAvailable;
}

I also tried most of the other answers but with little success.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

After that I tried to use this function:

public static async Task<byte[]> FileImageSourceToByteArrayAsync(FileImageSource fileImageSource)
{
    // Get the file path from the FileImageSource
    var filePath = fileImageSource.File;

    // Check if the file exists
    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"The file '{filePath}' does not exist.");
    }

    // Read the file into a byte array
    return await File.ReadAllBytesAsync(filePath);
}

The thing is when I read the image like above by using ImageSource.FromFile("filename") I get an exception in this function that filePath doesn’t exist. Which makes little sense because thats how I read images all the time. My image is an EmbeddedResource.

So I am looking for a specific answer how to read a local image from my resources folder and convert it to a byte[] which I can save and covert later on to an image to display it.

>Solution :

You can try to use the following code:

public static async Task<byte[]> ImageSourceToByteArrayAsync(ImageSource imageSource)
{

   var assem = Assembly.GetExecutingAssembly();
   using var stream = assem.GetManifestResourceStream("ProjectName.Resources.Images.test.png");
   byte[] bytesAvailable = new byte[stream.Length];
   stream.Read(bytesAvailable, 0, bytesAvailable.Length);
   return bytesAvailable;
}

The test.png is in the \Resources\Images and its build action is EmbeddedResource.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading