Xamarin Forms Byte[] to Image Source not showing - c#

Hi all I have a byte[] which I save from the Xamarin Essentials Media Picker, I want to display the image on my XAML page so all I have is a blank XAML page with a StackLayout and in my code I do the following:
Stream stream = new MemoryStream(filebyte);
var imageSource = ImageSource.FromStream(() => stream);
Image test = new Image();
test.Source = imageSource;
test.WidthRequest = 50;
test.HeightRequest = 50;
ImageStack.Children.Add(test);
but when the page loads nothing is there. i'm I missing something. I have even tried this on a fresh project using the latest version of Xamarin Forms and Xamarin Essential's

imgByteArray is Byte[], using following code to add image by behind code.
var stream1 = new MemoryStream(imgByteArray);
image.Source = ImageSource.FromStream(() => stream1);
image.WidthRequest = 50;
image.HeightRequest = 50;
imagestack.Children.Add(image);
Update:
Adding one image in Forms, setting Build action as Embedded resource, then converting this image into byte[], using this byte[] for Image to show. I have no problem.
var image = new Xamarin.Forms.Image();
var assembly = this.GetType().GetTypeInfo().Assembly;
byte[] imgByteArray = null;
var s = assembly.GetManifestResourceStream("FormsSample.f19.png");
if (s != null)
{
var length = s.Length;
imgByteArray = new byte[length];
s.Read(imgByteArray, 0, (int)length);
var stream1 = new MemoryStream(imgByteArray);
image.Source = ImageSource.FromStream(() => stream1);
image.WidthRequest = 50;
image.HeightRequest = 50;
imagestack.Children.Add(image);
}

Related

Drawing an image from svg url in wpf C#

This is the URL with image-https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/acid.svg
What I have tried
Sample 1-
-I am using SharpVectors package
public void DrawImage()
{
Image svgImage = new Image();
WpfDrawingSettings settings = new WpfDrawingSettings();
settings.IncludeRuntime = false;
settings.TextAsGeometry = true;
FileSvgReader converter = new FileSvgReader(settings);
DrawingGroup drawing = converter.Read(new Uri("https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/acid.svg"));
if (drawing != null)
{
svgImage.Source = new DrawingImage(drawing);
}
}
sample 1 works perfectly but it's latency is very high, So I wanted to improve the performance.
Sample 2 - I tried using bitmap to improve performance below is code, but the issue is I need to download the image or store in folder and use as path as string which works fine but my condition is my URLs are coming form JSON file in .SVG format, they are dynamic and I am not using any .XAMl files for UI.
UI built in code behind programmatically.
Is there any other way I can display SVG image in WPF?
public void DrawImage()
{
Image dynamicImage = new Image();
dynamicImage.Width = 300;
dynamicImage.Height = 200;
stcdock.Children.Add(dynamicImage);
WpfDrawingSettings settings = new WpfDrawingSettings();
settings.IncludeRuntime = true;
settings.TextAsGeometry = false;
string svgTestFile = #"\Downloads\acid.svg";
StreamSvgConverter converter = new StreamSvgConverter(settings);
MemoryStream memStream = new MemoryStream();
if (converter.Convert(svgTestFile, memStream))
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = memStream;
bitmap.EndInit();
dynamicImage.Source = bitmap;
}
}
.svg are not nativly supported in wpf.
https://www.nuget.org/packages/svg
This package promisses to add this functionality.

"Image could not be read." in MigraDocCore on Xamarin Forms

