package com.company.MyFirstProgect; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\kuhaj\\Downloads\\image1.png"); File file1 = new File("C:\\Users\\kuhaj\\Downloads\\image2.png"); BufferedImage image1 = ImageIO.read(file); BufferedImage image2 = ImageIO.read(file1); int columns = image1.getWidth(); int rows = image1.getHeight(); for (int row = 0; row < rows; rows++) { for (int col = 0; col < columns; col++) { int rgb = image1.getRGB(col, row); int rgb2 = image2.getRGB(col, row); if (rgb != rgb2){ System.out.println("NO!!!!!"); } } } } } 

When image1 and image2 different, this code still considers them the same and does not output NO!!!!! What is the problem?

  • And what's the problem? Please describe what specifically does not work. - Viacheslav Vedenin
  • Do not compare pictures they are the same! But in fact they are different! - Alexander Kukhtin
  • At a minimum, you need to compare the sizes of the first and second pictures, you now get that if the first picture is 10 by 10, then the second is 1000 by 1000, then only a slice from the first picture is compared - Viacheslav Vedenin
  • Chuchut did not understand what the problem was - Alexander Kukhtin
  • 6
    @AlexanderKukhtin you, by the way, in the question of rows++ , but should be row++ - Regent

1 answer 1

To compare any objects, the first thing to do is compare the size of the objects.

 if (image1.getWidth() != image2.getWidth() || image1.getHeight() != image2.getHeight()){ System.out.println("NO!!!!!"); return; } 

Otherwise, if the first picture is 1 per 1 pixel, then you will compare the first pixel from the second picture and if it matches, then consider the pictures to be the same, even if the second picture is much larger.

PS Also in the comments you wrote that instead

  for (int row = 0; row < rows; rows++) { 

must be

  for (int row = 0; row < rows; row++) { 

With rows ++, you only compare row = 0 (the zero row of all columns), then it comes to int overflow and exits.

  • Nfr So then you need to use variables - Alexander Kukhtin
  • Yes, sorry, the author poorly formulated the proposals - did not immediately realize - Regent
  • I apologize, there are 2 pictures they are identical but on the 2nd picture there is an inscription that is not on the first picture, but why does the condition show that they are the same? - Alexander Kukhtin