Tom Coldenhoff
Tom Coldenhoff

Reputation: 138

Is there a solution to convert an ImageSource to an Android Bitmap and vice-versa in Xamarin.Forms

I'm currently working on an application that modifies a picture that is currently located in the PCL project. And I'm currently having trouble with converting the DataTypes.

I'm currently trying to figure out how I can convert an ImageSource to a bitmap. I've read some answers on the internet but they didn't seem to work for me.

I call the platform-specific code with a DependencyService and pass the ImageSource as a parameter.

The function signature looks like this:

        public ImageSource BlurImage(ImageSource ImageSource)
        {

            return null;
        }

This function should Create a bitmap from the ImageSource first and once all the logic has been done it should convert back to an ImageSource.

Can someone explain to me how I should convert ImageSource to bitmap and vice-versa?

Thanks in advance, Tom

Upvotes: 1

Views: 1247

Answers (1)

FreakyAli
FreakyAli

Reputation: 16562

You can use the below function to convert ImageSource to Bitmap:

 private async Task<Bitmap> GetImageFromImageSource(ImageSource imageSource, Context context)
    {
        IImageSourceHandler handler;

        if (imageSource is FileImageSource)
        {
            handler = new FileImageSourceHandler();
        }
        else if (imageSource is StreamImageSource)
        {
            handler = new StreamImagesourceHandler(); // sic
        }
        else if (imageSource is UriImageSource)
        {
            handler = new ImageLoaderSourceHandler(); // sic
        }
        else
        {
            throw new NotImplementedException();
        }

        var originalBitmap = await handler.LoadImageAsync(imageSource, context);         

        return originalBitmap;
    }

And the Next one for Bitmap to ImageSource:

public async Task<ImageSource> GetBytesFromImage(Bitmap bitmap)
 {
    ImageSource imgSource;
    using (var stream = new MemoryStream())
    {
        bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); // You can change the compression asper your understanding
        imgSource=ImageSource.FromStream(stream);
    }
   return imgSource;
  }

Upvotes: 2

Related Questions