~shabbyrobe/imgx

19bee0275d7ae33f0f6147d1250672684f6f3f65 — Blake Williams 5 months ago 8f33909
testimg: Image compare functions
1 files changed, 88 insertions(+), 0 deletions(-)

A testimg/cmp.go
A testimg/cmp.go => testimg/cmp.go +88 -0
@@ 0,0 1,88 @@
package testimg

import (
	"image"
)

type CompareResult int

const (
	CompareSame CompareResult = iota
	CompareSizeMismatch
	ComparePixelMismatch
)

func CompareVisibleViaRGBA(img1, img2 image.Image) CompareResult {
	r1, r2 := img1.Bounds(), img2.Bounds()
	if r1.Size() != r2.Size() {
		return CompareSizeMismatch
	}

	for y := r1.Min.Y; y < r1.Max.Y; y++ {
		for x := r1.Min.X; x < r1.Max.X; x++ {
			r1, g1, b1, a1 := img1.At(x, y).RGBA()
			r2, g2, b2, a2 := img2.At(x, y).RGBA()

			if r1 != r2 || g1 != g2 || b1 != b2 || a1 != a2 {
				return ComparePixelMismatch
			}
		}
	}

	return CompareSame
}

func EqualVisibleViaRGBA(img1, img2 image.Image) bool {
	r1, r2 := img1.Bounds(), img2.Bounds()
	if r1.Size() != r2.Size() {
		return false
	}

	for y := r1.Min.Y; y < r1.Max.Y; y++ {
		for x := r1.Min.X; x < r1.Max.X; x++ {
			r1, g1, b1, a1 := img1.At(x, y).RGBA()
			r2, g2, b2, a2 := img2.At(x, y).RGBA()

			if r1 != r2 || g1 != g2 || b1 != b2 || a1 != a2 {
				return false
			}
		}
	}

	return true
}

func CompareVisibleViaRGBALoose(img1, img2 image.Image, leeway int) CompareResult {
	r1, r2 := img1.Bounds(), img2.Bounds()
	if r1.Size() != r2.Size() {
		return CompareSizeMismatch
	}

	for y := r1.Min.Y; y < r1.Max.Y; y++ {
		for x := r1.Min.X; x < r1.Max.X; x++ {
			r1, g1, b1, a1 := img1.At(x, y).RGBA()
			r2, g2, b2, a2 := img2.At(x, y).RGBA()

			if leeway <= 0 {
				if r1 != r2 || g1 != g2 || b1 != b2 || a1 != a2 {
					return ComparePixelMismatch
				}
			} else {
				if rdiff := int(r1) - int(r2); rdiff >= leeway || rdiff <= -leeway {
					return ComparePixelMismatch
				}
				if gdiff := int(g1) - int(g2); gdiff >= leeway || gdiff <= -leeway {
					return ComparePixelMismatch
				}
				if bdiff := int(b1) - int(b2); bdiff >= leeway || bdiff <= -leeway {
					return ComparePixelMismatch
				}
				if adiff := int(a1) - int(a2); adiff >= leeway || adiff <= -leeway {
					return ComparePixelMismatch
				}
			}
		}
	}

	return CompareSame
}