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.
Related
Please help finding a solutions to this problem. I have an image string encoded in base64 in sql server database by using this function in c#
public string ImageToBase64()
{
string path = "D:\\SampleImage.jpg";
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
i use this code to retrieve the image data in android
Byte[] imageBytes = Base64.decode(rs.getstring("imagedata"), Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
imageView.setImageBitmap(decodedImage);
The following error shows in log :
D/skia: --- Failed to create image decoder with message
'unimplemented'
Please help..
Finally i find the answer,
Just don't use any encoding technics while converting image to and from image datatype .. Both while inserting to sql server and getting data from db.
Thanks !!
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 have method like this,
public static void Base64ToImageAndSave(string rawData, string path)
{
string parsedData;
parsedData = rawData.Contains(',')
? rawData.Substring(rawData.IndexOf(',') + 1)
: rawData;
byte[] imageBytes = Convert.FromBase64String(parsedData);
using (MemoryStream memoryStream = new MemoryStream(imageBytes))
{
using (Image image = Image.FromStream(memoryStream))
{
image.Save(path, ImageFormat.Jpeg);
}
}
}
I send base64 parameter for save the picture as a jpeg file. But I have this error
A generic error occurred in GDI+
on this line,
image.Save(path, ImageFormat.Jpeg);
I use using for dispose, but still have error. How can i solve this problem? thanks.
For future reference:
If you are getting the same error , then we can say that you don't have a write permission on some directory.
For example, if you are trying to save the Image from the memory stream to the file system , you may get that error.
Make sure to add write permission in folder or for the network service account.
Hope this helps!
I have a div with an image inside of it. In javascript I am getting the div, and sending the innerHTML of the div to the server. The javascript is oversimplified below:
function uploadImage() {
var imageInfo = document.getElementById('divImage').innerHTML;
PageMethods.uploadImage(imageInfo, onSuccess, onError);
} //end function
I am currently receiving this on the server as a string.
[WebMethod]
public static string uploadImage(string base64FileString){...}
The results are as follows:
<img height="150" width="150" title="name.png" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...../>
I need to save this image to disk, and I'm at a loss. It's my understanding that I could get everything past the "base64," (using a split) and create an image using the following:
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64FileString);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
image.Save(.....);
But this seems very inefficient. Is there a better way to create the image from the string, a better way to receive the string, or better way to pass the string?
You can use File.WriteAllBytes:
byte[] imageBytes = Convert.FromBase64String(base64FileString);
File.WriteAllBytes(path, imageBytes);
Absolutely no need to go through MemoryStream and the System.Drawing namespace once you have the byte[].
I know there must be a better way to do this, but I have a solution that at least works. If anyone can point out a more sophisticated way I'm all ears. I would have assumed there was some sort of object that would receive the img on the server to save to disk, but maybe not.
Javascript and webmethod remain unchanged. I passed the InnerHTML of the div to the server, and accept it as a string. On the server I used multiple splits (which I understand to be very slow) to get at the base64 part of the image.
[WebMethod]
public static string uploadImage(string base64FileString){
//Get all of the text right of the comma
string base64PartTemp= base64FileString.Split(',')[1];
//The final part of the base64 had a \" to remove
//Now base64PartFinal is the base64 part of the image only
string base64PartFinal= base64PartTemp.Split('\"')[0];
//Get all of the text to the right of the period from original string
string fileTypePart = base64FileString.Split('.')[1];
//Because the file is an image the file type will be 3 chars
string fileType = fileTypePart.Substring(0, 3);
//Use a new guid for the file name, and append the fileType
string finalFileName = Guid.NewGuid() + "." + fileType;
//Turn the final base64 part into byte array
byte[] imageBytes = Convert.FromBase64String(base64PartFinal);
//Get the working directory of the project to store the files
string path= System.AppDomain.CurrentDomain.BaseDirectory.ToString();
//Append that I want to put the image in the images folder, under a designated filename
path += "Images/" + finalFileName;
//Write the image to file
File.WriteAllBytes(path, imageBytes);
...
}
I couldn't find an answer to this for a few days. I hope it helps someone. Like I said, may not be the most efficient solution, but it does work.
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.