// Package attachtest makes attachment fixtures for tests: a PNG, and a // JPEG as a phone writes it, with an EXIF orientation and GPS position. package attachtest import ( "bytes" "encoding/binary" "hash/crc32" "image" "image/color" "image/jpeg" "image/png" ) // gpsMark is the latitude's numerators, bytes no small fixture holds by // chance. var gpsMark = []uint32{424242, 171717, 999999} // PNG is a w by h PNG. func PNG(w, h int) []byte { img := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { img.Set(x, y, color.RGBA{uint8(x), uint8(y), 90, 255}) } } var b bytes.Buffer _ = png.Encode(&b, img) return b.Bytes() } // Photo is a w by h JPEG with EXIF orientation and a GPS latitude. func Photo(w, h int, orientation uint16) []byte { img := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { img.Set(x, y, color.RGBA{200, uint8(x), uint8(y), 255}) } } var b bytes.Buffer _ = jpeg.Encode(&b, img, &jpeg.Options{Quality: 90}) raw := b.Bytes() exif := append([]byte("Exif\x00\x00"), tiff(orientation)...) seg := binary.BigEndian.AppendUint16([]byte{0xff, 0xe1}, uint16(len(exif)+2)) out := append([]byte{}, raw[:2]...) out = append(out, append(seg, exif...)...) return append(out, raw[2:]...) } // HasGPS reports whether b still holds the fixture's latitude. func HasGPS(b []byte) bool { for _, n := range gpsMark { if bytes.Contains(b, binary.LittleEndian.AppendUint32(nil, n)) { return true } } return false } func tiff(orientation uint16) []byte { le := binary.LittleEndian b := le.AppendUint32([]byte("II*\x00"), 8) b = le.AppendUint16(b, 2) b = le.AppendUint16(le.AppendUint16(b, 0x0112), 3) b = le.AppendUint16(le.AppendUint16(le.AppendUint32(b, 1), orientation), 0) gps := uint32(8 + 2 + 2*12 + 4) b = le.AppendUint16(le.AppendUint16(b, 0x8825), 4) b = le.AppendUint32(le.AppendUint32(le.AppendUint32(b, 1), gps), 0) data := gps + 2 + 12 + 4 b = le.AppendUint16(b, 1) b = le.AppendUint16(le.AppendUint16(b, 2), 5) b = le.AppendUint32(le.AppendUint32(le.AppendUint32(b, 3), data), 0) for _, n := range gpsMark { b = le.AppendUint32(le.AppendUint32(b, n), 1) } return b } // PNGHeader is a PNG that claims w by h: a signature, IHDR and IEND only. func PNGHeader(w, h uint32) []byte { ihdr := binary.BigEndian.AppendUint32(nil, w) ihdr = append(binary.BigEndian.AppendUint32(ihdr, h), 8, 6, 0, 0, 0) out := []byte("\x89PNG\r\n\x1a\n") out = append(out, pngChunk("IHDR", ihdr)...) return append(out, pngChunk("IEND", nil)...) } func pngChunk(kind string, data []byte) []byte { out := binary.BigEndian.AppendUint32(nil, uint32(len(data))) out = append(append(out, kind...), data...) return binary.BigEndian.AppendUint32(out, crc32.ChecksumIEEE(append([]byte(kind), data...))) }