copy EXIF from one JPEG blob to another and return a new JPEG blob.
This file contains 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
// Copyright (c) 2019 Jian Weihang <tonytonyjan@gmail.com> | |
export default async (src, dest) => { | |
const exif = await retrieveExif(src); | |
return new Blob([dest.slice(0, 2), exif, dest.slice(2)], { | |
type: "image/jpeg" | |
}); | |
}; | |
export const SOS = 0xffda, | |
APP1 = 0xffe1, | |
EXIF = 0x45786966, | |
retrieveExif = blob => | |
new Promise((resolve, reject) => { | |
const reader = new FileReader(); | |
reader.addEventListener("load", ({ target: { result: buffer } }) => { | |
const view = new DataView(buffer); | |
let offset = 0; | |
if (view.getUint16(offset) !== 0xffd8) | |
return reject("not a valid jpeg"); | |
offset += 2; | |
while (true) { | |
const marker = view.getUint16(offset); | |
if (marker === SOS) break; | |
const size = view.getUint16(offset + 2); | |
if (marker === APP1 && view.getUint32(offset + 4) === EXIF) | |
return resolve(blob.slice(offset, offset + 2 + size)); | |
offset += 2 + size; | |
} | |
return resolve(new Blob()); | |
}); | |
reader.readAsArrayBuffer(blob); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool work, is there also a way to copy IPTC, XMP, or simply any kind of metadata from one JPG to another? Best regards.