I want to get UIImage from Asset Library Url
I'm an developing app in xamarin ios, trying to get a UIImage Object from a given Asset-Library-Url.
Picked multiple images from gallery using ELCImagePickerViewController.
All image paths are added in string array list.
Now i need to get all the images in Byte[] using the Asset-Library-Url path.
The given Url is:
assets-library://asset/asset.JPG?id=0E126068-14F9-431F-91B5-8BC397727656&ext=JPG
I tried it with the following approach :
static UIImage FromUrl(string uri)
{
using (var url = new NSUrl(uri))
using (var data = NSData.FromUrl(url))
return UIImage.LoadFromData(data);
}
But it always returns null.
Can anybody please tell me what i'm doing wrong here?
These Urls are for the ALAssetsLibrary, you will need to use the ALAssetsLibrary to access them. See example below:
public Byte[] LoadAssetAsByteArray(string uri)
{
var nsUrl = new NSUrl(uri);
var asset = new ALAssetsLibrary();
Byte[] imageByteArray = new Byte[0];
UIImage image;
asset.AssetForUrl(nsUrl,(ALAsset obj) => {
var assetRep = obj.DefaultRepresentation;
var cGImage = assetRep.GetFullScreenImage();
image = new UIImage(cGImage);
// get as Byte[]
imageByteArray = new Byte[image.AsPNG().Length];
//imageView.Image = image;
},
(NSError err) => {
Console.WriteLine(err);
});
return imageByteArray;
}
There is a great recipe using a UIImagePickerController on the Xamarin Site which I beleive would help you
Related
I've been struggling with this implementation for a few hours now and can't seem to find any solutions wherever I look (SO, Xamarin Forums, Google etc)...
In this current scenario I have a few images in .Droid.Resources.Drawable which I wish to access and convert into a byte[] from my shared code. This is due to the fact that I wish to test the full span of my CRUD functionality on a REST API I've set up as an end-point for our server.
The images show up fine in the application, but for some reason I simply can't seem to warp my head around the process of converting these images to a byte[] in Xamarin. I've done it countless times in 'normal' C#...
Sorry if the code is a bit messy, but I'm sure you get the idea.
I want to get an image from .Droid storage (will be ported for iOS later)
Convert said image into a byte[]
Send that byte[] representation to my API.
In the code's current state I'm getting this error:
C#: An instance of an abstract class can not be created
Where I'm attempting to create a new Stream (new Stream(sauce))
The below example is based on snippets found here and full credit goes to Sten and Vincent.
/*
* Takes an arbitrary string as a token, updates a record with dummy data and a placeholder_image.
*/
public async Task<string> PostUpdateFoundation(string arbitrary, Image img)
{
ImageSource sauce = ImageSource.FromFile("abc.png");
byte[] byte_img = FromStreamToByte(new Stream(sauce)); //error occurs here
Debug.WriteLine("I'm in!");
var client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
var content = new StringContent(arbitrary);
var response = await client.PostAsync(String.Format("http://some.api.to.test.com?s={0}&img={1}", arbitrary, byte_img), content);
var result = response.Content.ReadAsStringAsync().Result;
return result;
}
/*
* Attempts to convert an stream (based on image source) into a byte[].
*/
public static byte[] FromStreamToByte (Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
Try using Plugin.Media
byte BImageSource = ReadFully(file.GetStream());
var bytes = new byte[file.GetStream().Length]; //file is from the plugin and contains your image
file.GetStream().Position = 0;
file.GetStream().Read(bytes, 0, (int)file.GetStream().Length);
BImageSource = ReadFully(file.GetStream()); //BImageSource is your resource in bytes
byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
Hope this helps!
I am trying to Deserialize and serialize json data from Wikipedia API. At first I need to Deserilize some particular data like Title,Extract, Images, Co-ordinates etc.After Deserialization , I need to serialize this data again to get resulted output. But which serialization I am having problem that is the Wikipedia API there are some images in png format. But in my code I can convert only jpg image to hash format. so when .png file occurred, it goes to exception handling and nothing shows as output. I would like to know how can I write my code which can convert both jpg and png image. My code is as follows-
using (WebClient client = new WebClient())
{
try
{
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=48.47|9.11&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20");
var json = JsonConvert.DeserializeObject<RootObject>(response);
List<Poi> poi = new List<Poi>();
foreach (var page in json.query.pages) //foreach statement cannot operate on variables of type 'List_Places_Geo.RootObject' because 'List_Places_Geo.RootObject' does not contain a public definition for 'GetEnumerator'
{
Poi obj = new Poi();
obj.Title = page.title;//what to write in this line to get the title;
obj.Description =page.extract ;
var Image = new PoiImage();
var ImgfirstKey = page.thumbnail.source;
Image.ImageID = string.Format("{0:X}.jpg", ImgfirstKey.GetHashCode());
obj.Images = new List<PoiImage> {Image};
obj.Lat = page.coordinates.First().lat;
obj.Lon = page.coordinates.First().lon;
poi.Add(obj);
}
string result = JsonConvert.SerializeObject(poi, Formatting.Indented);
Console.WriteLine(result);
}
catch(Exception)
{
Console.WriteLine("Error");
}
}
My Wikipedia api looks like this-
https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=52.5243700|13.4105300&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20
try this Code. Might be helpful for you . Get Images Directly from Path (You will definitely get a path of Each Image ) and Change it into Base64 encoded String and pass it in JSONObject.
At other end decode it using Base64 Class decoder and Write it as a file.
Here a code to encode the Image Directly from Path
using (Image image = Image.FromFile(Path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
I am trying to develop a simple Windows 8 Metro app which simply downloads an image file from a given URL (say http://sample.com/foo.jpg) and then save it to Pictures Library.
I have an image control in the UI to display the downloaded image.
I'm also facing difficulty in setting the image source for the image control to the newly downloaded image (actually I'm not even able to download it).
Also, is it possible to store the image file in a particular folder in the Pictures library (if it doesn't exist, then the app should create it)?
I'm really stuck here.
Please help me.
Here's some rough code that I believe accomplishes what you want. It assumes you have two image controls (Image1 and Image2) and that you have the Pictures Library capability checked in the manifest. Take a look at the XAML images sample as well
Uri uri = new Uri("http://www.picsimages.net/photo/lebron-james/lebron-james_1312647633.jpg");
var fileName = Guid.NewGuid().ToString() + ".jpg";
// download pic
var bitmapImage = new BitmapImage();
var httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(uri);
byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();
// create a new in memory stream and datawriter
using (var stream = new InMemoryRandomAccessStream())
{
using (DataWriter dw = new DataWriter(stream))
{
// write the raw bytes and store
dw.WriteBytes(b);
await dw.StoreAsync();
// set the image source
stream.Seek(0);
bitmapImage.SetSource(stream);
// set image in first control
Image1.Source = bitmapImage;
// write to pictures library
var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
fileName,
CreationCollisionOption.ReplaceExisting);
using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
}
}
}
// read from pictures library
var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
using ( var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read) )
{
bitmapImage.SetSource(pictureStream);
}
Image2.Source = bitmapImage;
}
I'm currently trying to build an app that involves the user selecting a photo from their library (or taking a photo) and uploading it to Imgur. I have already built a fairly robust C# Imgur client for Windows Forms applications, but unfortunately porting it to the Windows Phone has been a disaster.
Here is the code that I am using:
public void UploadImageAsync(Stream PhotoStream)
{
try
{
WebClient w = new WebClient();
w.Headers["Content-type"] = "application/x-www-form-urlencoded";
string data = "key="+PublicKey+
"&_fake_status=200"+
"&type=base64"+
"&image="+PhotoStreamToBase64(PhotoStream);
w.UploadStringAsync(new Uri("http://api.imgur.com/2/upload", UriKind.Absolute), "POST", data);
}
catch (Exception ex)
{
}
}
string PhotoStreamToBase64(Stream PhotoStream)
{
MemoryStream memoryStream = new MemoryStream();
PhotoStream.CopyTo(memoryStream);
byte[] result = memoryStream.ToArray();
return System.Convert.ToBase64String(result);
}
What is interesting (and frustrating) is that it appears as though everything is working fine, and I receive a successful response after the upload has completed. However, when trying to view the image after being uploaded, the result looks like this: http://i.imgur.com/NWY0R.jpg.
This leads me to believe that somehow the image stream is being converted into the byte array incorrectly, or converted into a base 64 string incorrectly. In any case, I cannot get it to work and I am at a total loss. Does anybody have any idea? Any help would be greatly appreciated.
SpikeX pushed me toward Imgur's C# API example for image uploading. Borrowing the Base64 encoding logic from their example fixed the issue. Here is the now functional PhotoStreamToBase64 method:
string PhotoStreamToBase64(Stream PhotoStream)
{
MemoryStream memoryStream = new MemoryStream();
PhotoStream.CopyTo(memoryStream);
byte[] result = memoryStream.ToArray();
string base64img = System.Convert.ToBase64String(result);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < base64img.Length; i += 32766)
{
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(32766, base64img.Length - i))));
}
return sb.ToString();
}
What is the C# equivalent of the following Java snippet below:
Drawable image;
URL imageUrl;
imageUrl = new URL(getMyImageUrl(imageNumber));
Bitmap bitmap = BitmapFactory.decodeStream(imageUrl.openStream());
image = new BitmapDrawable(bitmap);
Thanks in advance.
A more literal conversion to C# would be:
var imageUrl = new Java.Net.URL(GetMyImageUrl(imageNumber));
var bitmap = Android.Graphics.BitmapFactory.DecodeStream (imageUrl.OpenStream ());
var image = new Android.Graphics.Drawables.BitmapDrawable (bitmap);
This is one of the strengths of Mono for Android: the classes and methods mirror the underlying Java platform (with some exceptions) while providing much of the .NET framework, so migrating code from Java to C# should be reasonably straightforward.
using System.Drawing;
using System.Drawing.Imaging;
public Bitmap DownloadImage(string imageUrl)
{
try
{
WebClient client = new WebClient();
using(Stream stream = client.OpenRead(imageUrl))
{
Bitmap bitmap = new Bitmap(stream);
}
}
catch(Exception)
{
//todo: handle me
throw;
}
return bitmap
}
Have a look at http://www.dreamincode.net/code/snippet2555.htm . I assumed you would want to use Bitmap. I have never used Drawable in Java, so correct me if I'm wrong.