kilag
kilag

Reputation: 576

Create a unique hash of image in python

I use a programme to store some image on a storage in line (swarm), where the link is directly compute from image data to build a hash.

The issue is that if I upload 2 times the same image, it will create the same hash, that I don't want : I want each hash unique, even if the photo is the same.

So I search a way to modify in in python just a little the image before to upload it.

I have try for example to modify 1 pixel with a random choice like that :

from random import randint

image = Image.open(file)
i = randint(30, image.size[0] - 30)
j = randint(30, image.size[1] - 30)
pixels = image.load()
pixels[i,j]=(pixels[i, j][0], pixels[i, j][1] - 1, pixels[i, j][2])

but for a reason I don't understand it doesn't change anything to the hash

I have also trying to modify so info of the image, without success (with the current UTC time + random code)

So do you have a solution to solve this problem ?

here you have the documentation of swarm : https://docs.ethswarm.org/docs/getting-started/upload-and-download which say "In Swarm, every piece of data has a unique address which is a unique and reproducible cryptographic hash digest. If you upload the same file twice, you will always receive the same hash. This makes working with data in Swarm super secure!"

so I don't understand why modifying 1 pixel is not working.

Also if it can help, here the way I upload a file on swarm

headers = {"content-type": f"image/png", "Swarm-Pin": "true"}
result = requests.post("https://gateway.ethswarm.org/files", data=file, headers=headers)

edit : the full code I have try as requested in comment:

image = Image.open(file)
output = io.BytesIO()
i = randint(0, image.size[0])
j = randint(0, image.size[1])
pixels = image.load()
pixels[i,j]=(pixels[i, j][0], pixels[i, j][1] - 1, pixels[i, j][2])
image.save(output, format=image_format)
result = requests.post("https://gateway.ethswarm.org/files", data=output.getvalue(), headers=headers)

Upvotes: 0

Views: 1422

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207425

Rather than alter the pixel content of your image, which is not very desirable, you might consider using the uuid module to generate a unique UUID, convert it to a string and save it as the comment in your PNG/JPEG file. That ensures that your hash will always be unique.

Note also, that merely reading a JPEG with PIL and saving it, even without changing a pixel, will probably cause changes to file size and pixel values because JPEG is lossy. So maybe also consider using exiftool to set the comment to avoid decoding and re-encoding the pixels.

Upvotes: 1

Related Questions