Skip to content

Improve data URI parsing. #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 7, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions js/canvas-to-blob.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,39 +36,50 @@
}()),
BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
window.MozBlobBuilder || window.MSBlobBuilder,
dataURIPattern = /^data:((.*?)(;charset=.*?)?)(;base64)?,/,
dataURLtoBlob = (hasBlobConstructor || BlobBuilder) && window.atob &&
window.ArrayBuffer && window.Uint8Array && function (dataURI) {
var byteString,
var matches,
mediaType,
isBase64,
dataString,
byteString,
arrayBuffer,
intArray,
i,
mimeString,
bb;
if (dataURI.split(',')[0].indexOf('base64') >= 0) {
// Parse the dataURI components as per RFC 2397
matches = dataURI.match(dataURIPattern);
if (!matches) throw new Error('invalid data URI');
// Default to text/plain;charset=US-ASCII
mediaType = matches[2] ?
matches[1] :
'text/plain' + (matches[3] || ';charset=US-ASCII');
isBase64 = !!matches[4];
dataString = dataURI.slice(matches[0].length);
if (isBase64) {
// Convert base64 to raw binary data held in a string:
byteString = atob(dataURI.split(',')[1]);
byteString = atob(dataString);
} else {
// Convert base64/URLEncoded data component to raw binary data:
byteString = decodeURIComponent(dataURI.split(',')[1]);
byteString = decodeURIComponent(dataString);
}
// Write the bytes of the string to an ArrayBuffer:
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
for (i = 0; i < byteString.length; i += 1) {
intArray[i] = byteString.charCodeAt(i);
}
// Separate out the mime component:
mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// Write the ArrayBuffer (or ArrayBufferView) to a blob:
if (hasBlobConstructor) {
return new Blob(
[hasArrayBufferViewSupport ? intArray : arrayBuffer],
{type: mimeString}
{type: mediaType}
);
}
bb = new BlobBuilder();
bb.append(arrayBuffer);
return bb.getBlob(mimeString);
return bb.getBlob(mediaType);
};
if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) {
if (CanvasPrototype.mozGetAsFile) {
Expand Down
2 changes: 1 addition & 1 deletion js/canvas-to-blob.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.