Marcos
Marcos

Reputation: 11

Convert Image (from drawable folder) to ByteArray

So, I'm stuck with smth on my code. I'm trying to create a Share button inside my App to share some images to other Apps.

A friend from work shared with me the same code he uses, he get the bytearray of a image and pass it to a DependencyService, but he already has his images in ByteArray, in my case, my images are all stored inside Resources/drawable folder.

What we tried to do but couldn't was to get an image from drawable folder and convert it to ByteArray.

private void ShareImage(object sender, EventArgs e)
{
    //Convert img to ByteArray


    //ShareWindow
    DependencyService.Get<IShare>().Share("", "", buffer);
}

For example, how would I convert an image called "MyImage1.png" that's inside "Resources/drawable" (on both Android and iOS projects) to ByteArray? Looks like it's the only thing missing for this button to work.

Thank you!

Upvotes: 0

Views: 1290

Answers (1)

SushiHangover
SushiHangover

Reputation: 74209

You can call these via a DependencyService.

Android

public byte[] DrawableByNameToByteArray(string fileName)
{
    var context = Application.Context;
    using (var drawable = Xamarin.Forms.Platform.Android.ResourceManager.GetDrawable(context, fileName))
    using (var bitmap = ((BitmapDrawable)drawable).Bitmap)
    {
        var stream = new MemoryStream();
        bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
        bitmap.Recycle();
        return stream.ToArray();
    }
}

iOS

public byte[] iOSBundleResourceByNameToByteArray(string fileName)
{
    using (var image = UIImage.FromFile(fileName))
    using (NSData imageData = image.AsPNG())
    {
        var byteArray = new byte[imageData.Length];
        System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, byteArray, 0, Convert.ToInt32(imageData.Length));
        return byteArray;
    }
}

Note: Passing byte[] around is very inefficient, streams are better, but since you are using a native "sharing" feature, you are best off using the original file.

Upvotes: 2

Related Questions