Compare images in Rails

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

Example1: When your images are present on 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kavita Jadhav

Kavita Jadhav

Application Developer @ ThoughtWorks Technologies