agi.image_preview_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package agi
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "hash/crc32"
  6. "image"
  7. "image/color"
  8. "image/jpeg"
  9. "image/png"
  10. "os"
  11. "path/filepath"
  12. "testing"
  13. )
  14. // jpegOfSize encodes a w x h picture whose left half is red and right half blue
  15. func jpegOfSize(t *testing.T, w, h int) []byte {
  16. t.Helper()
  17. img := image.NewRGBA(image.Rect(0, 0, w, h))
  18. for y := 0; y < h; y++ {
  19. for x := 0; x < w; x++ {
  20. c := color.RGBA{R: 220, A: 255}
  21. if x >= w/2 {
  22. c = color.RGBA{B: 220, A: 255}
  23. }
  24. img.Set(x, y, c)
  25. }
  26. }
  27. var buf bytes.Buffer
  28. if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 95}); err != nil {
  29. t.Fatalf("jpeg encode: %v", err)
  30. }
  31. return buf.Bytes()
  32. }
  33. // withExifOrientation puts an APP1 Exif segment holding only the Orientation
  34. // tag right after the SOI marker of a JPEG
  35. func withExifOrientation(jpg []byte, orientation uint16) []byte {
  36. tiff := []byte{'I', 'I', 42, 0, 8, 0, 0, 0} //little endian, IFD0 at 8
  37. ifd := make([]byte, 2+12+4)
  38. binary.LittleEndian.PutUint16(ifd[0:], 1) //one entry
  39. binary.LittleEndian.PutUint16(ifd[2:], 0x0112) //Orientation
  40. binary.LittleEndian.PutUint16(ifd[4:], 3) //SHORT
  41. binary.LittleEndian.PutUint32(ifd[6:], 1) //count
  42. binary.LittleEndian.PutUint16(ifd[10:], orientation)
  43. payload := append([]byte("Exif\x00\x00"), append(tiff, ifd...)...)
  44. seg := []byte{0xFF, 0xE1, 0, 0}
  45. binary.BigEndian.PutUint16(seg[2:], uint16(len(payload)+2))
  46. seg = append(seg, payload...)
  47. out := append([]byte{}, jpg[:2]...)
  48. out = append(out, seg...)
  49. return append(out, jpg[2:]...)
  50. }
  51. // pngClaimingSize returns a PNG whose header says w x h (the pixel data is
  52. // that of a 1 x 1 picture, so only DecodeConfig can read it)
  53. func pngClaimingSize(t *testing.T, w, h uint32) []byte {
  54. t.Helper()
  55. var buf bytes.Buffer
  56. if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 1, 1))); err != nil {
  57. t.Fatalf("png encode: %v", err)
  58. }
  59. data := buf.Bytes()
  60. //IHDR data starts after the 8 byte signature, 4 byte length and "IHDR"
  61. binary.BigEndian.PutUint32(data[16:], w)
  62. binary.BigEndian.PutUint32(data[20:], h)
  63. binary.BigEndian.PutUint32(data[29:], crc32.ChecksumIEEE(data[12:29]))
  64. return data
  65. }
  66. func TestFitPreview(t *testing.T) {
  67. tests := []struct {
  68. name string
  69. w, h int
  70. maxW, maxH int
  71. wantW, wantH int
  72. }{
  73. {"landscape fits the width", 1200, 800, 600, 1200, 600, 400},
  74. {"portrait fits the width", 800, 1200, 400, 1200, 400, 600},
  75. {"tall picture fits the height", 200, 2000, 600, 1000, 100, 1000},
  76. {"small picture is kept", 300, 200, 600, 1200, 300, 200},
  77. {"no height limit", 1200, 2400, 600, 0, 600, 1200},
  78. {"no limits", 640, 480, 0, 0, 640, 480},
  79. }
  80. for _, tc := range tests {
  81. t.Run(tc.name, func(t *testing.T) {
  82. got := fitPreview(image.NewRGBA(image.Rect(0, 0, tc.w, tc.h)), tc.maxW, tc.maxH)
  83. if b := got.Bounds(); b.Dx() != tc.wantW || b.Dy() != tc.wantH {
  84. t.Errorf("got %dx%d, want %dx%d", b.Dx(), b.Dy(), tc.wantW, tc.wantH)
  85. }
  86. })
  87. }
  88. }
  89. func TestDecodePreviewSourceOrientation(t *testing.T) {
  90. src := jpegOfSize(t, 40, 20)
  91. tests := []struct {
  92. name string
  93. orientation uint16
  94. wantW, wantH int
  95. }{
  96. {"no exif", 0, 40, 20},
  97. {"upright", 1, 40, 20},
  98. {"rotated 180", 3, 40, 20},
  99. {"rotated 90 clockwise", 6, 20, 40},
  100. {"rotated 90 counter clockwise", 8, 20, 40},
  101. }
  102. for _, tc := range tests {
  103. t.Run(tc.name, func(t *testing.T) {
  104. data := src
  105. if tc.orientation > 0 {
  106. data = withExifOrientation(src, tc.orientation)
  107. }
  108. img, err := decodePreviewSource(data, ".jpg")
  109. if err != nil {
  110. t.Fatalf("decode: %v", err)
  111. }
  112. if b := img.Bounds(); b.Dx() != tc.wantW || b.Dy() != tc.wantH {
  113. t.Errorf("got %dx%d, want %dx%d", b.Dx(), b.Dy(), tc.wantW, tc.wantH)
  114. }
  115. })
  116. }
  117. t.Run("rotated 90 clockwise puts the left edge on top", func(t *testing.T) {
  118. img, err := decodePreviewSource(withExifOrientation(src, 6), ".jpg")
  119. if err != nil {
  120. t.Fatalf("decode: %v", err)
  121. }
  122. r, _, b, _ := img.At(10, 2).RGBA()
  123. if r < b {
  124. t.Errorf("top of the upright picture should be red (the old left half), got r=%d b=%d", r>>8, b>>8)
  125. }
  126. })
  127. }
  128. func TestDecodePreviewSourceRefuses(t *testing.T) {
  129. tests := []struct {
  130. name string
  131. data []byte
  132. }{
  133. {"not a picture", []byte("hello world, not an image")},
  134. {"empty", []byte{}},
  135. {"too many pixels", pngClaimingSize(t, 20000, 20000)},
  136. }
  137. for _, tc := range tests {
  138. t.Run(tc.name, func(t *testing.T) {
  139. if _, err := decodePreviewSource(tc.data, ".png"); err == nil {
  140. t.Errorf("expected an error")
  141. }
  142. })
  143. }
  144. }
  145. func TestEncodePreview(t *testing.T) {
  146. clear := image.NewNRGBA(image.Rect(0, 0, 8, 8)) //fully transparent
  147. t.Run("jpeg turns transparency white", func(t *testing.T) {
  148. data, err := encodePreview(clear, "jpeg")
  149. if err != nil {
  150. t.Fatalf("encode: %v", err)
  151. }
  152. img, format, err := image.Decode(bytes.NewReader(data))
  153. if err != nil || format != "jpeg" {
  154. t.Fatalf("decode: %v (%s)", err, format)
  155. }
  156. r, g, b, _ := img.At(4, 4).RGBA()
  157. if r>>8 < 245 || g>>8 < 245 || b>>8 < 245 {
  158. t.Errorf("expected white, got %d,%d,%d", r>>8, g>>8, b>>8)
  159. }
  160. })
  161. t.Run("png keeps transparency", func(t *testing.T) {
  162. data, err := encodePreview(clear, "png")
  163. if err != nil {
  164. t.Fatalf("encode: %v", err)
  165. }
  166. img, format, err := image.Decode(bytes.NewReader(data))
  167. if err != nil || format != "png" {
  168. t.Fatalf("decode: %v (%s)", err, format)
  169. }
  170. if _, _, _, a := img.At(4, 4).RGBA(); a != 0 {
  171. t.Errorf("expected a transparent pixel, alpha %d", a)
  172. }
  173. })
  174. t.Run("unknown format", func(t *testing.T) {
  175. if _, err := encodePreview(clear, "gif"); err == nil {
  176. t.Errorf("expected an error")
  177. }
  178. })
  179. }
  180. func TestPreviewFormatOf(t *testing.T) {
  181. tests := []struct {
  182. dest string
  183. want string
  184. wantErr bool
  185. }{
  186. {"user:/a/b.jpg", "jpeg", false},
  187. {"user:/a/b.JPEG", "jpeg", false},
  188. {"user:/a/b.png", "png", false},
  189. {"user:/a/b.webp", "", true},
  190. {"user:/a/b", "", true},
  191. }
  192. for _, tc := range tests {
  193. t.Run(tc.dest, func(t *testing.T) {
  194. got, err := previewFormatOf(tc.dest)
  195. if (err != nil) != tc.wantErr || got != tc.want {
  196. t.Errorf("got %q, %v; want %q, error %v", got, err, tc.want, tc.wantErr)
  197. }
  198. })
  199. }
  200. }
  201. func TestRenderPreview(t *testing.T) {
  202. fsh, dir := newImageTestFSH(t)
  203. photo := filepath.Join(dir, "photo.jpg")
  204. if err := os.WriteFile(photo, withExifOrientation(jpegOfSize(t, 300, 200), 6), 0644); err != nil {
  205. t.Fatalf("write: %v", err)
  206. }
  207. raw := filepath.Join(dir, "photo.arw")
  208. if err := os.WriteFile(raw, jpegOfSize(t, 300, 200), 0644); err != nil {
  209. t.Fatalf("write: %v", err)
  210. }
  211. tests := []struct {
  212. name string
  213. path string
  214. wantW, wantH int
  215. wantErr bool
  216. }{
  217. {"jpeg is upright and fitted", photo, 100, 150, false},
  218. {"raw uses its embedded jpeg", raw, 100, 66, false},
  219. {"missing file", filepath.Join(dir, "none.jpg"), 0, 0, true},
  220. {"folder", dir, 0, 0, true},
  221. }
  222. for _, tc := range tests {
  223. t.Run(tc.name, func(t *testing.T) {
  224. data, w, h, err := renderPreview(fsh, tc.path, 100, 400, "jpeg")
  225. if tc.wantErr {
  226. if err == nil {
  227. t.Errorf("expected an error")
  228. }
  229. return
  230. }
  231. if err != nil {
  232. t.Fatalf("renderPreview: %v", err)
  233. }
  234. if w != tc.wantW || h != tc.wantH {
  235. t.Errorf("reported %dx%d, want %dx%d", w, h, tc.wantW, tc.wantH)
  236. }
  237. cfg, err := jpeg.DecodeConfig(bytes.NewReader(data))
  238. if err != nil {
  239. t.Fatalf("output is not a jpeg: %v", err)
  240. }
  241. if cfg.Width != w || cfg.Height != h {
  242. t.Errorf("encoded %dx%d, reported %dx%d", cfg.Width, cfg.Height, w, h)
  243. }
  244. })
  245. }
  246. }