Skip to content

Instantly share code, notes, and snippets.

@jochemstoel
Forked from mikey0000/convertToJPG
Created November 21, 2022 13:43
Show Gist options
  • Save jochemstoel/cfe3e568056ff8fd71c6304f58ef903e to your computer and use it in GitHub Desktop.
Save jochemstoel/cfe3e568056ff8fd71c6304f58ef903e to your computer and use it in GitHub Desktop.
convert png to jpeg using javascript and write back to original file
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
var convertToJPG = function(file) {
var image = new Image();
image.src = file.nativeURL;
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
image.onload = function(){
//save to temp location??
file.createWriter(function(fileWriter) {
file.onWriteEnd = function(e) {
console.log('Write completed.');
};
file.onError = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var ui8a = convertDataURIToBinary(image);
var blob = new Blob(ui8a.buffer, {type: "image/jpeg"});
fileWriter.write(blob);
}, errorHandler);
};
image.src = canvas.toDataURL("image/jpg");
return image;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment