Praxis Ashelin
Praxis Ashelin

Reputation: 5227

Strip EXIF data from image

How can I strip the EXIF data from an uploaded image through javascript? I am currently able to access the EXIF data using this exif-js plugin, like this:

EXIF.getData(oimg, function() {
    var orientation = EXIF.getTag(this, "Orientation");
});

However, I have not found any way to actually remove the Exif data, only to retrieve it.

More specifically, I am trying to do this to get rid of the orientation Exif data which rotates my image on certain browsers.

Upvotes: 22

Views: 30428

Answers (2)

Removing EXIF data from images.

Earlier EXIF data existed only in TIFF, JPEG(JPG) & HEIC, but now png also supports EXIF data.

First, let's understand what an image contains

Contents of an Image

The image buffer contains a header(2 bytes) + data.

The data part contains many segments, and every segment contains a header(2bytes) + data.

Length of segment presents in 1st byte of data (or after 2bytes from the segment start)

Exif buffer segment starts with 'marker' [header=marker]

The marker for jpg image is '0xFFE1'

Steps to remove EXIF data

  1. read the image as a buffer
  2. iterate through each segment
  3. if a segment has EXIF data, remove the segment

The below code is in TS works for jpg ( just remove types, it'll work in js )

Use: https://www.npmjs.com/package/exifr for more robust solution that works for all formats

const cleanBuffer = (arrayBuffer: ArrayBuffer) => {
  let dataView = new DataView(arrayBuffer);
  const exifMarker = 0xffe1;
  let offset = 2; // Skip the first two bytes (0xFFD8)

  while (offset < dataView.byteLength) {
    if (dataView.getUint16(offset) === exifMarker) {
      // Found an EXIF marker
      const segmentLength = dataView.getUint16(offset + 2, false) + 2;

      // Update the arrayBuffer and dataView
      arrayBuffer = removeSegment(arrayBuffer, offset, segmentLength);
      dataView = new DataView(arrayBuffer)
    } else {
      // Move to the next marker
      offset += 2 + dataView.getUint16(offset + 2, false);
    }
  }

  return arrayBuffer;
};

const removeSegment = (buffer: ArrayBuffer, offset: number, length: number) => {
  // Create a new buffer without the specified segment
  const modifiedBuffer = new Uint8Array(buffer.byteLength - length);
  modifiedBuffer.set(new Uint8Array(buffer.slice(0, offset)), 0);
  modifiedBuffer.set(new Uint8Array(buffer.slice(offset + length)), offset);

  return modifiedBuffer.buffer;
};
const removeExifData = (file: File): Promise<File> => {
  return new Promise((resolve) => {
    if (file && file.type.startsWith('image/')) {
      const fr = new FileReader();
      fr.onload = function (this: FileReader) {
        const cleanedBuffer = cleanBuffer(this.result as ArrayBuffer);
        const blob = new Blob([cleanedBuffer], { type: file.type });
        const newFile = new File([blob], file.name, { type: file.type });
        resolve(newFile);
      };
      fr.readAsArrayBuffer(file);
    } else resolve(file);
  });
};

Upvotes: 6

Musa
Musa

Reputation: 97717


Here is a little demo of it, select an image with orientation data to see how it looks with and with out it(modern browsers only).

http://jsfiddle.net/mowglisanu/frhwm2xe/3/

var input = document.querySelector('#erd');
input.addEventListener('change', load);
function load(){
    var fr = new FileReader();
    fr.onload = process;
    fr.readAsArrayBuffer(this.files[0]);
    document.querySelector('#orig').src = URL.createObjectURL(this.files[0]);
}
function process(){
    var dv = new DataView(this.result);
    var offset = 0, recess = 0;
    var pieces = [];
    var i = 0;
    if (dv.getUint16(offset) == 0xffd8){
        offset += 2;
        var app1 = dv.getUint16(offset);
        offset += 2;
        while (offset < dv.byteLength){
            //console.log(offset, '0x'+app1.toString(16), recess);
            if (app1 == 0xffe1){

                pieces[i] = {recess:recess,offset:offset-2};
                recess = offset + dv.getUint16(offset);
                i++;
            }
            else if (app1 == 0xffda){
                break;
            }
            offset += dv.getUint16(offset);
            var app1 = dv.getUint16(offset);
            offset += 2;
        }
        if (pieces.length > 0){
            var newPieces = [];
            pieces.forEach(function(v){
                newPieces.push(this.result.slice(v.recess, v.offset));
            }, this);
            newPieces.push(this.result.slice(recess));
            var br = new Blob(newPieces, {type: 'image/jpeg'});
            document.querySelector('#mod').src = URL.createObjectURL(br);
        }
    }       
}
img{
    max-width:200px;
}
<input id="erd" type="file"/><br>
<img id="orig" title="Original">
<img id="mod" title="Modified">

Upvotes: 30

Related Questions