Search code examples
xamarinxamarin.formsxamarin-studio

How to convert Image to ImageSource Xamarin.Form


Hey I have image generated in ZXingBarcodeImageView I want to convert that to ImageSource so I can bind the Image in xaml, How to achieve this, Good Day and Thank you

 public class GenerateCode: IGenerateCode
 {
    ZXingBarcodeImageView barcode;

    public ImageSource GenerateQr(string code)
    {
        barcode = new ZXingBarcodeImageView
        {
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.FillAndExpand,
        };
        barcode.BarcodeFormat = ZXing.BarcodeFormat.QR_CODE;
        barcode.BarcodeOptions.Width = 100;
        barcode.BarcodeOptions.Height = 100;
        barcode.BarcodeOptions.Margin = 10;
        barcode.BarcodeValue = code;
        return barcode; error as barcode is an image
    }
 }



<Image Source={Binding imgSource} />     

Solution

  • I presume that you are using a platform specific component to generate images. This component either stores the generated image into the filesystem or returns a binary representation in memory.

    To convert a file into an ImageSource, you would use ImageSource.FromFile(). To convert a stream, use ImageSource.FromStream().

    You can find the APIs here and some great documentation there.

    In your case above, the BindingContext (whether that's a page or a ViewModel does not matter) will have to expose a public property of type ImageSource and returns the converted image using either of the methods above.