How can I populate more than one Silverlight Image from Bing Maps asynchronous calls? - image

I have the following code, which works fine if you just want to populate one Image with a response from Bing Maps. But if I try to do two then the variable _currentImage always ends up being "image1" because the calls are asynchronous. How can I pass the image variable along to the ImageryServiceGetMapUriCompleted method?
using System;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using BasicBingMapsImagerySvc.ImageryService;
namespace BasicBingMapsImagerySvc
{
public partial class MainPage : UserControl
{
private const string BingMapsKey = "my key";
private Image _currentImage;
public MainPage()
{
InitializeComponent();
GetMap(42.573377, -101.032251, image0, MapStyle.AerialWithLabels);
GetMap(42.573377, -101.032251, image1, MapStyle.Road_v1);
}
private void GetMap(double lat, double lon, Image image, MapStyle mapStyle)
{
var mapUriRequest = new MapUriRequest();
// Set credentials using a valid Bing Maps key
mapUriRequest.Credentials = new Credentials();
mapUriRequest.Credentials.ApplicationId = BingMapsKey;
// Set the location of the requested image
mapUriRequest.Center = new Location();
mapUriRequest.Center.Latitude = lat;
mapUriRequest.Center.Longitude = lon;
// Set the map style and zoom level
var mapUriOptions = new MapUriOptions();
mapUriOptions.Style = mapStyle;
mapUriOptions.ZoomLevel = 13;
// Set the size of the requested image to match the size of the image control
mapUriOptions.ImageSize = new SizeOfint();
mapUriOptions.ImageSize.Height = 256;
mapUriOptions.ImageSize.Width = 256;
mapUriRequest.Options = mapUriOptions;
var imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
imageryService.GetMapUriCompleted += ImageryServiceGetMapUriCompleted;
_currentImage = image;
imageryService.GetMapUriAsync(mapUriRequest);
}
private void ImageryServiceGetMapUriCompleted(object sender, GetMapUriCompletedEventArgs e)
{
// The result is an MapUriResponse Object
MapUriResponse mapUriResponse = e.Result;
var bmpImg = new BitmapImage(new Uri(mapUriResponse.Uri));
_currentImage.Source = bmpImg;
}
}
}

You could use a lambda expression / delegate for your event handler, which allows you to 'capture' the reference to the image:
var imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
imageryService.GetMapUriCompleted += (s,e) =>
{
// The result is an MapUriResponse Object
MapUriResponse mapUriResponse = e.Result;
var bmpImg = new BitmapImage(new Uri(mapUriResponse.Uri));
// set the image source
image.Source = bmpImg;
};

Related

How to get Image from directory path in xamarin forms

I want to retrieve image which i have it's path in phone
filepath = "/storage/emulated/0/Android/data/com.CommunicatorEye/files/Pictures/EmployeesCards/IMG_20190131_143513.jpg";
var image = DependencyService.Get<IDependency().RetriveImageFromLocation(filepath);
IDependency.cs
public interface IDependency
{
Task<Image> RetriveImageFromLocation(string location);
}
Android
DependencyImplementation.cs
public async Task<Image> RetriveImageFromLocation(string location)
{
Image image = new Image();
var memoryStream = new MemoryStream();
using (var source = System.IO.File.OpenRead(location))
{
await source.CopyToAsync(memoryStream);
}
image.Source = ImageSource.FromStream(() => memoryStream);
return image;
}
but it doesn't work for me , any sample ?
If that file is within your app's sandbox, there is no reason to use DI/DependencyService/etc... to obtain a stream to populate an ImageSource and then add that to an Image.
Use an FileImageSource (static ImageSource.FromFile) and supply it the path:
var image = new Image
{
Source = ImageSource.FromFile(filePath)
};
This is how you can get path of resources. keys should be declared in App.xaml file
public static String GetImagePath(string AppResourceName)
{
return (Application.Current.Resources[AppResourceName] as FileImageSource).File;
}
public static Color GetColor(string AppResourceName)
{
return (Color)Application.Current.Resources[AppResourceName];
}

ZXing QR Code Generation in Xamarin Forms PCL

