Created
July 31, 2018 06:09
-
-
Save Necroforger/51e805465849a3e344dea5a809da2939 to your computer and use it in GitHub Desktop.
Xor the RGB pixels of two images together, because why not
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
package main | |
import ( | |
"flag" | |
"image" | |
"image/draw" | |
_ "image/gif" | |
_ "image/jpeg" | |
"image/png" | |
"log" | |
"os" | |
"strings" | |
_ "golang.org/x/image/bmp" | |
) | |
func readImage(p string) (image.Image, error) { | |
f, err := os.Open(p) | |
if err != nil { | |
return nil, err | |
} | |
defer f.Close() | |
img, _, err := image.Decode(f) | |
return img, err | |
} | |
func writeImage(p string, img image.Image) error { | |
f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0600) | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
return png.Encode(f, img) | |
} | |
func cloneRGBA(img image.Image) *image.RGBA { | |
dst := image.NewRGBA(img.Bounds()) | |
draw.Draw(dst, dst.Bounds(), img, image.ZP, draw.Src) | |
return dst | |
} | |
// XorImage xors the RGB values of an image together | |
func XorImage(imgA *image.RGBA, imgB *image.RGBA, dst *image.RGBA) { | |
w, h := imgB.Bounds().Dx(), imgB.Bounds().Dy() | |
wa, ha := imgA.Bounds().Dx(), imgA.Bounds().Dy() | |
for y := 0; y < h; y++ { | |
for x := 0; x < w; x++ { | |
idx := (y*imgB.Stride + x*4) | |
idxA := ((y%ha)*imgA.Stride + (x%wa)*4) // Wrap around | |
dst.Pix[idx+0] = imgB.Pix[idx+0] ^ imgA.Pix[idxA+0] | |
dst.Pix[idx+1] = imgB.Pix[idx+1] ^ imgA.Pix[idxA+1] | |
dst.Pix[idx+2] = imgB.Pix[idx+2] ^ imgA.Pix[idxA+2] | |
// Set alpha pixel | |
dst.Pix[idx+3] = 255 | |
} | |
} | |
} | |
func main() { | |
flag.Parse() | |
if len(flag.Args()) < 3 { | |
log.Fatal("Usage: imagecipher [image-key] [image] [output-file]") | |
} | |
imageA, err := readImage(flag.Arg(0)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
imageB, err := readImage(flag.Arg(1)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
dst := image.NewRGBA(imageB.Bounds()) | |
XorImage(cloneRGBA(imageA), cloneRGBA(imageB), dst) | |
var destination = flag.Arg(2) | |
if !strings.HasSuffix(strings.ToLower(flag.Arg(2)), ".png") { | |
destination += ".png" | |
} | |
writeImage(destination, dst) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment