Skip to content

Updated b64toByteArrays function to improve performance #97

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
44 changes: 21 additions & 23 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,38 +91,36 @@ class Resizer {
return canvas.toDataURL(`image/${compressFormat}`, qualityDecimal);
}

static b64toByteArrays(b64Data, contentType) {
contentType = contentType || "image/jpeg";
var sliceSize = 512;

var byteCharacters = atob(
b64Data.toString().replace(/^data:image\/(png|jpeg|jpg|webp);base64,/, "")
);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);

var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

var byteArray = new Uint8Array(byteNumbers);

byteArrays.push(byteArray);
static b64toByteArrays(b64Data) {
const sliceSize = 1024; // 1024 gives best performance
const base64Marker = /^data:image\/(png|jpeg|jpg|webp);base64,/;

const byteCharacters = atob(b64Data.replace(base64Marker, ""));
const byteLength = byteCharacters.length;
const byteArrays = [];

for (let offset = 0; offset < byteLength; offset += sliceSize) {
const sliceLength = Math.min(sliceSize, byteLength - offset);
const byteArray = new Uint8Array(sliceLength);

for (let i = 0; i < sliceLength; i++) {
byteArray[i] = byteCharacters.charCodeAt(offset + i);
}

byteArrays.push(byteArray);
}

return byteArrays;
}
}

static b64toBlob(b64Data, contentType) {
const byteArrays = this.b64toByteArrays(b64Data, contentType);
const byteArrays = this.b64toByteArrays(b64Data);
var blob = new Blob(byteArrays, { type: contentType, lastModified: new Date() });
return blob;
}

static b64toFile(b64Data, fileName, contentType) {
const byteArrays = this.b64toByteArrays(b64Data, contentType);
const byteArrays = this.b64toByteArrays(b64Data);
const file = new File(byteArrays, fileName, { type: contentType, lastModified: new Date() });
return file;
}
Expand Down