Loading image from URL in Windows Phone 7 - silverlight

I use below code to load image from URL in my winodws phone 7 application.
Uri uri = new Uri("http://dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/80000/5000/100/85108/85108.strip.print.gif", UriKind.Absolute)
image1.Source = new BitmapImage(uri);
It is working fine for me. But image is loading asynchronously and by the time I want to show some kind of busy indicator there and if image does not exist on such URL then I want to show some default image. How can I achieve that?

I think if you are subscribed to the Image.ImageFailed Event you should be able to show to default image in case of a non-existing image.
Conditions in which this event can occur include the following:
File not found.
Invalid (unrecognized or unsupported) file format.
Unknown file format decoding error after upload.
So something like this might work for you:
image1.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(handlerImageFailed);
Uri uri = new Uri("http://dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/80000/5000/100/85108/85108.strip.print.gif", UriKind.Absolute)
image1.Source = new BitmapImage(uri);
void handlerImageFailed(object sender, ExceptionRoutedEventArgs e)
{
// Show the default image
}

Related

how to download image in browser -angularjs

I am showing image list in a html table. I have one column in the table as image name and made it as link so user can click and download the image. The image list come from database which are saved as byte array and while sending to client side I am converting it to static object as shown below
given below
FileContent = Utilities.GetString(item.FileContent);
//GetString method
public static object GetString(byte[] bytes)
{
try
{
MemoryStream stPictureSource = new MemoryStream(bytes);
var sr = new StreamReader(stPictureSource);
return sr.ReadToEnd();
}
catch(Exception ex)
{
Logger.Log(ex);
return string.Empty;
}
}
So,Can some one have an idea, how to download image in browser.
Please let me now if the question isnt clear...
Comparison your Tags included angularjs and asp.net-web-api, This sample App showing how to do file uploads with angularjs using Asp.net Web Api. Hopefully it can aid you to deal with your problem.angular-fileupload-sample

Listbox default image

