Compare images in Rails

Kavita Jadhav
Jun 9, 2022

--

https://www.fresherslive.com/latest/articles/brain-teaser-spot-the-difference-picture-puzzle-can-you-spot-3-differences-in-these-pictures-1555147828

Let’s assume a scenario where you continuously sync images from other applications into your application and you don't have a way to identify if the image is updated or not. Here now instead of simply updating the image every time you can compare the MD5 hash of those images to identify if the image is updated or not.

Example1: When your images are present on the internet

new_image_url = 'http://source.com/user/100/profile.jpg'
existing_image_url = 'http://destination.com/user/100/profile.jpg'

new_image_file = URI.parse(new_image_url).open
existing_image_file = URI.parse(existing_image_url).open

new_image_md5 = Digest::MD5.file(new_image_file.path).hexdigest
existing_image_md5 = Digest::MD5.file(existing_image_file.path).hexdigest

if new_image_md5 != existing_image_md5
user.update_profile(new_image_file)
end

Example2: When your images are present on file system

new_image_path = '/Users/myuser/user_service/source_images/100/profile.jpg'
new_image_path = '/Users/myuser/user_service/destination_images/100/profile.jpg'
new_image_file = File.open(new_image_path)
existing_image_file = File.open(existing_image_path)
new_image_md5 = Digest::MD5.file(new_image_file.path).hexdigest
existing_image_md5 = Digest::MD5.file(existing_image_file.path).hexdigest
if new_image_md5 != existing_image_md5
user.update_profile(new_image_file)
end

Happy coding!

--

--

Kavita Jadhav
Kavita Jadhav

Written by Kavita Jadhav

Application Developer @ Teladoc Health

No responses yet