PixelGrabber là một thư viện Java cho phép lấy ra các điểm ảnh (pixels) trên hình và từ đó có thể dùng để so sánh để phát hiện ra sự thay đổi, khác biệt giữa hai bức ảnh. Có thể ứng dụng vào Automation để nhận biết những sự thay đổi layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package ComparePixels; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.PixelGrabber; import java.io.File; public class Test { public static void main(String args[]) { try { // Set the image location String firstImagePath = "images/01_changed.png"; String secondImagePath = "images/02_changed.png"; // Check the file exists File tempFirstImage = new File(firstImagePath); boolean firstImageExists = tempFirstImage.exists(); File tempSecondImage = new File(secondImagePath); boolean secondImageExists = tempSecondImage.exists(); if ((firstImageExists == true) && (secondImageExists == true)) { // Get image information Image firstImage = Toolkit.getDefaultToolkit().getImage(firstImagePath); Image secondImage = Toolkit.getDefaultToolkit().getImage(secondImagePath); PixelGrabber firstGrabber = new PixelGrabber(firstImage, 0, 0, -1, -1, false); PixelGrabber secondGrabber = new PixelGrabber(secondImage, 0, 0, -1, -1, false); int[] first_data = null; if (firstGrabber.grabPixels()) { int width = firstGrabber.getWidth(); int height = firstGrabber.getHeight(); first_data = new int[width * height]; first_data = (int[]) firstGrabber.getPixels(); } int[] second_data = null; if (secondGrabber.grabPixels()) { int width = secondGrabber.getWidth(); int height = secondGrabber.getHeight(); second_data = new int[width * height]; second_data = (int[]) secondGrabber.getPixels(); } // Compare 2 images and check the results boolean result = java.util.Arrays.equals(first_data, second_data); if (result == true) { System.out.println("Passed. They are the same!"); } else { System.out.println("Failed. There are some difference between 2 images!"); } } else { System.out.println("File(s) could not found!"); } } catch (InterruptedException e) { e.printStackTrace(); } } } |
Kết quả:
Input layout: 01.png & 02.png
Output: Passed. They are the same!
Input layout: 01_changed.png vs 02_changed.png
Output: Failed. There are some difference between 2 images!
Nếu file không tồn tại sẽ hiển thị thông báo: File(s) could not found!
The PixelGrabber class implements an ImageConsumer which can be attached to an Image or ImageProducer object to retrieve a subset of the pixels in that image.
Nhận diện hình ảnh là một chủ đề hay và đáng tìm hiểu để ứng dụng vào kiểm thử tự động.
5 Comments