In an windows phone 7 application I'm populating one listbox with remote images .. since the images are not downloaded instantly I want to load a default image until the remote image are ready. What is the best way to do this?
Until now, I have the following code skelton:
public partial class RemoteImage : PhoneApplicationPage
{
ObservableCollection<Image> images = new ObservableCollection<Image> { };
public RemoteImage()
{
InitializeComponent();
listImage.ItemsSource = GetAllImages();
}
private ImageSource GetImageSource(string fileName)
{
return new BitmapImage(new Uri(fileName, UriKind.Absolute));
}
private ObservableCollection<Image> GetAllImages()
{
WebClient restClient = new WebClient();
restClient.OpenReadAsync(new Uri(#"http://www.my-api.com"));
restClient.OpenReadCompleted += new OpenReadCompletedEventHandler(onReadComplete);
return images;
}
private void onReadComplete(object sender, OpenReadCompletedEventArgs args)
{
Stream stm = args.Result;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
RootObject ro = (RootObject)ser.ReadObject(stm);
foreach (var item in ro.items)
{
images.Add(new Image{ PhotoSource = GetImageSource(item.image.link) });
}
}
}
If you know, how many images you would need, you should create first the number of default images. Load some image file directly at your project and use it as imageSource for default images. Then, when you'll finish downloading remote images, you should set the new image source for each.
When I got the similar issue, I had some problems with defining which exactly downloaded image refers to which object on page. (As you remember the WebClient objects work asynchronously, so if you have 10 images on page and download 10 remote images at once you can't say that the first downloaded image is the first on page) To solve this you could create more complicated download method (I used a delegate to transfer the id/name of image) or use recursion (Start download method for first image, download it, set source for one on page, download next one...).

Adding image F#

I have a stack panel to which I want to add some icons dynamically.
If I add a TextBlock to the stack panel, it works perfectly:
// assuming stackPanel is my stack panel
let text = new TextBlock()
text.Text <- "Test"
stackPanel.Children.add(text)
However, my goal is to add an image, but seems like it fails to resolve the image
let getImageSource(imagePath) =
let uri = new Uri(imagePath, UriKind.Relative)
new BitmapImage(uri);
let icon = new Image()
icon.Source <- getImageSource("images/fileIcon/icon.gif")
stackPanel.Children.Add(icon) // this doesnt work
now when I do:
let icon = new Image()
icon.Source <- getImageSource("images/fileIcon/icon.gif")
stackPanel.Children.Add(icon)
let text = new TextBlock()
text.Text <- "Test"
stackPanel.Children.add(text)
I can see there's an empty space between the texts, as if there is an empty image there.
So my guess is there's something wrong with the way I resolve the image path - but I am not sure why.
Thoughts?
Thanks!
In case your gif's Build Action is Resource, then the proper way to address it is /SilverlightApplication1;component/path/to/file.gif. Here SilverlightApplication1 is the name of your silverlight application
In case it's Build Action is Content, then it's proper address is /path/to/file.gif, always with a leading slash when creating a BitmapImage.
Check out Silverlight 2: Demystifying URI references for app resources for more information.
For easier debugging of image loading problems, hook to the BitmapImage.ImageFailed event and see what kind of errors crop up.
One last note, AFAIK Silverlight doesn't support the GIF format. You might use PNG instead.
You can try with the following Uri if yours is WPF App.
let uri = Uri("pack://application:,,,/asm_name;component/images/fileIcon/icon.gif")
asm_name have to be replaced with your actual assembly name.
if your are working on Silverlight application, you need to modify the uri like this. Assuming that the build action of icon.gif is Resource.
let uri = Uri("../images/fileIcon/icon.gif", UriKind.Relative)
Hope this helps.

Properly cancel an image download in Silverlight

I have a set of Image elements that I use to download pictures. All the pictures have to be downloaded, but I wish to download the picture the user is looking at in the first place. If the user changes the viewed picture, I wish to cancel the downloads in progress to get the viewed picture as fast as possible.
To start a download I write: myImage.Source = new BitmapImage(theUri);.
How should I cancel it?
myImage.Source = null; ?
act on the BitmapImage ?
a better solution ?
I don't wish to download the picture by code to keep the benefit of the browser cache.
This is definitely doable -- I just tested it to make sure. Here is a quick class you can try:
public partial class Page : UserControl
{
private WebClient m_oWC;
public Page()
{
InitializeComponent();
m_oWC = new WebClient();
m_oWC.OpenReadCompleted += new OpenReadCompletedEventHandler(m_oWC_OpenReadCompleted);
}
void StartDownload(string sImageURL)
{
if (m_oWC.IsBusy)
{
m_oWC.CancelAsync();
}
m_oWC.OpenReadAsync(new Uri(sImageURL));
}
void m_oWC_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
BitmapImage oBMI = new BitmapImage();
oBMI.SetSource(e.Result);
imgMain.Source = oBMI;
}
}
This works just like you wanted (I tested it). Everytime you call StartDownload with the URL of an image (presumably whenever a user clicks to the next image) if there is a current download in progress it is canceled. The broswer cache is also definitely being used (I verified with fiddler), so cached images are loaded ~ instantly.

Silverlight image: load URL dynamically?

I'm tinkering with Silverlight 2.0.
I have some images, which I currently have a static URL for the image source.
Is there a way to dynamically load the image from a URL path for the site that is hosting the control?
Alternatively, a configuration setting, stored in a single place, that holds the base path for the URL, so that each image only holds the filename?
From what I gather you aren't trying to change the image itself dynamically, but rather to correctly determine the location of the image at runtime.
I believe simply prefixing the image relative URL with "../" should get you to the root of your application, not necessarily the site as the application might not be hosted in the root of a site.
If your XAP file is located as follows:
http://somesite.foo/app1/somethingelse/clientbin/MyFoo.xap
And you where trying to link the following image:
http://somesite.foo/app1/somethingelse/images/a/boo.png
Apparently all relative URI's are relative to where the XAP file is located (ClientBin folder typically) and Silverlight appends the current Silverlight client namespace. So if you Silverlight control is in the namespace Whoppa you would need to put all your images in the clientbin/Whoppa/ directory. Not exactly convenient.
The workaround is to use absolute URIs as follows:
new Uri(App.Current.Host.Source, "../images/a/boo.png");
In the code behind or a value converter you can do
Uri uri = new Uri("http://testsvr.com/hello.jpg");
YourImage.Source = new BitmapImage(uri);
// create a new image
Image image = new Image();
// better to keep this in a global config singleton
string hostName = Application.Current.Host.Source.Host;
if (Application.Current.Host.Source.Port != 80)
hostName += ":" + Application.Current.Host.Source.Port;
// set the image source
image.Source = new BitmapImage(new Uri("http://" + hostName + "/cute_kitten112.jpg", UriKind.Absolute));
http://www.silverlightexamples.net/post/How-to-Get-Files-From-Resources-in-Silverlight-20.aspx
using System.Windows.Resources; // StreamResourceInfo
using System.Windows.Media.Imaging; // BitmapImage
....
StreamResourceInfo sr = Application.GetResourceStream(new Uri("SilverlightApplication1;component/MyImage.png", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.SetSource(sr.Stream);
SilverlightHost.Source will provide you the URL that was used to load the XAP file. You can use this to then construct a relative URL for your images.
So if for example your XAP is hosted on http://foo.bar/ClientBin/bas.xap and your images were stored in http://foo.bar/Images/ you can simply use the Source to grab the host name and protocol to construct the new URI.
img.Source = new BitmapImage(image uri) must work.
img.Source = new BitmapImage(new Uri("/images/my-image.jpg", UriKind.Relative)); will properly resolve to the root of the Silverlight application where as "../images/my-image.jpg" will not.
This is only true in the code-behind when dynamically setting the source of the image. You cannot use this notation (the "/" to designate the root) in the XAML (go fiquire, hope they fix that)
The below code worked for me only when the image is included in the project as a resource file:
img.Source = new BitmapImage(new Uri("/images/my-image.jpg", UriKind.Relative));
I am unable to access URL from absolute URLs. Not even Flickr's farm URL for images.

Resources