Bind a PictureBox with a string of a url for LoadAsync - c#

Is there a way to bind a PictureBox to a string so that when the string will change, it will call LoadAsync() with the url in the string and load an image?
Currently this is what I have in the auto generated code.
this.itemImagePictureBox.DataBindings.Add(new System.Windows.Forms.Binding("Image", this.MySource, "ItemImage", true));
What I want instead is:
this.itemImagePictureBox.DataBindings.Add(new System.Windows.Forms.Binding("String", this.MySource, "ImageUrl", true));
MySource has a property for url string, and I also tried to make it have a field of an Image, but a Bitmap for example doesn't have a load async feature so I still can't use the url string.

Make sure the WaitOnLoad property is false (default), thus enabling asynchronous image load, and then bind to ImageLocation property:
this.itemImagePictureBox.WaitOnLoad = false;
this.itemImagePictureBox.DataBindings.Add(new System.Windows.Forms.Binding(
"ImageLocation", this.MySource, "ImageUrl", true));

Does it have to be databinding? Why not:
MyImage = new Bitmap(fileToDisplay);
itemImagePictureBox.Image = (Image) MyImage ;
await itemImagePictureBox.LoadAsync();
itemImagePictureBox.Refresh();
Or, if the image is a URL:
Load an image from a url into a PictureBox

Related

how to cast (or convert) an ImageSource to FileImageSource [duplicate]

I am trying add a background image using the image property in button. The issue I'm facing is that i can't set StreamImageSource as button background. I encountered the error given below if I try to do so.
The Code I use to set Image:
ImageSource iconsource =ImageSource.FromStream(() => new MemoryStream(ImgASBytes));
Button Icon = new Button ();
Icon.Image = iconsource ;
The Error I encounter:
Error CS0266: Cannot implicitly convert type 'Xamarin.Forms.ImageSource' to 'Xamarin.Forms.FileImageSource'. An explicit conversion exists (are you missing a cast?)
ImageSource.FromStream () returns a StreamImageSource (see docs). Button.Image accepts only FileImageSource (see docs).
It means that what you're trying to achieve won't work, no matter how hard you try to cast one into the other.
Button.Image will accept images stored as resources in your platform projects, and loaded either with:
Icon.Image = ImageSource.FromFile ("foobar.png");
or
Icon.Image = "foobar.png";
The accepted answer is true that you can't cast StreamImageSource to FileImageSource, I think that the real question is about how to share images in a PCL and use them on a button, just like one would when creating an Image forms control.
The answer is to have a Grid which contains both a Button and an Image object, where the Image overlaps the Button.
For example, the C# code might look like this:
ImageSource imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
Button iconButton = new Button ();
iconButton.VerticalOptions = LayoutOptions.FillAndExpand;
iconButton.HorizontalOptions = LayoutOptions.FillAndExpand;
var image = new Image();
image.Source = imageSource;
// So it doesn't eat up clicks that should go to the button:
image.InputTransparent = true;
// Give it a margin so it doesn't extend to the edge of the grid
image.Margin = new Thickness(10);
var grid = new Grid();
// If we don't set a width request, it may stretch horizontally in a stack
grid.WidthRequest = 48;
// Add the button first, so it is under the image...
grid.Children.Add(iconButton);
// ...then add the image
grid.Children.Add(image);
You may have to play with the sizes and thickness values but this should get you a clickable button with an icon.
As of Xamarin.Forms 3.4.0 you can now use ImageButton. You can use embedded images by using an extension method explained in this MS document
Careful with upper- and lowercase in filenames.
I was wondering, why my button-images were shown properly on the simulator, but not on my iPhone.
On the device the filename must match exactly, the simulator doesn't care about upper- and lowercase in filenames.
I use this and it works
var imageA = new Image();
imageA.Source=(FileImageSource)ImageSource.FromFile(allergeneLocation)};
or
var imageA = new Image()
{
BackgroundColor = Color.Teal,
Source = (FileImageSource)ImageSource.FromFile(allergeneLocation)},
};
Here is what I tried:
Button refreshBut = new Button
{
Image = (FileImageSource)
(ImageSource.FromFile("refreshBut.png"))
};
While it compiles I then get an unhandled null reference exception with the description: Object reference not set to an instance of an object. I am not sure if this will help anyone else try to solve this but I am at the same wall.

How do I get the Source of an Image on GestureCompleted