I'm trying to generate and display QR code using ZXing package, I tried in following code I was not able to show QR code. It's showing blank image (transparent).
private void OnGenerateQRCodeButton_Clicked(object sender, EventArgs e)
{
var writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = (int)imageCompanyLogo.Height,
Width = (int) imageCompanyLogo.Width,
Margin = 0,
PureBarcode = true
}
};
var bitmap = writer.Write("www.helloworld.com");
imageQRCode.Source = ImageSource.FromStream(() => new MemoryStream(bitmap));
}
Please suggest any way to do it. Thanks.
Create interface in PCL(Xamarin) project for Dependency Service.
Create a class in Native(Xamarin.Droid) and Inherit from PCL Interface.
Implement the method as shown below.
public Stream ConvertImageStream(string text, int width = 300, int height = 300)
{
var barcodeWriter = new ZXing.Mobile.BarcodeWriter
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Width = width,
Height = height,
Margin = 10
}
};
barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
var bitmap = barcodeWriter.Write(text);
var stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream); // this is the diff between iOS and Android
stream.Position = 0;
return stream;
}
call the method from PCL(Xamarin) project using Dependency Service.
In xaml.cs
private void OnGenerateQRCodeButton_Clicked(object sender, EventArgs e)
{
string barcodeText = "www.helloworld.com";
var stream = DependencyService.Get<IBarCodeServices>().ConvertImageStream(barcodeText, (int)imageCompanyLogo.Width,(int) imageCompanyLogo.Height);
barcodeImage.Source = ImageSource.FromStream(() => stream);
}
Debug and see if stream in empty or not.
var stream = (Stream)null;
private void OnGenerateQRCodeButton_Clicked(object sender, EventArgs e)
{
var writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = (int)imageCompanyLogo.Height,
Width = (int) imageCompanyLogo.Width,
Margin = 0,
PureBarcode = true
}
};
using(var bitmap = barcodeWriter.Write("www.helloworld.com"))
{
stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Png);
stream.Seek(0, SeekOrigin.Begin);
}
imageQRCode.Source = ImageSource.FromStream(() => new MemoryStream(stream));
}

How to upload images to facebook which is selected by using photoChooserTask in windows phone 8?

I am developing a Windows Phone app in which I have to post a photo to facebook. And that particular photo is choosen by using PhotoChooserTask or CameraChooserTask.
Normally, I can post a particular photo successfully, but I am facing problem to post the selected photo. I saw some link like
link
So please if anyone know about the issue please help me out.
Thanx in advance.
EDIT
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
//var parameters1 = new Dictionary<>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
parameters["ContentType"] = "image/png";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
string imageName = "ic_launcher.png";
StreamResourceInfo sri = null;
Uri jpegUri = new Uri(imageName, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);
try
{
byte[] imageData = new byte[sri.Stream.Length];
sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
fbUpload.SetValue(imageData);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Tribute";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1 + "\n" + d + "\n" + memoType + "\n" + message1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
//client.PostTaskAsync("me/photos", parameters1);
}
On clicking on a button I am calling PostClicked class and it will directly go to facebook mainpage and it will ask for login information. Like this I am doing.
Please check it out
Now I can share a photo to facebook successfully by using photochoosertask or cameratask.
I am sharing my experience so that if anyone face the same issue can use it.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageToIsolatedStorage(image, tempJPEG);
this.image.Source = image;
}
public void SaveImageToIsolatedStorage(BitmapImage image, string fileName)
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
var fileStream = isolatedStorage.CreateFile(fileName);
if (image != null)
{
var wb = new WriteableBitmap(image);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
fileStream.Close();
}
}
With this you can able to save the selected image to IsolatedStorage.
And then at the time of posting the photo to facebook you have to select the image from IsolatedStorage.
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
try
{
byte[] data;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
fileStream.Close();
}
}
//MemoryStream ms = new MemoryStream(data);
//BitmapImage bi = new BitmapImage();
//// Set bitmap source to memory stream
//bi.SetSource(ms);
//this.imageTribute.Source = bi;
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = tempJPEG,
ContentType = "image/jpg"
};
fbUpload.SetValue(data);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Notice";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
Thanx to all....
you can do that by two methods :
1) by using mediasharetask in which it will show u all sharing account to which your phone is synced like facebook,gmail,linkdin,twitter,etc : it can be used like like this.
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = path;
shareMediaTask.Show();
2) by using facebook sdk. you can get the package from nuget manager and then u can use it to share on facebook.
I hope this might help u.

How to display images into another page using navigation query string in windows phone 7?

i'm not able to display the images to another page. The images are taken from json. So i'm trying to pass the image url of the selected item of a listbox into a navigagtion query string.The variable i'm trying to pass the data is showing as null.Plese provide me with solution. Thanks
Here the code of the first page:
private void ImageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var lbi = (sender as ListBox).SelectedItem;
if (e.AddedItems.Count > 0)
{
Uri targetPage = new Uri("/DisplayPhoto.xaml?selectedItem="+ lbi.ToString(),UriKind.RelativeOrAbsolute);
NavigationService.Navigate(targetPage);
}
((ListBox)sender).SelectedIndex = -1;
}
Code of the second page:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
Uri uri = new Uri(selectedIndex, UriKind.Absolute);
var img = new Image();
img.Source = new BitmapImage(uri);
img.Height = 400;
img.Width = 400;
listBox1.Items.Add(img);
}
base.OnNavigatedTo(e);
}
Try to escape your parameters with Uri.EscapeUriString
Uri targetPage = new Uri("/DisplayPhoto.xaml?selectedItem="+ Uri.EscapeUriString(lbi.ToString()),UriKind.RelativeOrAbsolute);
NavigationService.Navigate(targetPage);
I prefer sending data via some static property, preferably inside the App class. This way you can "send" complex objects from one page to another.

