CORS Issue with Images / toDataURL

I am trying to use the following code to convert an image from an S3 bucket into a base64 string. However, I have two issues I am currently facing:

  1. If I use img.crossOrigin = “Use-Credentials” or img.crossOrigin = “Anonymous”, I get the following error back: {“isTrusted”:true}, which appears to be a CORS issue.

  2. If I do not include this line, I am able to load the image, but then I have a “tainted” canvas, which CORS will not allow me to call toDataURL on.

Is there any simple way to fix this? Will this require configuration on the AWS side?

getImageBase64String(url: string, callback) {
		// Convert image to base64 string
		var canvas: any = document.createElement('CANVAS'),
		ctx: any = canvas.getContext('2d'),
		img: any = new Image();
		img.crossOrigin = "Use-Credentials";

		img.onload = () => {

			var dataURL: any = null;
	 		canvas.height = img.height;
			canvas.width = img.width;
			ctx.drawImage(img, 0, 0);

			// set image quality
        	dataURL = canvas.toDataURL('image/jpeg', 1.0);
			canvas = null;
			callback(dataURL, null);
		};

		img.onerror = (err) => {
			console.log('getImageBase64String - error', JSON.stringify(err));
			callback(null, err);
		};
		img.src = JSON.parse(url);
 	}
1 Like

hi @bschmuck did you ever figure this out? Am having the same issue

Is it the url a blob:url?. Try to use another src url, maybe you can transform the image url to base64 before referenced as src, like

  renderPictureAsBase64(image) {
    return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(image)))
  }

then you can do

img.src = this.renderPictureAsBase64url);