1

How would I go about debugging what's wrong with a string that I believe is in Base64 format, but which in VB using the below line of code

Dim theImage As Drawing.Image = imageUtils.Base64ToImage(teststring)

throws the following exception?

{"Base64ToImage(): 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. "}

The test string itself is far too long to paste here; I tried but reached (a lot) over the character limit. I've tried a few online conversion tools and it doesn't seem to work there either. At first I thought I was passing the string wrong from my ajax call to the web method VB code behind...but I've tried hard-coding my string into the function as well with the same failure. So, I'm convinced the string itself is bad data.

It looks like:

Dim teststring = "dataImage/ png;base64, 
iVBORw0KGgoAAAANSUhEUgAAB4AAAAQ4CAYAAADo08FDAAAgAElEQVR4Xuy9268sWbbe9UVE3i / 
rvte + V....K/1Tx5/8A736wVclDQN4AAAAASUVORK5CYII="

But I also tried removing the "dataImage" part and using

Dim teststring = 
"iVBORw0KGgoAAAANSUhEUgAAB4AAAAQ4CAYAAADo08FDAAAgAElEQVR4Xuy9268sWbbe9UVE3i / 
rvte + V....K/1Tx5/8A736wVclDQN4AAAAASUVORK5CYII="

And it doesn't make a difference.

I am getting this string in javascript using this function:

btnFreeze.onclick = video.onclick = function (e) {
                e.preventDefault();
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                canvas.getContext('2d').drawImage(video, 0, 0);
                alert("got here");
                $hfLicenseScreenshot.val(canvas.toDataURL());
                $img.css("background-image", "url(" + $hfLicenseScreenshot.val() + ")");
                $("#hiddenTextbox").val($hfLicenseScreenshot.val());
                //$("#save").show();
                return false;
            };

...where ultimately the string is from

canvas.toDataURL()

and about halfway through that function there is a hidden field called $hfLicenseScreenshot, from which I am saving the value into a "hidden" textbox (I dont know why my variable was getting lost, I know it's redundant but that's why I saved the value to a textbox called hiddentextbox. I get the sstring from hiddentextbox later, like:

$("#hiddenTextbox").val().toString();

So, I have no idea how to go about debugging this image base 64 string. I've tried different images taken from my webcam and it's just not working with any of them. Any ideas?

...I don't know if it's been serialized or not, since I think the JSON stringify method is supposed to do that. I might be confused there.

...Here is my ajax call:

$.ajax({
    type: "POST",
    url: "/BackCode/FirstPage.aspx/SaveData",
    data: JSON.stringify({ currentData: currentData, str: makeblob(str) }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    currentData: currentData,
    success: function (resp) {
        resp = resp.d;
        if (resp.success) {
            if (typeof callback === "function")
                callback.apply(this, [resp]);
            load();

        } else {
            $.statusMessage(resp.statusMessage, "red");
        }
    },
    error: function (jsonObject, textStatus, errorThrown) {
        $.statusMessage(errorThrown, "red");
    }
});

I have also been having issues with this, and it goes into the last error function a lot:

$.statusMessage(errorThrown, "red");

So I don't know whether I'm passing it correctly either.

PBJ
  • 354
  • 2
  • 15
  • You seem to have have a lot of space characters in your base64 string... – Pseudonymous Aug 22 '19 at 10:51
  • Yes, there are. Is that a problem? That's just what resulted from canvas.toDataURL() so I assumed that was fine. I'll try a function later, to remove spaces/newlines and see if that helps! I hope you're right because this post seems also to indicate that will help: https://stackoverflow.com/questions/3092019/can-a-base64-encoded-string-contain-whitespace – PBJ Aug 22 '19 at 13:55
  • Spaces aren't valid standard base64 characters so could well be the issue. Let me fire up a bit of VB and see, will report back. – Pseudonymous Aug 22 '19 at 19:26

2 Answers2

1

The following works for me:

Dim base64String = "Qk2uAAAAAAAAADYAAAAoAAAABgAAAAYAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA////AAAAAAAAAAAAAAAA////AAAAAAD///////////////8AAAAAAP///////////////////////wAA////////////////////////AAD///8AAAD///////8AAAD///8AAP///////////////////////wAA"

Dim base64Bytes = Convert.FromBase64String(base64String)

Using memoryStream = New MemoryStream(base64Bytes)
    Dim image As Image = Image.FromStream(memoryStream)
    image.Save($"C:\Users\{Environment.UserName}\Desktop\Smile.bmp")
End Using

I've removed the initial metadata which indicates what type of image it is, the original string was:

data:image/bmp;base64,Qk2uAAAAAAAAADYAAAAoAAAABgAAAAYAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA////AAAAAAAAAAAAAAAA////AAAAAAD///////////////8AAAAAAP///////////////////////wAA////////////////////////AAD///8AAAD///////8AAAD///8AAP///////////////////////wAA

Try removing the spaces from your base64 encoding - as they're not a valid base64 character - and the metadata from the start.

Here are the valid base64 characters taken from Wikipedia: Valid Base64 Characters

Pseudonymous
  • 839
  • 5
  • 13
0

I tried removing whitespace like some other suggestions here, and that did not fix my problem (although I'm sure that was likely a secondary problem).

In my case, my string wasn't actually a valid image at all because I had tried to pass it from Ajax to the VB WebMethod as an object (this was because passing as a string was not working). And at one point I had tried converting it to a Blob object....so my test string was just something totally invalid. I should have just left it as a string in both front end and backend. So, I don't even know what my string one that I posted earlier, but it wasn't an image.

Eventually I realized that my string on the front-end was too long, which was my actual/original issue. Now I realize the irony of having mentioned earlier that the string was too long to post in my question. There is something in the WebConfig you can set for maxlength of an image string:

<webServices>
    <jsonSerialization maxJsonLength="86753010">
    </jsonSerialization>
</webServices>

So, the json serialization was failing because I had this code commented-out. I commented it back in and made the number bigger, and that fixed my issue. So then I was able to pass the string properly and everything worked!

PBJ
  • 354
  • 2
  • 15