save image locally & display windows phone 7

I'm trying to implement an app of news (feedrss) by using WP7 i've tried this solution , but it does'nt work for me , here is my code :
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();}
private void Go_Click(object sender, RoutedEventArgs e)
{
WebClient _client = new WebClient();
_client.DownloadStringCompleted += Feed;
Location.Text = "http://www.aufaitmaroc.com/feeds/ma-vie.xml";
_client.DownloadStringAsync(new Uri((Location.Text)));
InitializeComponent();
}
private void Feed(object Sender, DownloadStringCompletedEventArgs e)
{
XElement _xml;
try
{
if (!e.Cancelled)
{
_xml = XElement.Parse(e.Result);
List<FeedItem> l = new List<FeedItem>();
foreach (XElement value in _xml.Elements("channel").Elements("item"))
{
FeedItem _item = new FeedItem();
_item.Title = value.Element("title").Value;
_item.enclosure = value.Element("enclosure").Attribute("url").Value;
_item.Description = Regex.Replace(value.Element("description").Value,
#"<(.|\n)*?>", String.Empty);
_item.Link = value.Element("link").Value;
_item.Guid = value.Element("guid").Value;
_item.Published = DateTime.Parse(value.Element("pubDate").Value);
l.Add(_item);
HttpWebRequest reqest1 = (HttpWebRequest)WebRequest.Create(_item.enclosure);
reqest1.BeginGetResponse(DownloadImageCallback, reqest1);
Thread.Sleep(1000);
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(_item.enclosure), client);
}
listBox.ItemsSource = l;
}
}
catch
{
}
}
IsolatedStorageFile MyStore = IsolatedStorageFile.GetUserStoreForApplication();
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var resInfo = new StreamResourceInfo(e.Result, null);
var reader = new StreamReader(resInfo.Stream);
byte[] contents;
using (BinaryReader bReader = new BinaryReader(reader.BaseStream))
{
contents = bReader.ReadBytes((int)reader.BaseStream.Length);
}
IsolatedStorageFileStream stream = MyStore.CreateFile("10.jpg");
stream.Write(contents, 0, contents.Length);
stream.Close();
}
void DownloadImageCallback(IAsyncResult result)
{
HttpWebRequest req1 = (HttpWebRequest)result.AsyncState;
HttpWebResponse responce = (HttpWebResponse)req1.EndGetResponse(result);
Stream s = responce.GetResponseStream();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
string directory = "Imagestest";
if (!MyStore.DirectoryExists(directory))
{
MyStore.CreateDirectory(directory);
IsolatedStorageFileStream stream = MyStore.CreateFile("10.jpg");
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isoFileStream = myIsolatedStorage.CreateFile(directory + "//ANALYSE_10052013095620.jpg"))
{
var bitimage = new BitmapImage();
var wb = new WriteableBitmap(bitimage);
var width = wb.PixelWidth;
var height = wb.PixelHeight;
// bitimage.SetSource = isoFileStream;
image1.Source = bitimage;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
else
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(directory + "//ANALYSE_10052013095620.jpg"))
{
myIsolatedStorage.DeleteFile(directory + "//ANALYSE_10052013095620.jpg");
}
using (var isoFileStream = myIsolatedStorage.CreateFile(directory + "//ANALYSE_10052013095620.jpg"))
{
var bitimage = new BitmapImage();
var wb = new WriteableBitmap(bitimage);
var width = wb.PixelWidth;
var height = wb.PixelHeight;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
});
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FeedItem currentFeedItem = (FeedItem)listBox.SelectedItem;
PhoneApplicationService.Current.State["FeedItem"] = currentFeedItem;
}
When i run this project , nothing's happend , it does'nt create any folder ,when i stop the internet , images doesnt display anymore.
If you need image caching in your app, I can suggest JetImageLoader library for you
Features:
Caching in memory (so it will work very fast with lists, grids, etc)
Caching is IsolatedStorageFile (to prevent reloading each time)
Fully asynchronous (no lags)
Usage via XAML Binding Converter, you do not have to change your code, just declare converter for Image
But it supports only Windows Phone 8+
I am authour of that library, so if you got any questions, please write to me here or create an issue on github
If you want to save image locally and the display image from locally, then try this sample
http://code.msdn.microsoft.com/wpapps/CSWP8ImageFromIsolatedStora-8dcf8411, on WP 8 it's works fine.

Resources