I want to find the URI of an Image on the phone screen when the image is dragged.
I have many images on the screen and I need to know which one has been dragged, I can easily find that from the filename of the image as they are named A.png, B.png and so on.
private void OnGestureCompleted(object sender, Microsoft.Phone.Controls.GestureEventArgs e){
Image image = sender as Image;
TranslateTransform transform = image.RenderTransform as TranslateTransform;
//storing the final values after the gesture is complete
xFin = (e.GetPosition(null).X);
yFin = (e.GetPosition(null).Y);
//failed attempts to convert adress to string
MessageBox.Show(image.Source.ToString());
}
This returns System.Windows.Controls.Image.
and this on the other hand throws an exception stating that ConvertToString hasn't been implemented.
ImageSourceConverter convertor = new ImageSourceConverter();
string location = convertor.ConvertToString(image);
MessageBox.Show(location);
Is there some way this can be done?
If you know that the Source property is BitmapImage (which it probably is if you are passing in a URI to the Image in the Source property in XAML) then you can use UriSource:
MessageBox.Show(((BitmapImage)image.Source).UriSource.ToString());
I suggest you use the Tag property of the Image control to store the info you need though. More scalable robust in the long run.

Image name as string, use it to make image visible WPF with C#

I have an image name as a string. The real imagename on the form is called "image". So i get something like this:
image.Visibility = Visibility.Hidden;
string imageName = "image";
// need something here to make it usable...
changedImageName.Visibility = Visibility.Visible;
Now, a string can not be used in combination with the Visibility property.
I cant really find what i must make the string to, to make it usable for the visibility property.
If i see this page: http://msdn.microsoft.com/en-us/library/system.windows.visibility.aspx
Do I understand correct that I make it a "enum" ? And if yes, how do I get a string to that property?
EDIT 1
I see I have not been explaining it proper enough.
I forgot to mention I am using a WPF form.
on this form, I have put an image.
In the initialize part, the image get set to hidden.
so for example the imagename I named "Image"
so I use image.Visibility = Visibility.Hidden;
later on in my code, I want to make the image visible again, depending on what the user does.
so, instead if just using the name to get the image visible again, I want to use a string.
this string is looking exactly as the name of the image.
but i cant use the string in combination with the Visibility function.
but i cant find anywhere what i must make this string to, to be able to use that visibility option on it.
hope i explained a bit better now :).
Later on, i will have multiple images on the WPF window.
So the key is that i will use the string, that is corresponding with the name of the image.
Depending on what the user has input into the string, some image will or will not show.
EDIT 2
If you have:
String theName = ImageName.name
you can get the name of the image into a string, so you can do stuff with it.
i am looking for a way to do the exact opposite of this. So i want to go from a string, to that name, so after that i can use this to control the image again.
Edit 3
some example:
private void theButton_Click(object sender, RoutedEventArgs e)
{
//get the Name property of the button
Button b = sender as Button;
string s = b.Name;
MessageBox.Show("this is the name of the clicked button: " + s);
//the name of the image to unhide, is the exact same as the button, only with IM in front so:
string IM = "IM";
IM += s;
MessageBox.Show("this string, is now indentical to the name of the image i want to unhide, so this string now looks like: " + IM );
// now, this wont work, because i cant use a string for this, although the string value looks exactly like the image .name property
// so string IM = IMtheButton
// the image to unhide is named: IMtheButton.name
IM.Visibility = Visibility.Visible;
}
looks like you're using WPF, so you can create a boolean to visibility converter and use it with a boolean (and create a method that receives string if necessary) and just use:
<ContentControl Visibility="{Binding Path=IsControlVisible, Converter={StaticResource BooleanToVisibilityConverter}}"></ContentControl>
or any other converter...
check this links:
http://bembengarifin.wordpress.com/2009/08/12/setting-visibility-of-wpf-control-through-binding/
http://andu-goes-west.blogspot.com/2009/05/wpf-boolean-to-visibility-converter.html
http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter.aspx
EDIT 1:
so then you will have to iterate over the images and check if your string is equals to name of the Image class.
something like this (not tested):
foreach (Image img in container.Items)
{
if img.Name == yourMagicallyString;
{
img.Visibility = Visibility.Visible;
}
else
{
img.Visibility = Visibility.Hidden;
}
}
If I understand correctly, you are trying to find a control based on the name or ID of the control. If so, try this:
Control changedImage = this.Controls.Find("image", false)[0];
Depending on what you are targeting and what version you might need to tweak a little
EDIT Updated per #Alexander Galkin comments about Find returning an array. There should definitely be some checking and whatnot but I'm leaving that up to the OP.
EDIT 2 For finding a control by name in WPF see this post.
The code I was looking for:
object item = FindName(IM);
Image test1 = (Image)item;
test1.Visibility = Visibility.Visible;

Binding a System.Drawing.Image to a Gridview in ASP.Net

