0

I want to process an image and make it secure by adding a watermark to it using transloadit. But the source of image I have is base64 encoded string rather than asking user to upload it to a form. Can I pass this base64 encoded string to form and process it to get watermark on it?

Any help is appreciated. Thanks!

meen
  • 2,287
  • 3
  • 23
  • 42

1 Answers1

2

It seems like you need to convert the base64 data uri to a Blob object, then manually set the blob as a parameter in FormData, as suggested in this SO question

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

Then set it using:

var dataURL = canvas.toDataURL('image/jpeg', 0.5);
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);

credit to @Stoive for the code

Community
  • 1
  • 1
danr
  • 91
  • 5