java.awt.Image の比較
テストの一部で Image の比較をしたいのだがやり方が分からずに悩む。
public static boolean compareImage(Image expected, Image actual) { if (expected == actual) { return true; } ImageIcon ai = new ImageIcon(actual); ImageIcon ei = new ImageIcon(expected); assertEquals(ei.getIconHeight(), ai.getIconHeight()); assertEquals(ei.getIconWidth(), ai.getIconWidth()); // 実際の画像が一致するかどうかを比較したいのだが。。。 return true; }
これでは高さと幅が一致すると同じになってしまう。
誰か、画像を比較する方法を教えてくださいませ。
(ごそごそ)
自己解決できた。java.awt.image.PixelGrabber クラスを使うことでピクセル単位の比較が可能だと言うことが分かった。
以下のコードで比較できる。
private static boolean compareImage(Image expected, Image actual){ if (expected == actual) { return true; } ImageIcon ei = new ImageIcon(expected); ImageIcon ai = new ImageIcon(actual); int eh = ei.getIconHeight(); int ew = ei.getIconWidth(); int ah = ai.getIconHeight(); int aw = ai.getIconWidth(); assertEquals(eh, ah); assertEquals(ew, aw); int ep = new int[ew * eh]; int ap = new int[aw * ah]; PixelGrabber epg = new PixelGrabber(expected, 0, 0, ew, eh, ep, 0, ew); PixelGrabber apg = new PixelGrabber(actual, 0, 0, aw, ah, ap, 0, aw); try{ epg.grabPixels(); apg.grabPixels(); }catch(Exception e){ e.printStackTrace(); } assertEquals(ep.length, ap.length); for(int i = 0; i < ep.length; i++){ assertEquals(ep[i], ap[i]); } return true; }
assert でチェックしているから boolean で結果を返すのは意味ないかも。(^^;
ってか、メソッドのシグネチャを
public static void assertEquals(Image expected, Image actual)
にするのが適当か。