Golang image package is very handy to some extent but lack the support to set DPI of an image. I checked the file header of generated file, FF D8 FF DB
which looks like jpeg raw. AFAIK, raw doesn't come with DPI like what jfif has. So here's my question, how to set DPI of the generated image? Or how to convert a raw to jfif, from which I know I can edit a specific bit of the file to set DPI? Previously I embedded an AdvancedBatchConverter executable in my app and used exec.Command(fmt.Sprintf("%s/AdvancedBatchConverter/abc.exe", cwd), outputFile, "/jfif", fmt.Sprintf("/convert=%s", jfifFileName))
to do the trick, but really, disgusted by it every time I looked at the code.
how to set DPI using Golang?
1.9k Views Asked by Simon At
2
There are 2 best solutions below
0

github.com/dsoprea/go-exif/v2 can reader and write exif data. with other package github.com/dsoprea/go-jpeg-image-structure here is code example . for write DPI(XResolution, YResolution) to Image.
import(
exif2 "github.com/dsoprea/go-exif/v2"
exifcommon "github.com/dsoprea/go-exif/v2/common"
jpegstructure "github.com/dsoprea/go-jpeg-image-structure"
)
func SetExifData(filepath string) error {
jmp := jpegstructure.NewJpegMediaParser()
intfc, err := jmp.ParseFile(filepath)
log.PanicIf(err)
sl := intfc.(*jpegstructure.SegmentList)
// Make sure we don't start out with EXIF data.
wasDropped, err := sl.DropExif()
log.PanicIf(err)
if wasDropped != true {
fmt.Printf("Expected the EXIF segment to be dropped, but it wasn't.")
}
im := exif2.NewIfdMapping()
err = exif2.LoadStandardIfds(im)
log.PanicIf(err)
ti := exif2.NewTagIndex()
rootIb := exif2.NewIfdBuilder(im, ti, exifcommon.IfdPathStandard, exifcommon.EncodeDefaultByteOrder)
err = rootIb.AddStandardWithName("XResolution", []exifcommon.Rational{{Numerator: uint32(96), Denominator: uint32(1)}})
log.PanicIf(err)
err = rootIb.AddStandardWithName("YResolution", []exifcommon.Rational{{Numerator: uint32(96), Denominator: uint32(1)}})
log.PanicIf(err)
err = sl.SetExif(rootIb)
log.PanicIf(err)
b := new(bytes.Buffer)
err = sl.Write(b)
log.PanicIf(err)
if err := ioutil.WriteFile(filepath, b.Bytes(), 0644); err != nil {
fmt.Printf("write file err: %v", err)
}
return nil
}
I believe you're looking for the exif values
XResolution
andYResolution
My understanding is the native jpeg encoder doesn't have any options for exif data.
https://github.com/dsoprea/go-exif will let you modify the exif data.
Additionally I believe if you first write the jpeg to a bytes.Buffer or similar and then append the exif you can do the entire thing in memory without flushing to disk first.
I hope that helps.