I'm using Xam.Plugin.Media to capture a photo from the camera and I want to use the stream from the image to print it on a pdf. I tried so many ways to do this but no one is working and always is printed a gray rectangle with the "Image could not be read" on the center. Anyone have an ideia how to fix this ?
here is my code
var paragraph = document.LastSection.AddParagraph();
paragraph.Format.Alignment = ParagraphAlignment.Center;
var iimage = DependencyService.Get<IImage>();
using (Stream stream = MyImage.GetStream())
{
stream.Position = 0;
MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.ImageSourceImpl = iimage.Implementation;
var foto = MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromStream($"MyImage_{Id}.jpg", () => stream, 100)
var image = paragraph.AddImage(foto);
image.LockAspectRatio = false;
image.Width = "15cm";
image.Height = "10cm";
}
Thanks for Helping.
edit 1: I removed the dependen service and Im using MediaPicker instead of Plugin Media and is throwing a NullReferenceException when the ImageSource is created.
Here is the code:
var paragraph = document.LastSection.AddParagraph();
paragraph.Format.Alignment = ParagraphAlignment.Center;
using (Stream stream = await MyImage.OpenReadAsync())
{
stream.Position = 0;
var foto = MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromStream($"{MyImageId}.jpg", () => stream, 100);
var image = paragraph.AddImage(foto);
image.LockAspectRatio = false;
image.Width = "15cm";
image.Height = "10cm";
}
here is the stack trace:
System.NullReferenceException: Object reference not set to an instance of an object.
at MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.FromStream (System.String name, System.Func1[TResult] imageStream, System.Nullable1[T] quality) [0x00005] in <491d7d6ccaa64ee5ad963f480330f219>:0
at Myproject.MyClass.MyMethod()
'''
The ImageSource Implementation is null by default, so I added this code to set the
ImageSource.Impl, before create the Image Source:
if(MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.ImageSourceImpl == null)
{
MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel.Shapes.ImageSource.ImageSourceImpl = new ImageSharpImageSource<Rgba32>();
}

QR code rendering with ZXing.Net.Mobile in Xamarin.Forms app

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.
i.e. 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, e.g. 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, i.e. like in one of the Form's samples.
Otherwise, dynamically create an Image class widget, add it your layout via AddView for your ContentPage.

Adding Image to FixedPage in WPF

I want to be able to print images with other UIElements. I have a FixedPage instance and trying to add image like so
// Basic printing stuff
var printDialog = new PrintDialog();
var fixedDocument = new FixedDocument();
fixedDocument.DocumentPaginator.PageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
FixedPage page = new FixedPage();
page.Width = fixedDocument.DocumentPaginator.PageSize.Width;
page.Height = fixedDocument.DocumentPaginator.PageSize.Height;
Image img = new Image();
// PrintIt my project's name, Img folder
var uriImageSource = new Uri(#"/PrintIt;component/Img/Stuff.png", UriKind.RelativeOrAbsolute);
img.Source = new BitmapImage(uriImageSource);
img.Width = 100;
img.Height = 100;
page.Children.Add(img);
PageContent pageContent = new PageContent();
((IAddChild)pageContent).AddChild(page);
fixedDocument.Pages.Add(pageContent);
// Print me an image please!
_printDialog.PrintDocument(fixedDocument.DocumentPaginator, "Print");
It gives me a blank paper. I'm wondering why, because other UIElements (such as TextBox, Grid, Rect) appear with no problems. What am I missing?
Thanks!
PS OK, I've found another solution. I don't know why but with that Uri a picture loads properly
var uri = new Uri("pack://application:,,,/Img/Stuff.png");
To be more clear on my Code
var bitImage = new BitmapImage();
bitImage.BeginInit();
bitImage.StreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read);
bitImage.DecodePixelWidth = 250;
bitImage.CacheOption = BitmapCacheOption.OnLoad;
bitImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
bitImage.EndInit();
bitImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin);
bitImage.Freeze();
var tempImage = new Image {Source = bitImage};
var imageObject = new ImageObject(tempImage, fileName);
bitImage.StreamSource.Dispose();
page.Children.Add(imageObject);
First i would like to suggest that, see below.
Set the sourceStream of the Image for BitMap
bitImage.StreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read);
Then freeze the BitMap Image, or it ll not be in the instance as render able image.
bitImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin);
bitImage.Freeze();
This should work, if not i personally think it is a bad idea to directly work with BitMaps, i use Bitmap to create image form file then copy it to the type Image(system.drawing iguess), something like below
var tempImage = new Image {Source = bitImage};
var imageObject = new ImageObject(tempImage, fileName);
bitImage.StreamSource.Dispose();
this tempImage can be added to ur page as regular UIElement.
Hope it helps.

Windows Phone 7- Set an Image source to a stream in memory

Is it possible to set the source of an image in WP7 to a stream? Normally I'd use BitmapImage to do this in Silverlight but I don't see that option in WP7. Here's my code:
var request = WebRequest.CreateHttp("http://10.1.1.1/image.jpg");
request.Credentials = new NetworkCredential("user", "password");
request.BeginGetResponse(result =>
{
var response = request.EndGetResponse(result);
var stream = response.GetResponseStream();
// myImage.Source = ??
}, null);
The reason I ask is because I need to provide credentials to get the image - if there's another way to approach the problem I'm open to suggestions.
Yes, use this code:
var bi = new BitmapImage();
bi.SetSource(stream);
myImage.Source = bi;
In case WritableBitmap you can use:
WriteableBitmap wbmp = new WriteableBitmap(1000, 1000);
Extensions.LoadJpeg(wbmp, stream);
Image img = new Image();
img.Source = wbmp;
Try this one
<Image Name="Img" Stretch="UniformToFill" />
var bitImg= new BitmapImage();
bitImg.SetSource(stream); // stream is Stream type
Img.Source = bitImg;

Categories

Resources