helpers_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package imaging
  2. import (
  3. "bytes"
  4. "image"
  5. "testing"
  6. )
  7. func compareNRGBA(img1, img2 *image.NRGBA, delta int) bool {
  8. if !img1.Rect.Eq(img2.Rect) {
  9. return false
  10. }
  11. if len(img1.Pix) != len(img2.Pix) {
  12. return false
  13. }
  14. for i := 0; i < len(img1.Pix); i++ {
  15. if absint(int(img1.Pix[i])-int(img2.Pix[i])) > delta {
  16. return false
  17. }
  18. }
  19. return true
  20. }
  21. func TestEncodeDecode(t *testing.T) {
  22. imgWithAlpha := image.NewNRGBA(image.Rect(0, 0, 3, 3))
  23. imgWithAlpha.Pix = []uint8{
  24. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25. 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
  26. 244, 245, 246, 247, 248, 249, 250, 252, 252, 253, 254, 255,
  27. }
  28. imgWithoutAlpha := image.NewNRGBA(image.Rect(0, 0, 3, 3))
  29. imgWithoutAlpha.Pix = []uint8{
  30. 0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255,
  31. 127, 128, 129, 255, 131, 132, 133, 255, 135, 136, 137, 255,
  32. 244, 245, 246, 255, 248, 249, 250, 255, 252, 253, 254, 255,
  33. }
  34. for _, format := range []Format{JPEG, PNG, GIF, BMP, TIFF} {
  35. img := imgWithoutAlpha
  36. if format == PNG {
  37. img = imgWithAlpha
  38. }
  39. buf := &bytes.Buffer{}
  40. err := Encode(buf, img, format)
  41. if err != nil {
  42. t.Errorf("fail encoding format %s", format)
  43. continue
  44. }
  45. img2, err := Decode(buf)
  46. if err != nil {
  47. t.Errorf("fail decoding format %s", format)
  48. continue
  49. }
  50. img2cloned := Clone(img2)
  51. delta := 0
  52. if format == JPEG {
  53. delta = 3
  54. } else if format == GIF {
  55. delta = 16
  56. }
  57. if !compareNRGBA(img, img2cloned, delta) {
  58. t.Errorf("fail comparing images format=%s %#v %#v", format, img, img2cloned)
  59. continue
  60. }
  61. }
  62. buf := &bytes.Buffer{}
  63. err := Encode(buf, imgWithAlpha, Format(100))
  64. if err != ErrUnsupportedFormat {
  65. t.Errorf("expected ErrUnsupportedFormat")
  66. }
  67. }