JRuby Image Comparison – Part 2

JRuby Image Comparison – Part 2

In continuation to find ways of comparing if images are equal I decided to try comparing them as byte arrays.

First we need to declare some library’s. We will be using JRuby for these examples. If you want to use Java this will look simular.

require 'java'

java_import 'java.awt.image.BufferedImage'
java_import 'javax.imageio.ImageIO'
java_import 'java.io.ByteArrayOutputStream'

Now we need to make a function that will allow us to open an image as a bufferedImage, and a function to convert image to a byte array.

def get_image(filename)
  file = java::io::File.new(filename)
  return ImageIO::read(file)
end

def byte_array(image)
  os = ByteArrayOutputStream.new
  ImageIO::write(image, "png", os)
  return os.toByteArray()
end

Lastly we need a way to compare the 2 arrays to see if they are equal

def compare(img1, img2)
  java::util::Arrays.equals(b1, b2)
end

Want to download the whole script checkout Github