Skip to content

Instantly share code, notes, and snippets.

@vmihailenco
Created February 15, 2012 15:52
Show Gist options
  • Select an option

  • Save vmihailenco/1836834 to your computer and use it in GitHub Desktop.

Select an option

Save vmihailenco/1836834 to your computer and use it in GitHub Desktop.
Error level analys for JPEG in Golang
package main
import (
"bytes"
"flag"
"image"
"image/jpeg"
_ "image/png"
"os"
)
const amplifier = 10
func diff(x, y uint8) uint8 {
if x > y {
return x - y
}
return y - x
}
func panicIf(err error) {
if err != nil {
panic(err)
}
}
func DrawELA(input, output string) {
inReader, err := os.Open(input)
panicIf(err)
inStat, err := inReader.Stat()
panicIf(err)
outWriter, err := os.Create(output)
panicIf(err)
src, _, err := image.Decode(inReader)
panicIf(err)
bounds := src.Bounds()
srcRGBA, ok := src.(*image.RGBA)
if !ok {
panic("can not convert src to RGBA")
}
buf := bytes.NewBuffer(make([]byte, 0, inStat.Size()*2))
err = jpeg.Encode(buf, src, &jpeg.Options{95})
panicIf(err)
sample, err := jpeg.Decode(buf)
panicIf(err)
sampleRGBA, ok := sample.(*image.RGBA)
if !ok {
panic("can not convert sample to RGBA")
}
for x := bounds.Min.X; x < bounds.Max.X; x++ {
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
i := srcRGBA.PixOffset(x, y)
srcRGBA.Pix[i] = diff(srcRGBA.Pix[i], sampleRGBA.Pix[i]) * amplifier
srcRGBA.Pix[i+1] = diff(srcRGBA.Pix[i+1], sampleRGBA.Pix[i+1]) * amplifier
srcRGBA.Pix[i+2] = diff(srcRGBA.Pix[i+2], sampleRGBA.Pix[i+2]) * amplifier
}
}
err = jpeg.Encode(outWriter, srcRGBA, &jpeg.Options{95})
panicIf(err)
}
func main() {
var input *string = flag.String("input", "", "input stream")
var output *string = flag.String("output", "", "output stream")
flag.Parse()
DrawELA(*input, *output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment