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;
}
}
Related
I need to convert a JBIG1 image to another image format, such as JPEG or PNG, but I can't seem to find anything related to this.
This JBIG1 image is received encoded in Base64.
I've tried using System.Drawing in .NET to accomplish this, but a "System.ArgumentException: Parameter is not valid" exception is thrown on calling Image.FromStream() using the JBIG1 byte array data.
See code below:
byte[] binData = ConvertFromBase64StringToArray("BASE64 ENCODED JBIG1 IMAGE GOES HERE");
Image img = binData.ConvertToImage();
img.Save("C:/Images/converted-from-jbig.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
Functions used:
public static byte[] ConvertFromBase64StringToArray(string base64String)
{
byte[] data = Convert.FromBase64String(base64String);
using (var stream = new MemoryStream(data, 0, data.Length))
{
data = stream.ToArray();
}
return data;
}
public static Image ConvertToImage(this byte[] byteArrayIn)
{
var ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms); //exception thrown in this line
return returnImage;
}
Does anyone have any knowledge to share about this topic?
You'll probably need a third party library to work with JBig files. It looks like https://github.com/dlemstra/Magick.NET has support for that.
So I'm trying to come up with the code to convert a image to base64 version.
But I get a exception thrown.
System.IO.FileNotFoundException: 'C:\content\images\thumbs\0000001_camping_650.jpeg'
Now I'm working on a copy of the website on my local machine, but the images are stored on the test server. So I'm fairly sure this is where the problem is coming from.
Also the database is nots tored locally either, but on the sql server.
Both the sql server and test server are public facing.
This is the code I'm working with:
string base64String = string.Empty;
// Convert Image to Base64
using (var img = System.Drawing.Image.FromFile(Path.GetFullPath(pictureModel.ImageUrl))) // Image Path from File Upload Controller
{
using (var memStream = new MemoryStream())
{
img.Save(memStream, img.RawFormat);
byte[] imageBytes = memStream.ToArray();
// Convert byte[] to Base64 String
base64String = Convert.ToBase64String(imageBytes);
string ImageBase64 = base64String;
// return base64String;
}
}
Debugging output for this:
System.Diagnostics.Debug.WriteLine(pictureModel.ImageUrl);
System.Diagnostics.Debug.WriteLine(Path.GetFullPath(pictureModel.ImageUrl));
is this:
/content/images/thumbs/0000001_camping_650.jpeg
C:\content\images\thumbs\0000001_camping_650.jpeg
Not sure how to go about solving this one.
Im also working with a bit bucket repository, so the content\images\thumbs\ directory is excluded from the repository.
My solution on the local machine is C:\projects\test-website so I think I just need to figure out that path and is will work for the test and live site.
Cheers
Refactor your code as below:
string base64String = string.Empty;
// Convert Image to Base64
using (var img = System.Drawing.Image.FromFile(Server.MapPath("~") + pictureModel.ImageUrl))) // Image Path from File Upload Controller
{
using (var memStream = new MemoryStream())
{
img.Save(memStream, img.RawFormat);
byte[] imageBytes = memStream.ToArray();
// Convert byte[] to Base64 String
base64String = Convert.ToBase64String(imageBytes);
string ImageBase64 = base64String;
// return base64String;
}
}
Ok so looks like I figured it out.
First step was to copy all the images into the solution.
Then I needed to use the Server.MapPath to get the absolute path to the image.
using (var img = System.Drawing.Image.FromFile(Server.MapPath(pictureModel.ImageUrl))) // Image Path from File Upload Controller
{
using (var memStream = new MemoryStream())
{
img.Save(memStream, img.RawFormat);
byte[] imageBytes = memStream.ToArray();
// Convert byte[] to Base64 String
base64String = Convert.ToBase64String(imageBytes);
string ImageBase64 = base64String;
// return base64String;
}
}
So now when I do this output:
System.Diagnostics.Debug.WriteLine(Server.MapPath(pictureModel.ImageUrl));
I get this path:
C:\projects\test-website\Presentation\Nop.Web\content\images\thumbs\0000001_camping_650.jpeg
I think this will be correct so will accept my answer when I confirm it all works, got another error to figure out now :/
Sigh the joys of coding
If your local machine is not your server machine, you can try to show the path from server to your client machine.
Firstly, you need to share your root folder.
Then, access your shared folder with server's IP address. For example:
'\10.0.0.164\content\images\thumbs\0000001_camping_650.jpeg'
If you were testing on your local machine.
Kindly check if that file exist in your local machine
'C:\content\images\thumbs\0000001_camping_650.jpeg'
or check the location of your application where it is located.
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 have a file that is created using
var recordIntent = new Intent(MediaStore.Audio.Media.RecordSoundAction);
I have no problems retrieving the URI of this file. And I can play it back using MediaPlayer without any difficulties.
However, I would like to send this as a response to my webAPI, and am looking at a way to convert the Audio File represented by this URI to a byte array that I can convert to JSON.
With an image file i can do something like
Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, responseUri);
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
byte[] bitmapData = stream.ToArray();
Is there a similar way I can retrieve the Byte Array data from my audio URI?
edit:
formatting of Audio URI.
responseUri = {content://media/external/audio/media/21}
Taken from a ton of different SO answers, and a little bit of extra conversion for mono from Java I came up with these results.
public String GetRealPathFromUri(Uri contentUri){
String[] proj = {MediaStore.Audio.AudioColumns.Data};
ICursor cursor = ManagedQuery(contentUri, proj, null, null, null);
int column_index = cursor.GetColumnIndex(MediaStore.Audio.AudioColumns.Data);
cursor.MoveToFirst();
return cursor.GetString(column_index);
}
var responseRealPath = GetRealPathFromUri(responseUri);
var getBytes = System.IO.File.ReadAllBytes(responseRealPath);
var responseBase = Convert.ToBase64String(getBytes);
I have literally tried every possible way on this but apparently I just can't figure out the right one.
I am trying to upload images to the next-gen gallery that is installed on a wordpress blog. Everything about xml-rpc is working since I am able to do all other stuff with it.
The problem is that server returns an error saying the image is not a valid one. Which is quite obvious that the problem is about base64. However, for test purposes i copied and checked the base64 string and realized it is just right, it converts right to the image using an external base64 to image converter.
This is the line that submits the query.
result = categories.newImage(1, "admin", "password", newImage);
The struct for newImage is;
public struct imageI
{
public string name;
public string type;
public string bits;
public bool overwrite;
public int gallery;
public int image_id;
}
And this is how a new one is initialized, along with converting an image into base64
//Creating the image base64 string
string filename = "asd.jpg";
Image image1 = Image.FromFile(filename);
string base64 = ImageToBase64(image1, image1.RawFormat);
//for test purposes i copied and checked the base64 and it is just right, it converts right to the image using an external base64 to image converter.
Clipboard.SetText(base64);
//Creating a newImage
imageI newImage = default(imageI);
newImage.name = "newImage";
newImage.bits = base64;
newImage.gallery= 86;
And finally my method "ImageToBase64(Image, ImageFomat)";
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
In case anybody bumps on this, I figured it out, on the line;
newImage.name = "newImage"; the file name should be the same with the one you are uploading, or at least it should have the same extension so that the function in xml-rpc file can resolve the extension and check if it's okay to upload or not.