I'm trying to use ZXing.Net.Mobile to display a QR code as an image.
I'm having difficulty getting the byte[]
returned from BarcodeWriter.Writer(...)
into an image for display.
ie this does not display an image
public class BarcodePage : ContentPage
{
public BarcodePage()
{
Image image = new Image();
image.Source = ImageSource.FromStream(() =>
{
var writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = 200,
Width = 600
}
};
var bitmapBytes = writer.Write ("Some text");
return new MemoryStream(bitmapBytes);
});
Content = image;
}
}
The bitmapBytes
byte array looks like it has reasonable values in the debugger, how can I turn that into an image for display?
If I change the Image.Source assignment to:
image.Source = ImageSource.FromUri(new Uri("http://i.imgur.com/q0aIYvC.png"));
then it does correctly display the image, so I know the problem isn't with the Forms layout, etc.
Workaround
At the moment, I'm doing conversion to a MemoryStream in the native, eg in Android I have:
public class BuildQrCodes_Android : IBuildQrCodes
{
public async Task<MemoryStream> ImageStreamForAsync(string text)
{
var writer = new BarcodeWriter
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = 600,
Width = 600
}
};
var bitmap = writer.Write(text);
var stream = new MemoryStream();
await bitmap.CompressAsync(Bitmap.CompressFormat.Png, 100, stream);
stream.Position = 0;
return stream;
}
}
and then over in the Xamarin Forms side, I have
IBuildQrCodes qrBuilder = /* Service lookup */
var stream = await qrBuilder.ImageStreamForAsync("the text to encode");
return ImageSource.FromStream(() => new MemoryStream(stream.ToArray()));
which is doing what I want, so it's an acceptable workaround.
I am not sure what widget "Content" in your code represents, but assigning your "image" to a Form View's Image Class that is a member of your ContentPage should do the trick.
In XAML, you would create an Image within your ContentPage, ie like in one of the Form's samples .
Otherwise, dynamically create an Image class widget, add it your layout via AddView for your ContentPage .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.