I have defined a gridview control with a column of type ImageField and I bind the gridview to a List<MyRecord>.
MyRecord includes a property of type System.Drawing.Image, but the image is not rendered in the gridview.
There are numerous articles re binding using the URL field which points to (say) a jpg file... but i have the actual Image, not a file.
Any suggestions?
Create a custom ImageHandler like this article describes:
Image Handling In ASP.NET
That's not how the ImageField works. It expects the URL to the image.
<asp:ImageField DataImageUrlField = "ImageUrl" ...
The Handler.ashx worked... thank you
in the code, i set the ImageUrl = string.Format("~/HandlerGetImage.ashx?id={0}", imageNumber);
This dynamically calls the Handler in which i get the image index by
string v = context.Request.QueryString["id"];
Then, the following returns the image:
int ix = Convert.ToInt32(v);
MemoryStream ms = new MemoryStream(Query.imageList[ix]); // imagelist is created elsewhere
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
context.Response.ContentType = "image/jpeg";
//saving bitmap image
returnImage.Save(context.Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Jpeg);
returnImage.Dispose();

Add Bitmap to HTML

I have an ASP.NET web form. This web form has an event handler that generates some HTML. This HTML is based on the time-of-day, that is why it is created in the event handler. Based on the time of day, an image is created programmatically via the following method:
private Bitmap GetImageForTime(DateTime time)
{
Bitmap bitmap = new Bitmap();
// Dynamically build the bitmap...
return bitmap;
}
I want to call this method when the HTML is being generated. However, I do NOT want to write the image on the server. Instead, I would like to figure out a way to write it out along with the HTML. In a sense, I'm trying to accomplish the following:
protected void myLiteral_Load(object sender, EventArgs e)
{
string html = "<table><tr><td>";
html += GetImageForTime(DateTime.Now); // This is the problem because it's binary.
html += "</td><td>";
html += GetWeatherHtmlText();
html += "</td></tr></table>";
myLiteral.Text = html;
}
Is this possible? If so, how?
I would suggest implementing an IHttpHandler that generates your image and returns it as a byte stream. Then in the tag on the page, set the src attribute to the address of the HTTP Handler.
<html><body><img src="TimeImageHandler.ashx"/></body></html>
Example: http://www.c-sharpcorner.com/uploadfile/desaijm/httphandlersforimages11152005062705am/httphandlersforimages.aspx
Generic HTTP Handlers are pretty simple to create once you're aware of them:
public class TimeImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Bitmap bitmap = GetImageForTime(DateTime.Now);
context.Response.ContentType = "image/jpeg";
bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
public bool IsReusable { get { return false; } }
}
The way I have done this is to create an image tag in the HTML and point the image source (<img src="xxx" />) to a page that dynamically creates the image and returns that (and only that) on the response stream, with the correct mime type.
Potentially you could use the data URI scheme in an <img> tag or in some CSS but personally, I wouldn't.
Some more explanation.
Images in HTML are displayed as a result of an <img> element in the HTML. I don't believe there is any other way to display an image in an HTML page.
You will need to write a handler which can be invoked via the URL in the src attribute of the <img> element. That handler will generate and return the image.
Create another aspx page called TimeImage.aspx then in the Page_Load of the code-behind for the page put this code:
void Page_Load(object sender, EventArgs args) {
string mime = "image/jpeg";
Response.ContentType = mime;
Bitmap b = GetImageForTime(DateTime.Now);
var codec = ImageCodecInfo.GetImageEncoders().Where(i => i.MimeType == mime).SingleOrDefault();
if(codec != null)
b.Save(Response.OutputStream, codec, null);
}
Then make your html generation look like this:
protected void myLiteral_Load(object sender, EventArgs e)
{
string html = "<table><tr><td>";
html += "<img src='TimeImage.aspx'>"
html += "</td><td>";
html += GetWeatherHtmlText();
html += "</td></tr></table>";
myLiteral.Text = html;
}
This will create an img tag that calls the TimeImage.aspx page, that page changes the response mime-type to image/jpeg, converts your bitmap to a JPG, and then saves it to the response output stream so that the image tag can display it as a JPG.
If you prefer a different format just change the mime type at the top (e.g. "image/gif" for GIF, or "image/png" for PNG).
Beyond the already given solutions of using the data URI scheme or sending the image dynamically created (so, without storing it), there's another odd solution you can try: a table with each cell 1-pixel tall and wide and proper background per cell, and no borders of course... GIMP e.g. is able to export images this way as html, and if you force the size of cells and table, you can see the image as if it were embedded... of course, it is rather "heavy" if the image is big, but it could work ok for relatively small images.
EDITED (italics part added)

Categories

Resources