Skip to content

Commit 1c4f806

Browse files
committed
Improve data URI parsing.
1 parent b107a01 commit 1c4f806

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

js/canvas-to-blob.js

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,39 +36,50 @@
3636
}()),
3737
BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
3838
window.MozBlobBuilder || window.MSBlobBuilder,
39+
dataURIPattern = /^data:((.*?)(;charset=.*?)?)(;base64)?,/,
3940
dataURLtoBlob = (hasBlobConstructor || BlobBuilder) && window.atob &&
4041
window.ArrayBuffer && window.Uint8Array && function (dataURI) {
41-
var byteString,
42+
var matches,
43+
mediaType,
44+
isBase64,
45+
dataString,
46+
byteString,
4247
arrayBuffer,
4348
intArray,
4449
i,
45-
mimeString,
4650
bb;
47-
if (dataURI.split(',')[0].indexOf('base64') >= 0) {
51+
// Parse the dataURI components as per RFC 2397
52+
matches = dataURI.match(dataURIPattern);
53+
if (!matches) throw new Error('invalid data URI');
54+
// Default to text/plain;charset=US-ASCII
55+
mediaType = matches[2] ?
56+
matches[1] :
57+
'text/plain' + (matches[3] || ';charset=US-ASCII');
58+
isBase64 = !!matches[4];
59+
dataString = dataURI.slice(matches[0].length);
60+
if (isBase64) {
4861
// Convert base64 to raw binary data held in a string:
49-
byteString = atob(dataURI.split(',')[1]);
62+
byteString = atob(dataString);
5063
} else {
5164
// Convert base64/URLEncoded data component to raw binary data:
52-
byteString = decodeURIComponent(dataURI.split(',')[1]);
65+
byteString = decodeURIComponent(dataString);
5366
}
5467
// Write the bytes of the string to an ArrayBuffer:
5568
arrayBuffer = new ArrayBuffer(byteString.length);
5669
intArray = new Uint8Array(arrayBuffer);
5770
for (i = 0; i < byteString.length; i += 1) {
5871
intArray[i] = byteString.charCodeAt(i);
5972
}
60-
// Separate out the mime component:
61-
mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
6273
// Write the ArrayBuffer (or ArrayBufferView) to a blob:
6374
if (hasBlobConstructor) {
6475
return new Blob(
6576
[hasArrayBufferViewSupport ? intArray : arrayBuffer],
66-
{type: mimeString}
77+
{type: mediaType}
6778
);
6879
}
6980
bb = new BlobBuilder();
7081
bb.append(arrayBuffer);
71-
return bb.getBlob(mimeString);
82+
return bb.getBlob(mediaType);
7283
};
7384
if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) {
7485
if (CanvasPrototype.mozGetAsFile) {

js/canvas-to-blob.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)