| 1 | package imagefile |
| 2 | |
| 3 | import "encoding/binary" |
| 4 | |
| 5 | // EXIF's Orientation tag, read from an APP1 that is then dropped, and |
| 6 | // written back alone (§5). An EXIF block Mapa cannot read gives 1: it |
| 7 | // is dropped whole either way, so nothing in it is passed through. |
| 8 | |
| 9 | const tagOrientation = 0x0112 |
| 10 | |
| 11 | // orientation is the Orientation tag of a TIFF structure, or 1. |
| 12 | func orientation(tiff []byte) int { |
| 13 | if len(tiff) < 8 { |
| 14 | return 1 |
| 15 | } |
| 16 | var order binary.ByteOrder |
| 17 | switch string(tiff[:2]) { |
| 18 | case "II": |
| 19 | order = binary.LittleEndian |
| 20 | case "MM": |
| 21 | order = binary.BigEndian |
| 22 | default: |
| 23 | return 1 |
| 24 | } |
| 25 | if order.Uint16(tiff[2:]) != 42 { |
| 26 | return 1 |
| 27 | } |
| 28 | return ifdOrientation(tiff, order, int(order.Uint32(tiff[4:]))) |
| 29 | } |
| 30 | |
| 31 | func ifdOrientation(tiff []byte, order binary.ByteOrder, ifd int) int { |
| 32 | if ifd < 8 || ifd+2 > len(tiff) { |
| 33 | return 1 |
| 34 | } |
| 35 | count := int(order.Uint16(tiff[ifd:])) |
| 36 | for entry := range count { |
| 37 | at := ifd + 2 + 12*entry |
| 38 | if at+12 > len(tiff) { |
| 39 | return 1 |
| 40 | } |
| 41 | if order.Uint16(tiff[at:]) != tagOrientation { |
| 42 | continue |
| 43 | } |
| 44 | value := int(order.Uint16(tiff[at+8:])) |
| 45 | if order.Uint16(tiff[at+2:]) != 3 || value < 1 || value > 8 { |
| 46 | return 1 |
| 47 | } |
| 48 | return value |
| 49 | } |
| 50 | return 1 |
| 51 | } |
| 52 | |
| 53 | // orientationExif is a minimal APP1 payload: one IFD, one tag. |
| 54 | func orientationExif(value int) []byte { |
| 55 | out := []byte("Exif\x00\x00MM\x00\x2a\x00\x00\x00\x08" + |
| 56 | "\x00\x01\x01\x12\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00" + |
| 57 | "\x00\x00\x00\x00") |
| 58 | binary.BigEndian.PutUint16(out[6+8+2+8:], uint16(value)) |
| 59 | return out |
| 60 | } |
| 61 | |