Convert A Byte[] Array to Image in Xamarin Forms - arrays

Before asking this question I googled a lot but couldn't find a solution that suits mine.
In Xamarin.Forms I have a byte[] array and I want to Convert that byte[] array to an Image. How can I achieve that, this is what I tried:
In Front End(XAML):
<StackLayout BackgroundColor="Olive" x:Name="imagePanel">
<Image x:Name="PdfImage" Aspect="AspectFill" IsVisible="true"/>
</StackLayout>
In Code Behind(C#):
byte[] imageAsBytes = Constant.jsonPDF;
var stream1 = new MemoryStream(imageAsBytes);
PdfImage.Source = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
imagePanel.Children.Add(PdfImage);
But My problem is image is not displaying.
Can anybody tell me what I'm doing wrong. Any help would be greatly appreciated.

(XAML):
<Image Grid.Row="1" x:Name="IncidentImageData" Grid.ColumnSpan="4" BackgroundColor="DarkGray" Aspect="AspectFill" WidthRequest="50" HeightRequest="175"/>
viewModel.SImageBase64 is a byte[]
Code Behind(C#):
var stream1 = new MemoryStream(viewModel.SImageBase64);
IncidentImageData.Source = ImageSource.FromStream(() => stream1);
simply i have done like this and image has shown.

A Potential Fix
I know this thread is 2 years old now but I thought i'd post a working solution here for anyone who's also struggling with this. Just spent half a day researching and trying to solve an identical problem, the way the code was written on this post helped me greatly as it is almost 100% correct. You just need to provide the MemoryStream as a return from a lambda function within the FromStream() method.
Change this:
PdfImage.Source = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
To:
PdfImage.Source = ImageSource.FromStream(() =>
{
return new MemoryStream(imageAsBytes);
});
And the snippet should be working as of Xamarin Forms 5.0.0.2012
Full Code:
byte[] imageAsBytes = Constant.jsonPDF;
PdfImage.Source = ImageSource.FromStream(() =>
{
return new MemoryStream(imageAsBytes);
});
imagePanel.Children.Add(PdfImage);

Use this Code :
imgUserImage.Source = ImageSource.FromStream(() => new MemoryStream(userList.Single().ProfilePhoto));
Here profile photo type is byte[]
public byte[] ProfilePhoto { get; set; }

Related

How do I resolve Non String values, when using a WebService to access SqlServer

I'm currently trying to build a UWP app that points to a SqlServer, and thru much research, determined that my best plan of attack was to create a WebService and make EF Calls to "CRUD" the dbase.
I found a good tutorial that helped a lot, however, I'm still new at this so seeing what some else did, and adapting is a learning experience. So it has caused a few questions to come up, that I have yet to solve.
These are my question;
HostName below is an INT in the Database and POGO Class.. So I'm getting the "cannot implicitly convert type 'int' to 'string'" error. How do I resolve this? Do I use StringFormatConverter that is part of the Template I'm using?
The last value, EMV is a boolean value. It is currently pointing to a Toggleswitch and is pointing to the IsOn property of the Control. Will that resolve correctly?
Lastly, I would like to keep as much of my code adherent to the MVVM format. So If I move the below code below from Code Beyond to the ViewModel would that perform better?
Here is the Code Behind inside the Click Event...
private async void Save_Click(object sender, RoutedEventArgs e)
{
var tblDevice = new Device { HostName = hostNameTB.Text, Server =serverIPTB.Text, RouterName = routerNameTB.Text, IP = iPTB.Text, Gateway =gatewayTB.Text, Hardware = hardwareTB.Text, EMV = eMVTB.IsOn};
var deviceJson = JsonConvert.SerializeObject(tblDevice);
var client = new HttpClient();
var HttpContent = new StringContent(deviceJson);
HttpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("Application/json");
await client.PostAsync("http://localhost:2463/api/Devices", HttpContent);
Frame.GoBack();
}
Here is the XAML
<TextBox Name="hostNameTB" />
<TextBox Name="serverIPTB" />
<TextBox Name="routerNameTB" />
<TextBox Name="iPTB" />
<TextBox Name="gatewayTB" />
<TextBox Name="hardwareTB" />
<ToogleSwitch Header="EMV" IsOn="False" Name="eMVTB" OffContent="UnConfigured" OnContent="Configured" />
1 Int32.Parse(hostNameTB.Text) or via the Converter your choice.
2 Yes it will come thru as a 1 or a 0, true/false etc. In the DB I assume this a
BIT type?
3) it will perform the same only difference is testability

WPF Dynamic HyperLinks RichTextbox

I have seen several posts on various forms varying in times from 2006 to now about how to add hyperlinks to RichTextBox, but they all seem overly complex for what I want. I am creating a desktop chat client, and I receive input as strings, now among these strings may be some urls, I need those urls to be clickable. Which from what I gather means they need to be HyperLink objects.
Navigating through the RichTextBox and replacing the urls with HyperLinks seems to be no small feat. Does anyone have a relatively simple solution for this?
In my web client it's a simple one liner
value = value.replace(/(http:\/\/[^\s]+)/gi, '$1');
Never thought I'd see the day where C# actually makes it harder.
If you want to do an equivalent of value.replace(/(http:\/\/[^\s]+)/gi, '$1') in WPF:
<RichTextBox x:Name="MyRichTextBox" IsDocumentEnabled="True" IsReadOnly="True" />
And the code that converts the string is the following:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var htmlText = "Google's website is http://www.google.com";
MyRichTextBox.Document = ConvertToFlowDocument(htmlText);
}
private FlowDocument ConvertToFlowDocument(string text)
{
var flowDocument = new FlowDocument();
var regex = new Regex(#"(http:\/\/[^\s]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var matches = regex.Matches(text).Cast<Match>().Select(m => m.Value).ToList();
var paragraph = new Paragraph();
flowDocument.Blocks.Add(paragraph);
foreach (var segment in regex.Split(text))
{
if (matches.Contains(segment))
{
var hyperlink = new Hyperlink(new Run(segment))
{
NavigateUri = new Uri(segment),
};
hyperlink.RequestNavigate += (sender, args) => Process.Start(segment);
paragraph.Inlines.Add(hyperlink);
}
else
{
paragraph.Inlines.Add(new Run(segment));
}
}
return flowDocument;
}
}
It uses the same regular expression you provided, which is lacking if you properly want to recognize URLs with a regular expression. This one doesn't recognize https ones and the last dot in the following sentence would be a part of the URL: "This is a URL: http://www.google.com/."
What the code does is to split the text based on the regular expression, iterate it and adds the correct elements to the FlowDocument constructed on the fly.
Clicking the Hyperlink should open your default browser.
Result:
That said, this is only good for read only usage of the RichTextBox (as indicated by the question in the comment).

