MVC Convert Base64 String to Image, but ... System.FormatException - c#

My controller is getting an uploaded image in the request object in this code:
[HttpPost]
public string Upload()
{
string fileName = Request.Form["FileName"];
string description = Request.Form["Description"];
string image = Request.Form["Image"];
return fileName;
}
The value of image (at least the beginning of it) looks a lot like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/...
I tried to convert using the following:
byte[] bImage = Convert.FromBase64String(image);
However, that gives the System.FormatException: "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
I get the feeling that the problem is that at least the start of the string isn't base64, but for all I know none of it is. Do I need to parse the string before decoding it? Am I missing something completely different?

It looks like you may just be able to strip out the "data:image/jpeg;base64," part from the start. For example:
const string ExpectedImagePrefix = "data:image/jpeg;base64,";
...
if (image.StartsWith(ExpectedImagePrefix))
{
string base64 = image.Substring(ExpectedImagePrefix.Length);
byte[] data = Convert.FromBase64String(base64);
// Use the data
}
else
{
// Not in the expected format
}
Of course you may want to make this somewhat less JPEG-specific, but I'd try that as a very first pass.

The reason really is "data:image/jpeg;base64,", I'll suggest using this method for removing starting string from base64
var base64Content = image.Split(',')[1];
byte[] bImage = Convert.FromBase64String(base64Content);
This is Shortest solution and you don't have to use magic strings, or write a regex.

Related

String path to base64string

Im having a problem generating a base64string with a specific encoder.
I have an application that generate this base64string
RQA6AFwAUAByAG8AagBlAGMAdABzAFwAWQBvAHUAdAB1AGIAZQAuAE0AYQBuAGEAZwBlAHIAXABZAG8AdQB0AHUAYgBlAC4ATQBhAG4AYQBnAGUAcgAuAE0AbwBkAGUAbABzAC4AQwBvAG4AdABhAGkAbgBlAHIAXABvAGIAagBcAFIAZQBsAGUAYQBzAGUAXABuAGUAdABzAHQAYQBuAGQAYQByAGQAMgAuADAAXABZAG8AdQB0AHUAYgBlAC4ATQBhAG4AYQBnAGUAcgAuAE0AbwBkAGUAbABzAC4AQwBvAG4AdABhAGkAbgBlAHIALgBkAGwAbAAAAA==
which is equal to
E:\Projects\Youtube.Manager\Youtube.Manager.Models.Container\obj\Release\netstandard2.0\Youtube.Manager.Models.Container.dll
Now im trying convert
E:\Projects\Youtube.Manager\Youtube.Manager.Models.Container\obj\Release\netstandard2.0\Youtube.Manager.Models.Container.dll
To base64string but im getting this instead
RTpcUHJvamVjdHNcWW91dHViZS5NYW5hZ2VyXFlvdXR1YmUuTWFuYWdlci5Nb2RlbHMuQ29udGFpbmVyXG9ialxSZWxlYXNlXG5ldHN0YW5kYXJkMi4wXFlvdXR1YmUuTWFuYWdlci5Nb2RlbHMuQ29udGFpbmVyLmRsbA==
I want to get the same result as the first base64string which is
RQA6AFwAUAByAG8AagBlAGMAdABzAFwAWQBvAHUAdAB1AGIAZQAuAE0AYQBuAGEAZwBlAHIAXABZAG8AdQB0AHUAYgBlAC4ATQBhAG4AYQBnAGUAcgAuAE0AbwBkAGUAbABzAC4AQwBvAG4AdABhAGkAbgBlAHIAXABvAGIAagBcAFIAZQBsAGUAYQBzAGUAXABuAGUAdABzAHQAYQBuAGQAYQByAGQAMgAuADAAXABZAG8AdQB0AHUAYgBlAC4ATQBhAG4AYQBnAGUAcgAuAE0AbwBkAGUAbABzAC4AQwBvAG4AdABhAGkAbgBlAHIALgBkAGwAbAAAAA==
How can i do it?
This is my code which is giving me a wrong result
var bytes= Encoding.ASCII.GetBytes(msg);
return Convert.ToBase64String(bytes);
The problem here is the text encoding you're using.
The first Base64 string you posted is encoded using Unicode with a nul terminator byte pair. The trailing 'AAAAA==' is a dead giveaway here. You can see it yourself by examining the byte array:
var originalB64 = "RQA6AFwAUAByAG8AagBlAGMAdABzAFwAWQBvAHUAdAB1AGIAZQAuAE0AYQBuAGEAZwBlAHIAXABZAG8AdQB0AHUAYgBlAC4ATQBhAG4AYQBnAGUAcgAuAE0AbwBkAGUAbABzAC4AQwBvAG4AdABhAGkAbgBlAHIAXABvAGIAagBcAFIAZQBsAGUAYQBzAGUAXABuAGUAdABzAHQAYQBuAGQAYQByAGQAMgAuADAAXABZAG8AdQB0AHUAYgBlAC4ATQBhAG4AYQBnAGUAcgAuAE0AbwBkAGUAbABzAC4AQwBvAG4AdABhAGkAbgBlAHIALgBkAGwAbAAAAA==";
var bytes = Convert.FromBase64String(originalB64);
Converting this to a string will give you a null-terminated string 125 characters long, with the last character being nul.
Given a path that is not nul-terminated you can reproduce that string as follows:
string path = #"E:\Projects\Youtube.Manager\Youtube.Manager.Models.Container\obj\Release\netstandard2.0\Youtube.Manager.Models.Container.dll";
string newB64 = Convert.ToBase64String(Encoding.Unicode.GetBytes(path + "\0"));
This matches the original Base64 string exactly in my tests.

