RoughImageComparator.java revision 13978:1993af50385d
1/*
2 * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23package org.netbeans.jemmy.image;
24
25import java.awt.image.BufferedImage;
26
27/**
28 * Compares two images roughly (i.e. not all of the pixel colors should match).
29 *
30 * @author Alexandre Iline (alexandre.iline@oracle.com)
31 */
32public class RoughImageComparator implements ImageComparator {
33
34    double roughness = .0;
35
36    /**
37     * Creates a comparator with {@code roughness} allowed roughness.
38     *
39     * @param roughness Allowed comparision roughness.
40     */
41    public RoughImageComparator(double roughness) {
42        this.roughness = roughness;
43    }
44
45    /**
46     * Compares two images with allowed roughness.
47     *
48     * @param image1 an image to compare.
49     * @param image2 an image to compare.
50     * @return true if images have the same sizes and number of unmatching
51     * pixels less or equal to      <code>image1.getWidth() * image1.getHeight() * roughness<code>
52     */
53    @Override
54    public boolean compare(BufferedImage image1, BufferedImage image2) {
55        if (image1.getWidth() != image2.getWidth()
56                || image1.getHeight() != image2.getHeight()) {
57            return false;
58        }
59        double maxRoughPixels = (double) (image1.getWidth() * image1.getHeight()) * roughness;
60        int errorCount = 0;
61        for (int x = 0; x < image1.getWidth(); x++) {
62            for (int y = 0; y < image1.getHeight(); y++) {
63                if (image1.getRGB(x, y) != image2.getRGB(x, y)) {
64                    errorCount++;
65                    if (errorCount > maxRoughPixels) {
66                        return false;
67                    }
68                }
69            }
70        }
71        return true;
72    }
73}
74