Xamarin.Forms get image path - image

Using the Xamarin.Forms Camera sample from here - https://github.com/XForms/Xamarin-Forms-Labs-Samples/tree/master/XF.Labs.CameraSample i am able to select or take a photo. I then need to convert this image to binary
so here is the code that selects the image:
private async Task SelectPicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
var mediaFile = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
img.Source = imageSource;
}
and the code that takes the image is very similar
private async Task TakePicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
var mediaFile = await mediaPicker.TakePhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
img.Source = imageSource;
}
How do i get the actual string imagePath from the above so that i can call the DependencyService below?
public byte[] ImageToBinary(string imagePath)
{
FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int)fileStream.Length);
fileStream.Close();
return buffer;
}

Shouldn't do this stuff tired
It is built in to the MediaFile so the answer is simply mediaFile.Path.ToString();

mediaFile.Path will give you the actual path

Related

Xamarin : Convert image to Pdf format in Xamarin.forms

I am getting error width cannot be null , when passing image to inputstream.As i didn't find any alterante method . Basically i want to convert image to Pdf format in Xamarin.forms which supports UWP platform .
I am using xfinium pdf library for this.
public void ConvertJpegToPdf()
{
try
{
PdfFixedDocument document = new PdfFixedDocument();
Xfinium.Pdf.PdfPage page = document.Pages.Add();
page.Width = 800;
page.Height = 600;
var imageStream = GetStream();
PdfJpegImage jpeg = new PdfJpegImage(imageStream);//<-Error
PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 24);
PdfBrush brush = new PdfBrush(PdfRgbColor.Red);
page.Graphics.DrawImage(jpeg, 0, 0, page.Width, page.Height);
Stream pdfStream = null;
document.Save(pdfStream);
}
catch (Exception ex)
{
throw ex;
}
}
protected Stream GetStream()
{
byte[] byteArray = Encoding.UTF8.GetBytes("http://david.qservicesit.com/images/3.jpg");
MemoryStream stream = new MemoryStream(byteArray);
return stream;
}
Please suggest some alternate to do this
byte[] byteArray = Encoding.UTF8.GetBytes("http://david.qservicesit.com/images/3.jpg");
You could not get image stream in this way. The method you have used can only get the Bytes of string. For your scenario, you could use http client to acquire image stream. Please refer to the following code:
public async Task<Stream> GetStream()
{
HttpClient client = new HttpClient();
HttpResponseMessage res = await client.GetAsync(new Uri("http://david.qservicesit.com/images/3.jpg"));
Stream stream = await res.Content.ReadAsStreamAsync();
return stream;
}
public async Task ConvertJpegToPdf()
{
try
{
PdfFixedDocument document = new PdfFixedDocument();
Xfinium.Pdf.PdfPage page = document.Pages.Add();
page.Width = 800;
page.Height = 600;
var imageStream = await GetStream();
PdfJpegImage jpeg = new PdfJpegImage(imageStream);
PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 24);
PdfBrush brush = new PdfBrush(PdfRgbColor.Red);
page.Graphics.DrawImage(jpeg, 0, 0, page.Width, page.Height);
Stream pdfStream = new MemoryStream();
document.Save(pdfStream);
}
catch (Exception ex)
{
throw ex;
}
}

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));
}

Passing cookies to Image.GetInstance

Using image handler to convert relative path to absolute.
protected byte[] ConvertHTMLToPDF(string HTMLCode)
{
if (Request.Url == null)
throw new Exception();
var doc = new Document(PageSize.A4);
doc.Open();
var interfaceProps = new Hashtable();
var ih = new ImageHander {BaseUri = Request.Url.ToString()};
interfaceProps.Add("img_provider", ih);
foreach (IElement element in HTMLWorker.ParseToList(new StringReader(HTMLCode), null, interfaceProps))
{
doc.Add(element);
}
var _xmlr = new XmlTextReader(new StringReader(HTMLCode));
HtmlParser.Parse(doc, _xmlr);
var stream = new MemoryStream();
PdfWriter.GetInstance(doc, stream);
doc.Close();
return stream.ToArray();
}
class:
public class ImageHander : IImageProvider
{
public string BaseUri;
public Image GetImage(string src, Hashtable h, ChainedProperties cprops, IDocListener doc)
{
string imgPath;
if (src.ToLower().Contains("http://") == false)
imgPath = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + src;
else
imgPath = src;
return Image.GetInstance(imgPath);
}
}
imgPath at the end is correct. But it's not static file, it's url of action that returns image, so I need to pass cookies when requesting image. Is it possible?
Yes, it is possible, but you're gonna have to send the request yourself and not rely on the Image.GetInstance method. For example using the HttpClient you could send cookies along with the request:
var imageUrl = new Uri(imagePath);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
cookieContainer.Add(
new Uri(imageUrl.GetLeftPart(UriPartial.Authority)),
new Cookie("CookieName", "cookie_value")
);
var response = client.GetAsync(imageUrl).Result;
response.EnsureSuccessStatusCode();
Stream imageStream = response.Content.ReadAsStreamAsync().Result;
// You've got the Stream here, read the documentation of iTextSharp
// how to create an Image instance from a Stream:
return Image.FromStream(imageStream); // ?????
// or maybe there's a method allowing you to create an Image from byte[]
byte[] imageData = new byte[imageStream.Length];
imageStream.Read(imageData, 0, imageData.Length);
return Image.FromByteArray(imageData); // ?????
}

How to load an image from isolated storage into image control on windows phone?

I am using this code for storing the image into isolate storage at the time of camera action completed.
void camera_Completed(object sender, PhotoResult e)
{
BitmapImage objImage = new BitmapImage();
//objImage.SetSource(e.ChosenPhoto);
//Own_Image.Source = objImage;
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
fnam = e.OriginalFileName.Substring(93);
MessageBox.Show(fnam);
if (isolatedStorage.FileExists(fnam))
isolatedStorage.DeleteFile(fnam);
IsolatedStorageFileStream fileStream = isolatedStorage.CreateFile(fnam);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 100, 100);
MessageBox.Show("File Created");
fileStream.Close();
}
}
Now I want to take the image from isolated storage and display it in my image control.
Is it possible?
Yes it is. You can use this function to load image from IsolatedStorage:
private static BitmapImage GetImageFromIsolatedStorage(string imageName)
{
var bimg = new BitmapImage();
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = iso.OpenFile(imageName, FileMode.Open, FileAccess.Read))
{
bimg.SetSource(stream);
}
}
return bimg;
}
Usage:
ImageControl.Source = GetImageFromIsolatedStorage(fnam);
Something like this:
public BitmapImage LoadImageFromIsolatedStorage(string path) {
var isf = IsolatedStorageFile.GetUserStoreForApplication();
using (var fs = isf.OpenFile(path, System.IO.FileMode.Open)) {
var image = new BitmapImage();
image.SetSource(fs);
return image;
}
}
In your code
image1.Source = LoadImageFromIsolatedStorage("image.jpg");
check this snippet
public static void SaveImage( string name)
{
var bitmap = new BitmapImage();
bitmap.SetSource(attachmentStream);
var wb = new WriteableBitmap(bitmap);
var temp = new MemoryStream();
wb.SaveJpeg(temp, wb.PixelWidth, wb.PixelHeight, 0, 50);
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorage.DirectoryExists("foldername"))
{
myIsolatedStorage.CreateDirectory("foldername");
}
var filePath = Path.Combine("foldername", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, myIsolatedStorage))
{
fileStream.Write(((MemoryStream)temp).ToArray(), 0, ((MemoryStream)temp).ToArray().Length);
fileStream.Close();
}
}
}

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