forked from mtusi2026/mtusi2026lab5
100 lines
2.0 KiB
Go
100 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/binary"
|
|
"image"
|
|
)
|
|
|
|
// EXIF IFD0 Orientation, включая отражения. Исходные байты не изменяются.
|
|
func orient(src image.Image, data []byte) image.Image {
|
|
orientation := 1
|
|
if len(data) > 2 && data[0] == 255 && data[1] == 216 {
|
|
for pos := 2; pos+4 <= len(data); {
|
|
if data[pos] != 255 {
|
|
break
|
|
}
|
|
marker := data[pos+1]
|
|
if marker == 0xda || marker == 0xd9 {
|
|
break
|
|
}
|
|
n := int(binary.BigEndian.Uint16(data[pos+2 : pos+4]))
|
|
if n < 2 || pos+2+n > len(data) {
|
|
break
|
|
}
|
|
segment := data[pos+4 : pos+2+n]
|
|
if marker == 0xe1 && bytes.HasPrefix(segment, []byte("Exif\x00\x00")) {
|
|
orientation = exifOrientation(segment[6:])
|
|
break
|
|
}
|
|
pos += 2 + n
|
|
}
|
|
}
|
|
if orientation < 2 || orientation > 8 {
|
|
return src
|
|
}
|
|
b := src.Bounds()
|
|
w, h := b.Dx(), b.Dy()
|
|
dw, dh := w, h
|
|
if orientation >= 5 {
|
|
dw, dh = h, w
|
|
}
|
|
dst := image.NewNRGBA(image.Rect(0, 0, dw, dh))
|
|
for y := 0; y < h; y++ {
|
|
for x := 0; x < w; x++ {
|
|
dx, dy := x, y
|
|
switch orientation {
|
|
case 2:
|
|
dx = w - 1 - x
|
|
case 3:
|
|
dx, dy = w-1-x, h-1-y
|
|
case 4:
|
|
dy = h - 1 - y
|
|
case 5:
|
|
dx, dy = y, x
|
|
case 6:
|
|
dx, dy = h-1-y, x
|
|
case 7:
|
|
dx, dy = h-1-y, w-1-x
|
|
case 8:
|
|
dx, dy = y, w-1-x
|
|
}
|
|
dst.Set(dx, dy, src.At(b.Min.X+x, b.Min.Y+y))
|
|
}
|
|
}
|
|
return dst
|
|
}
|
|
func exifOrientation(b []byte) int {
|
|
if len(b) < 8 {
|
|
return 1
|
|
}
|
|
var order binary.ByteOrder
|
|
switch string(b[:2]) {
|
|
case "II":
|
|
order = binary.LittleEndian
|
|
case "MM":
|
|
order = binary.BigEndian
|
|
default:
|
|
return 1
|
|
}
|
|
if order.Uint16(b[2:4]) != 42 {
|
|
return 1
|
|
}
|
|
offset := uint64(order.Uint32(b[4:8]))
|
|
if offset+2 > uint64(len(b)) {
|
|
return 1
|
|
}
|
|
count := int(order.Uint16(b[offset : offset+2]))
|
|
start := int(offset) + 2
|
|
for i := 0; i < count; i++ {
|
|
p := start + i*12
|
|
if p+12 > len(b) {
|
|
break
|
|
}
|
|
if order.Uint16(b[p:p+2]) == 0x112 && order.Uint16(b[p+2:p+4]) == 3 && order.Uint32(b[p+4:p+8]) == 1 {
|
|
return int(order.Uint16(b[p+8 : p+10]))
|
|
}
|
|
}
|
|
return 1
|
|
}
|