Search code examples
c#maui

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.

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()
    {
    
       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.