Search code examples
javascriptnode.jsjpegexifpiexif

Modify jpg image Exif with Byte (UCS2) Type in javascript


I am trying to modify Exif data of a jpg using piexifjs module. it works well but for the most important and basic Tags like Title, Comment, Author... It doesn't work at all.

var piexif = require("piexifjs");
var fs = require("fs");

var filename1 = "image.jpg";
var filename2 = "out.jpg";

var jpeg = fs.readFileSync(filename1);
var data = jpeg.toString("binary");

var zeroth = {};

zeroth[piexif.ImageIFD.XPTitle] = "Birds";

var exifObj = {"0th":zeroth};
var exifbytes = piexif.dump(exifObj);

var newData = piexif.insert(exifbytes, data);
var newJpeg = Buffer.from(newData, "binary");
fs.writeFileSync(filename2, newJpeg);

when I run it it throws Error: 'pack' error. Got invalid type argument.
I search the internet and in Metadata reference tables it says they are of type Byte https://www.exiv2.org/tags.html. so when I make it zeroth[piexif.ImageIFD.XPTitle] = 4; or some number it runs, but without changing the title.
so how can I make it work? what does it mean when their type is Byte? how can


Solution

  • I found the answer here. You need:

    zeroth[piexif.ImageIFD.XPTitle]   = [...Buffer.from('Birds', 'ucs2')];
    zeroth[piexif.ImageIFD.XPComment] = [...Buffer.from('Tweet tweet', 'ucs2')];
    zeroth[piexif.ImageIFD.XPAuthor]  = [...Buffer.from('Ornithologist', 'ucs2')];
    

    Result:

    enter image description here