Image to Byte[] harder than thought 2 challenges

This is my 5th post over a month trying to solve what I thought was a simple problem: Write and read a small bitmap to a class.
My class:
public class Task
public byte? TaskImage { get; set; }
I recreate the bitmap in the controller after an edit, the bitmap is contained in System.Drawing. This line writes to a folder as a test. It works.
mybmp.Save("C:\\temp\\lot1.bmp",System.Drawing.Imaging.ImageFormat.Gif);
I think this puts it in a memory stream as a .bmp: Should this be .gif??
MemoryStream ms = new MemoryStream();
mybmp.Save(ms, System.Drawing.Imaging.ImageFormat.bmp);
CHALLENGE 1 provide inline code to convert to byte[] and write to class.
Task.TaskImage =
db.SaveChanges();
Later I pass the data via a viewmodel to my view and use the ForEach item concept to display the image.
CHALLENGE 2 code to display in view table:
<img src="data:image/gif;base64,#Convert.ToBase64String(item.TaskImage.Value)" />
This code has been provided by a contributor but causes this error.
Error 2 Argument 1: cannot convert from 'method group' to 'byte[]'
It was suggested I ask a new question.
I'm a beginner so please be explicit. When I have a working answer I'll go back and post answers to my earlier posts to help others.
I am assuming, you are properly saving the byte array and you already have contents of your image as a byte[]
why don't you try this, if you are using MVC4
<img src="#Url.Action("GetImage", "Controller", new{id=#Model.Id})"
alt = "img" />
where GetImage is :
public ActionResult GetImage(int id)
{
var imageByteArray= GetImageByte(id)
return File(imageByteArray, "Image/jpg");
}
Got it!
Challenge 1 the write bitmap into a byte[] field:
mybmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] byteArray = new byte[0];
ms.Close();
var lottoupdate = db.Lots //each task row contains the lotid to which
.Where(i => i.LotID == lotID) //it is associated. Find the LotID then
.Single(); // update the taskimage field in the lot class
byteArray = ms.ToArray();
lottoupdate.TaskImage = byteArray;
db.Entry(lottoupdate).State = EntityState.Modified;
db.SaveChanges();
There was a error in the lottoupdate.TaskImage=byteArray; line because TaskImage was nullable.
public class Task
public byte? TaskImage { get; set; }
So I removed the? therefore requiring data. I now seed the field.
Challenge 2 With the TaskImage byte[] passed in the viewmodel, display the image in the view table:
<text> #{
string imageBase64 = Convert.ToBase64String(#item.TaskImage);
String imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
}
</text>
<td><img src="#imageSrc" alt="Lot chart" border="0" /></td>
This displays the image in a table row. I needed the 'text' tags because html5 did not like the razor code without it. Note that I am not testing for null data, probably should. My program seeds an "base" image into the db.
I hope this helps someone else, it took about 30 hours of looking for this beginner.

