views:

163

answers:

3

Hi,
I would like to not duplicate the image if it's the same that is posted,

Like:

user1 post an image
user2 post the same image

2 # images in the db

Is there a way to handle that ??

Thanks,

A: 

Calculate the hash of each image as it is saved. When a new user posts the same image, check the hash of that image and see if it matches anything in the database

Aaron M
yes thats what I thought but I just fear doing a hash on an image each time before saving one would be kind of slow (but didn't try)
Mike
+1  A: 

http://www.codeproject.com/Messages/2913691/Comparing-one-image-to-many-others-speeded-up.aspx

I use it in my program and all fine!

DB related advice: store hashes in table. and then you just need one hash calculation.

About speed

1) Constrain image size 100x100 for example

2) When user try to log in, hash of his password calculated. i think users will login more frequently then update their avatars.

Trickster
that makes sense, I'll try that this evening, Thanks
Mike
A: 

To accomplish this you'd need to break out your attachments into their own model.

So where you likely now have

class User < ActiveRecord::Base
   has_attached_file :avatar #plus a bunch of specifications here
end

You would setup a new model and associations like

class User < ActiveRecord::Base
   belongs_to :images
end 

class Image < ActiveRecord::Base
   has_many :users
   has_attached_file :avatar
end

Then in your controller, you would need to do

Image.find_or_create_by_avatar_file_name(#filename here)

So now you have an user.image_id attribute and can have a single uploaded image associated with multiple users.

However, I've built a number of fairly large systems with user photo uploads (badge photos, avatar photos, fun pics, whatever) and the actual overlap between users tends to be quite small. Further, you're really only saving money on what is the cheapest of your resources: storage space. You don't save anything on bandwidth costs, processing or programmatic complexity by going this route.

Unless this is a really unique set of circumstances (in which case it would be neat to hear what you're doing) I would advise against going this route.

Mike Buckbee
yes I can have a single uploaded image associated with multiple users but ... how can I compare a new uploaded image with the other one ?
Mike
I added some controller code to my answer. You'd need to sort out the uploaded filename and maybe do a comparison on size.
Mike Buckbee
Thanks, for your complete reply, you definitely right --> storage is cheap even with thousands of duplicate, its ok ...
Mike