itextsharp : Index was outside the bounds of the array when inserting binary image to PDF [duplicate]

Still A Newbie.
I would like to replace the long Base64 string with a variable but keep getting error: Index was outside the bounds of the array.
Scenario: I am retrieving the full base64 string from SQL database e.g data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
I then split the string for the section that I want that is after the ','.
public SqlDataReader reader;
public String ClientSigImg;
public String ClientSigImg1;
ClientSigImg = reader[0].ToString();
ClientSigImg1 = ClientSigImg.Split(',')[1];
So the above base64 string changes on user input and instead of manual input like below
string base64 = #"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
byte[] imageBytes = Convert.FromBase64String(base64);
I would like to replace that long string with:
string base64 = #""+ ClientSigImg1 +"";
byte[] imageBytes = Convert.FromBase64String(base64);
It looks as though:
ClientSigImg = reader[0].ToString();
Is NOT returning a string with a comma in it (please debug and confirm). This means that you will see the error you are describing when this line of code runs:
ClientSigImg1 = ClientSigImg.Split(',')[1];
This is because index 1 will not exist. So, check that you are actually getting the correct data returned from your query.
In addition, once your query does return the correct data you can tidy your code and simply use:
byte[] imageBytes = Convert.FromBase64String(ClientSigImg1);
That is because:
string base64 = #""+ ClientSigImg1 +"";
Doesn't actually do anything other than add empty string before and after your string, hence, doesn't add anything!

Passing base64 string using c# string variable. Error: Index was outside the bounds of the array

Still A Newbie.
I would like to replace the long Base64 string with a variable but keep getting error: Index was outside the bounds of the array.
Scenario: I am retrieving the full base64 string from SQL database e.g data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
I then split the string for the section that I want that is after the ','.
public SqlDataReader reader;
public String ClientSigImg;
public String ClientSigImg1;
ClientSigImg = reader[0].ToString();
ClientSigImg1 = ClientSigImg.Split(',')[1];
So the above base64 string changes on user input and instead of manual input like below
string base64 = #"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
byte[] imageBytes = Convert.FromBase64String(base64);
I would like to replace that long string with:
string base64 = #""+ ClientSigImg1 +"";
byte[] imageBytes = Convert.FromBase64String(base64);
It looks as though:
ClientSigImg = reader[0].ToString();
Is NOT returning a string with a comma in it (please debug and confirm). This means that you will see the error you are describing when this line of code runs:
ClientSigImg1 = ClientSigImg.Split(',')[1];
This is because index 1 will not exist. So, check that you are actually getting the correct data returned from your query.
In addition, once your query does return the correct data you can tidy your code and simply use:
byte[] imageBytes = Convert.FromBase64String(ClientSigImg1);
That is because:
string base64 = #""+ ClientSigImg1 +"";
Doesn't actually do anything other than add empty string before and after your string, hence, doesn't add anything!

The input is not a valid Base-64 string as it contains a non-base 64 character, "

C# code:
string base64string = Textbox1.Text;
string converted = base64string.Replace('-', '+');
converted = converted.Replace('_', '/');
try
{
// Convert base64string to bytes array
Byte[] bytes = Convert.FromBase64String(converted);
gif = iTextSharp.text.Image.GetInstance(bytes);
}
Textbox1.Text contains
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABUYAAADICAYAAAAkwztuAAAgAElEQVR4Xu3db6wdVd0v8KX2UGlLRfPE8JgIWiUc3yikvqt/ohi1L1Q04u2VCiVq0UpjTIAcCUewxj9YOAakgR7808TEe28rFpOSFKI3xPhGQk1jWyOJN+gLlQYLCtQoT4V7Zj+Z7Zw5s//v2XvNzKdJE+nZs+a3Pr91tvt8z5qZl7y49Cf4Q4AAAQIECBAgQIAAAQIECBAgQIAAgQYJvEQw2qBumyoBAgQIECBAgAABAgQIECBAgAABAi0BwaiFQIAAAQIECBAgQIAAAQIECBAgQIBA4wQEo41ruQkTIECAAAECBAgQIECAAAECBAgQICAYtQYIECBAgAABAgQIECBAgAABAgQIEGicgGC0cS03YQIECBAgQIAAAQIECBAgQIAAAQIEBKPWAAECBAgQIECAAA....
its a correct format but still i am getting error.
You need to skip this: data:image/png;base64,, so try something like:
string base64string = Textbox1.Text.Substring(22);
This will fetch everything after the first 22 characters in you string. Note that you might want to verify that there are more than 22 characters in the text-box before doing this, just to make sure it's not empty.
EDIT: Perhaps an even better approach would be:
var text = Textbox1.Text;
var metadataStart = text.IndexOf("data:image/png;base64,");
if(start != -1)
{
// Remove the metadata if found
text = text.Remove(metadataStart, metadataStart + 22);
}
After this, you can go ahead and convert text.
You need to strip the starting data:image/png;base64,. The rest of the string looks like valid BASE64, but everything up to and including the comma does not belong in there.
You need to split this: data:image/png;base64,so try something like
try
{
string base64string = Textbox1.Text.Split(',')[1];
//Convert base64string to bytes array
Byte[] bytes = Convert.FromBase64String(base64string);
gif = iTextSharp.text.Image.GetInstance(bytes);
}

Is this 64-bit Encoded?

All of the passwords in our User DB look like this where we have == at the end:
91F2FSEYrFOcabeHK/UfNw==
So how can I tell if this is 64-bit encoded? It has to be because I can decode using a decode 64-bit routine I have.
I am trying now to figure out how to decode a literal string to 64-bit..back to the xxxxxxxx== and here is my code:
string passwordToEncrypt = "test";
byte[] passwordToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(passwordToEncrypt);
result = Convert.ToBase64String(passwordToBytes);
Updated:
I need the text test to come out in Base64 with the == at the end.
you have a typo in there - so the above code does not compile, try
string passwordToEncrypte = "test";
byte[] passwordToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(passwordToEncrypte);
string result = Convert.ToBase64String(passwordToBytes);
result contains now a "Base64"-encoded password and end with "=="...
BUT the above code works only for passwords containing ASCII... if you want it to work with UTF8 passwords then change it to :
string passwordToEncrypte = "test";
byte[] passwordToBytes = Encoding.UTF8.GetBytes(passwordToEncrypte);
string result = Convert.ToBase64String(passwordToBytes);
to go back from Base64 to the original you need to do:
string Original = Encoding.UTF8.GetString (Convert.FromBase64String(result));
see http://msdn.microsoft.com/en-us/library/86hf4sb8.aspx
and http://msdn.microsoft.com/en-us/library/system.convert.tobase64string.aspx
and http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx
Base64 encoded string doesn't always end with a =, it will only end with one or two = if they are required to pad the string out to the proper length.For more details checkout following link
Padding

Categories

Resources