Displaying Query data in a TextInput Field in Flex?

I'm trying to display query data into multiple TextInput Fields in Flex.
<mx:TextInput id="stagInput" text="{acContacts}" width="170" x="120" y="74"/>
This is what I'm trying but all that displays is [object Object]
I think I need to define the database field I'm wanting to display, but I'm unsure how to do this as TextInput fields don't support dataField or labelField properties. Is there another property I don't know about?
How do i go about fixing this?
Thanks!
Is acContacts the object? You can try {acContacts.label} or {acContacts.name} (or whatever attribute you wish to display).
Ok here's a bit more of my code
[Bindable]
private var acContacts:ArrayCollection;
private function retrieveData():void { //RETRIEVE DATA
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConn;
stmt.text = "SELECT * FROM tbl_person WHERE person_id=1";
stmt.execute();
var result:SQLResult = stmt.getResult();
acContacts = new ArrayCollection(result.data);
}
<mx:TextInput id="stagInput" text="{acContacts}" width="170" x="120" y="74"/>
The data comming from the query is information like first and last name, email, website .ect
I realize that my query currently has a hardcoded id but right now I'm just trying to get the users information displaying individual Textinputs - eg. one for first name one for last name .ect
Hope this explains my problem a bit better.
Thanks Again!
Here's what I was looking for
[Bindable]
private var acCon:ArrayCollection;
private function reData():void //RETRIEVE DATA
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConn;
stmt.text = "SELECT * FROM person";
stmt.execute();
var result:SQLResult = stmt.getResult();
acCon = new ArrayCollection(result.data);
}
<mx:Repeater id="repeater1" dataProvider="{acCon}">
<mx:Label id="Label1" text="{repeater1.currentItem.lastname}"/>

Showing Bitmap Images in WPF via C#

What I am trying to do is so simple but I am having a hard time making it work. I saw some posts along the same lines but I still have questions.
I have a MenuItem object called mnuA. All I want is set the icon property programatically in C#. I have tried the following
a) mnuA.Icon = new BitmapImage{UriSource = new Uri(#"c:\icons\A.png")};
Results: Instead of showing the actual icon, I get the class name (System.Windows.Media.Imaging.BitmapImage)
b) mnuA.Icon = new BitmapImage(new Uri(#"c:\icons\A.png"));
Results: Instead of showing the actual icon, I get the path of the image (file:///c:/icons/A.png)
What am I doing wrong? Do I really need a converter class for something simple like this?
Try this:
Image img = new Image();
img.Source = new BitmapImage(new Uri(#"c:\icons\A.png"));
mnuA.Icon = img;
Might be a long shot, but try something like:
Uri u = new Uri(...); mnuA.Icon = new
BitmapImage(u);
What it seems its happening is that your icon is getting converted to a string.

Resources