The problem seem originated from this line:
byte[] picture = Convert.FromBase64String(base64img);
If the base64img contains some header like data:image/png;base64, then Convert.FromBase64String() fails because the string is not fully formatted in Base64 format. Consider using string.Split() before converting from string parameter to remove corresponding Base64 header:
[HttpPost]
public ActionResult LoadImage(Car car, string base64img)
{
// split the header and content, separated by comma
var base64arr = base64img.Split(',');
byte[] picture = Convert.FromBase64String(base64arr[1]);
// do something with the image
return View();
}
If the content string contains characters other than ASCII or trailing padding ones, you should remove them like this:
string base64str = base64arr[1];
string processed = base64str.Replace('_', '/').Replace('-', '+');
switch (base64str.Length % 4)
{
case 2:
processed += "==";
break;
case 3:
processed += "=";
break;
}
byte[] picture = Convert.FromBase64String(processed);
Also consider using FormData object when passing image formatted with Base64 string:
$('#modalWindow').on('click', '#send', function () {
var file = $('#autoPicture').attr('src');
// note: if you send other form data, use 'serializeArray()' or 'serialize()'
var formData = new FormData();
// append other form contents here
formData.append("base64img", file);
$.ajax({
type: "POST",
url: "/Home/LoadImage",
data: formData,
success: function (data) {
alert('ะัะธะฒะตั');
},
error: function (error) {
alert(error.responseText);
}
});
});
Note:
The equals sign like = or == at the end of Base64 encoded string serves as trailing padding characters and not all Base64 encoded strings ended with them. You can see the reason behind padding here.
Convert base64 strings to byte array
C# Convert a Base64 -> byte[] - Stack Overflow
Base64 decode string to byte array
python - How to convert a Base64 file to bytes? - Stack Overflow
just two lines could solve this problem:
import base64
base64_code = "VER30QHI30JFOIAIO3020085723F" # this is just an example
img_data = base64_code.encode()
content = base64.b64decode(img_data)
with open('/path/to/your/image.jpg', 'wb') as fw:
fw.write(content)
print(content)
then you could check the image bytes.
you can find the following here:
import base64
base64_message = 'UHl0aG9uIGlzIGZ1bg=='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
Source: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/
Hi everyone so my question is very simple.
Are there any performance gains when storing a base64 as a byte[] or string type?
Imagine the following scenario
Example piece of code
PS: Sorry for my bad english, it's not my native language.