Created
August 18, 2023 11:50
-
-
Save josephrocca/c789e27d807e52867674b6ff7269aba8 to your computer and use it in GitHub Desktop.
Remove EXIF data from JPEG using JavaScript - simple and extremely fast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Code mostly written by GPT-4. Works well for me, but not extensively tested (e.g. on old or weird jpeg files) | |
function removeExifFromJpeg(arrayBuffer) { | |
let view = new DataView(arrayBuffer); | |
// Check if it's a JPEG file | |
if (view.getUint16(0, false) !== 0xFFD8) { | |
throw new Error("Not a valid JPEG"); | |
} | |
let position = 2; // Start after the SOI marker | |
while (position < view.byteLength - 2) { | |
let marker = view.getUint16(position, false); | |
// If it's the Exif segment (APP1), remove it | |
if (marker === 0xFFE1) { | |
let length = view.getUint16(position + 2, false); | |
let buf1 = new Uint8Array(arrayBuffer.slice(0, position)); | |
let buf2 = new Uint8Array(arrayBuffer.slice(position + length + 2)); | |
let result = new Uint8Array(buf1.length + buf2.length); | |
result.set(buf1, 0); | |
result.set(buf2, buf1.length); | |
return result.buffer; | |
} | |
// Increment by segment length if it's an APPn segment | |
if (marker >= 0xFFE0 && marker <= 0xFFEF) { | |
position += view.getUint16(position + 2, false) + 2; | |
} else { | |
position += 2; | |
} | |
} | |
// If no Exif data found, return the original buffer | |
return arrayBuffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment