EST. 2026 — Notes from real server work SYSADMIN · SECURITY · AI · DIRECTADMIN Issue 01
THE SYSADMIN ALMANAC
Home / Web / One Image Saved as 4 Files: File Hashes Miss It, dHash Finds It
Web

One Image Saved as 4 Files: File Hashes Miss It, dHash Finds It

by Ton-Or ·30 Nov 2026·11 min read
One Image Saved as 4 Files: File Hashes Miss It, dHash Finds It

A checksum can only tell whether two files are identical byte for byte. It cannot tell whether they look like the same image to a person. Checking for duplicate covers takes a hash that compares visual patterns, followed by a human review.

1-minute summary

Symptom / problem
The same cover image was uploaded under several ids, and GROUP BY id or md5 misses most of them
Who should read
Anyone maintaining an image library or a migrated site with duplicate images
Fix in short
Compute a 64-bit dHash, treat Hamming distance of 6 or less as a duplicate, group with union-find, then have a person confirm from a contact sheet
Jump to steps

I happened to open the extra services page on a client's website just after finishing its migration. The page separated listings by zone. When I selected one zone, an entire row of cards used the same cover image, with only the service names differing. The site owner noticed it too and gave me a brief instruction: check every duplicate image, make a list, and replace them one by one. I thought a single line of SQL would finish the job. I was wrong, so I wrote this down to record where that assumption failed and what I ended up using.

The service names, zones, and id numbers in this article are all fictional. The group counts, item counts, and thresholds come from the actual job.

First thought: GROUP BY media id and done

The new system stores images in a central table, and each item references its cover by media id. I started with the most direct approach: find cover ids used by more than one item.

SELECT cover_media_id, COUNT(*) AS n,
       GROUP_CONCAT(id ORDER BY id) AS items
FROM   services
WHERE  status = 'published' AND cover_media_id IS NOT NULL
GROUP  BY cover_media_id
HAVING n > 1
ORDER  BY n DESC;

That returned some results, but comparing them with what I could see on the website showed that a lot was missing. There was a row of four cards clearly using the same image, yet this query reported none of them.

The case that showed me this approach was insufficient was a four-part article series on the same subject. All four parts used the same illustration, but in the old system that image had been uploaded again every time a new part was written. The result was 4 ids and 4 files, all with different image dimensions and compression levels. I tried the next thing I could think of: comparing file checksums.

# สี่ไฟล์ที่ตาเห็นว่าเป็นรูปเดียวกัน ถ้าเหมือนกันทุกไบต์ต้องเหลือบรรทัดเดียว
md5sum media/0311.jpg media/0340.jpg media/0377.jpg media/0402.jpg   | awk '{print $1}' | sort -u | wc -l
# ได้ 4 = สี่ไฟล์ สี่ค่า

Not a single pair matched, which was correct behavior: changing even one byte in a file changes the entire checksum. Images resized or saved again at different quality settings are completely different files as far as md5 is concerned. In Migrating an old .aspx website to a JSON catalog, I successfully used SHA-1 to filter out unwanted images that were exact byte-for-byte duplicates. This was a different problem. These images were neither unwanted nor byte-for-byte duplicates. They were visual duplicates.

media id / checksum

Asks whether it is the same file

Only catches items referencing the same id or files identical byte for byte. Images uploaded again, resized, or saved at another quality setting all slip through.

perceptual hash

Asks whether it looks like the same image

Reduces the image to a brightness pattern and compares that pattern. It tolerates resizing and compression, but can group images that merely look similar, so human review is needed.

How dHash works

There are several types of perceptual hash. I chose dHash (difference hash) because I could write it myself in ten lines with Pillow without installing another library, and explain to someone else where each bit comes from.

The idea is to resize the image to 9x8 grayscale pixels, 72 pixels in total, then compare each pixel in each row with the one to its right. If the left pixel is brighter, the bit is 1; otherwise, it is 0. A row has 9 pixels, giving 8 pairs to compare. Across 8 rows, that produces 64 bits, stored as a single integer.

Resize to 9x8Grayscale only72 pixelsCompare neighbors8 pairs per rowLeft brighter = 1Get 64 bits8 rows x 8 pairsStore as one numberXOR two imagesCount differing bitsUp to 6 = same imageOne grayscale row12013198981407780201190Bits for this row01001001= 01001001Bits come from neighbors: 131 greater than 98 gives 1; 98 not greater than 98 gives 0
dHash stores only whether the left pixel is brighter than the right. Compression can shift grayscale values, but the relative brightness of neighboring pixels barely changes.

This is the entire function I used.

from PIL import Image

def dhash(path, size=8):
    # 9x8 เทา: กว้างกว่าสูง 1 พิกเซล เพื่อให้แต่ละแถวเทียบได้ 8 คู่
    im = Image.open(path).convert("L").resize((size + 1, size), Image.LANCZOS)
    px = list(im.getdata())
    bits = 0
    for r in range(size):
        for c in range(size):
            left = px[r * (size + 1) + c]
            right = px[r * (size + 1) + c + 1]
            bits = (bits << 1) | (left > right)
    return bits

def distance(a, b):
    # ระยะ Hamming: XOR แล้วนับบิตที่เป็น 1
    return bin(a ^ b).count("1")

To compare two images, XOR their 64-bit numbers. Differing bits become 1, and counting those bits gives the Hamming distance. A value of 0 means the brightness patterns match at every point. I treated images as the same when the distance was no more than 6 out of 64 bits.

Test before trusting: four versions of one image, and images that should not match

Before running this on the actual images, I tested it with a synthetic image on my own machine to see what this threshold could and could not tolerate. I created one 1200x800 image and saved several versions: JPEG at quality 92, resized to 900x600 at quality 80, resized to 640x427 at quality 60, saved as PNG, cropped by 20 percent from the left and top, flipped horizontally, and one unrelated image.

Test file md5 (first 8 characters) dHash Distance from original
JPEG quality 92 c759f5d4 1c64e4ec848c8cb4 0
900x600 quality 80 cf80b3e9 1c64e4ec848c8cb4 0
640x427 quality 60 0ef80f0b 1c64e4ec848c8cb4 0
PNG 4aaf18a3 1c64e4ec848c8cb4 0
Cropped by 20 percent 0e0e6672 ccd0dc8d58586868 31
Flipped horizontally c494c962 c4d9d8c8dec6c6d2 30
Other image e81ea163 e4859be38a9b994b 38

The md5 differed in every row, but the first four rows had the same dHash. This was exactly the case that had stalled me with the four-part article series. The bottom three rows made the limitations clear: heavily cropped or flipped images had distances of 30 or more, about the same as an entirely unrelated image. So dHash is not a tool for finding altered images. It finds images that have been saved again.

The numbers in this table come from test images, not the actual images

The synthetic image gave a distance of exactly 0 because its content was smooth. Real photographs compressed several times usually do not give 0, but shift by a few bits. My threshold of 6 allows for this, and its results need human confirmation. It is not a value that is always correct for every image set.

Grouping with union-find because similarity carries through

Having all the hashes was not the end, because the owner wanted "groups," not "pairs." Reporting pairs would turn a group of 7 items into 21 unreadable lines.

At first, I considered a simple grouping method: pick the first image as the representative and collect every image within a distance of 6 from it. But the result depends on which image is picked first, because threshold-based similarity can carry through a chain without holding for every pair. A is close to B, and B is close to C, but A and C may be farther apart than the threshold. If A is the representative, C ends up in another group, even though all three are the same image saved repeatedly in succession.

Group 1: A-B-C joined through B9 (over 6)Cover A4Cover B5Cover CSolid = Hamming distance at most 6Dashed = over threshold, no direct linkGroup 2: same media idCover D0Cover ECover FClose to noneNot groupedA and C are 9 bits apart, but both are close to B, so they share a group
There are two conditions for a link: the same media id, or a dHash distance of no more than 6 bits. A group contains every item reachable by following those links.

union-find solves this directly. It does not care which image is the representative, only which images connect, and merges everything reachable into one group. The result does not depend on order.

import json

MAX_DIST = 6
rows = json.load(open("covers.json", encoding="utf-8"))   # [{id, title, media_id, file}]
for r in rows:
    r["hash"] = dhash(r["file"]) if r.get("file") else None

parent = list(range(len(rows)))

def find(i):
    while parent[i] != i:
        parent[i] = parent[parent[i]]     # path halving ให้ต้นไม้เตี้ย
        i = parent[i]
    return i

for i in range(len(rows)):
    for j in range(i + 1, len(rows)):
        a, b = rows[i], rows[j]
        same = a["media_id"] and a["media_id"] == b["media_id"]
        near = (a["hash"] is not None and b["hash"] is not None
                and distance(a["hash"], b["hash"]) <= MAX_DIST)
        if same or near:
            parent[find(i)] = find(j)

clusters = {}
for i, r in enumerate(rows):
    clusters.setdefault(find(i), []).append(r)
dups = sorted((c for c in clusters.values() if len(c) > 1), key=len, reverse=True)
print(f"items {len(rows)} | groups {len(dups)} | items in groups {sum(map(len, dups))}")

There were 249 published service items, giving approximately 31,000 pairs. A straightforward comparison loop handled that easily, with no index or nearest-neighbor search structure needed. Personally, I would not consider anything more complicated until the image count reached tens of thousands.

Three outputs, and a contact sheet for review

The script produced three files. The first was JSON organized by group for the next program to read. The second was a markdown report listing the group number, group size, items, categories, zones, and media ids to send to the owner. The third was the most important: a PNG contact sheet with one group per row, 220x146 pixels per cell, and a number on every cell.

from PIL import Image, ImageDraw

W, H, PAD = 220, 146, 18          # PAD = แถบตัวหนังสือเหนือรูป
cols = max(len(c) for c in dups)
sheet = Image.new("RGB", (W * cols, (H + PAD) * len(dups)), "white")
draw = ImageDraw.Draw(sheet)

for row, group in enumerate(dups):
    for col, item in enumerate(sorted(group, key=lambda r: r["id"])):
        try:
            im = Image.open(item["file"]).convert("RGB")
            im.thumbnail((W, H))
            sheet.paste(im, (col * W, row * (H + PAD) + PAD))
        except OSError:
            pass                    # ไฟล์เปิดไม่ได้ ปล่อยช่องขาวไว้ให้เห็น
        draw.text((col * W + 2, row * (H + PAD) + 2),
                  f"G{row + 1} #{item['id']}", fill="black")

sheet.save("dup_sheet.png")

The sheet was necessary because the 6-bit threshold does not guarantee that images are the same. Images with large flat areas, such as logos on white backgrounds or icons centered on a solid color, can easily produce similar hashes despite being different images. Most pixels in each row do not differ from their neighbors, so most bits end up as 0 in both images. A contact sheet lets a person scan each row and decide in a few seconds per group, many times faster than opening pages individually. The same sheet can also be sent to a model that can read images for another review.

Always print numbers in the cells

If a contact sheet contains only images, the reviewer has to count row and column positions and cross-reference a separate report, which is easy to get wrong. Put the group number and item number above every image so the reviewer can immediately reply with the numbers of the groups that are genuine matches and those that are not.

These were the figures from the actual job.

249Services checked
31,000 pairsAll pairs compared directly (approx.)
30 groupsFirst pass, covering 77 items
22 groupsAfter merging duplicate content, covering 61
7 itemsLargest group
41 imagesReplaced
0 groupsRecheck after replacement
109 groupsWhen expanded to covers sitewide

The first pass found 30 groups covering 77 services. Those figures were mixed up with another problem: items with duplicate content. After merging away 48 duplicate content items and checking the 249 services again, there were 22 groups covering 61 services. The largest group had 7 items: the same type of service in 7 zones, all using one image. The next-largest groups were three service subtypes in the same zone, with 3 items sharing a cover. After replacing 41 images, a recheck found 0 groups.

The order of operations was a lesson for me. I checked images before dealing with duplicate content, which inflated the numbers and forced me to run it again. If two listings already refer to the same thing, their duplicate image is not an image problem. Merge the listings first, then count the images.

On the next pass, I expanded the same checker to covers across the entire website. It found 109 groups of covers duplicated across items, which became a separate chunk of work.

Exception rules that need to be written into the tool

The raw script output could not be turned straight into work assignments, because "duplicate image" is not always wrong. I had three rules to write into the tool, rather than keep in my head.

  1. There were 146 pairs of services differing only in zone name. This content does not count as duplicate because the services really are in different zones, but the duplicate images need fixing so the zones can be distinguished from their cards.
  2. A service and an article about the same subject may use the same image. This does not count as a duplicate.
  3. When choosing a replacement from an item's own gallery, the image must not be another item's cover, must not be on the prohibited image list, must be at least 600 pixels wide, and must pass a dHash check showing it does not duplicate an existing cover.

The third rule is where dHash was used a second time. Without that check, fixing one group could create a new duplicate group elsewhere.

def pick_replacement(item, gallery, used_cover_ids, cover_hashes, blocked):
    """เลือกรูปจากแกลเลอรีของรายการเอง ที่ยังไม่ชนกับปกใดในเว็บ"""
    for g in gallery:                       # g = {media_id, file, width}
        if g["media_id"] in used_cover_ids or g["media_id"] in blocked:
            continue
        if g["width"] < 600:
            continue
        h = dhash(g["file"])
        if any(distance(h, other) <= MAX_DIST for other in cover_hashes):
            continue
        return g, h
    return None, None                       # ไม่มีรูปที่ใช้ได้ ส่งเข้าคิวหารูปใหม่
Replace images manually without registering them, and the work comes back

This website still imports content from the old system periodically. If a cover is changed directly in the database, the next import will overwrite it with the original image. Every image replacement must be recorded in a jobs file, and the new image must be registered with a manifest so the post-import command can reapply it every time.

The jobs file looked roughly like this: one block per image to replace, specifying the item, its group, a reference image, the zone, and the desired scene so the next step of finding a new image knows what it needs to convey.

[
  {"key": "dup_118", "item": 118, "group": 1, "zone": "AA",
   "ref_file": "media/0311.jpg", "scene": "สินค้าประเภทเดียวกับรูปอ้างอิง วางในฉากของโซน AA"},
  {"key": "dup_119", "item": 119, "group": 1, "zone": "BB",
   "ref_file": "media/0311.jpg", "scene": "สินค้าประเภทเดียวกับรูปอ้างอิง วางในฉากของโซน BB"}
]

In each group, one item kept its original image and had no job; the rest needed replacements. A group of 7 items therefore meant 6 image jobs, not 7. The key is the name used to register the new image in the manifest. No matter how many times it runs, it points to the same image.

The sequence I use now

  1. Finish merging items with duplicate content before checking images, or the group count will be inflated.
  2. Export published items with their media ids and cover file paths into one JSON file so the script does not need its own database connection.
  3. Calculate a 64-bit dHash for every cover, link pairs with matching media ids or a Hamming distance of no more than 6, then group them with union-find.
  4. Produce JSON, a markdown report, and a contact sheet with every cell numbered for a person to confirm each group.
  5. Apply the exception rules, then create a jobs file for images that need replacing. Select replacements using the same conditions as the checker.
  6. Register the new images with a manifest, then run the checker again. The result must be 0 groups.
From symptom to recheck resultSame image across a row of cardsSpotted by eye->media id / md5Found some->dHash + union-find22 groups, 61 items->Human contact sheet reviewConfirm each group->Replace 41 imagesRecheck: 0 groups

Limitations to spell out

An 8x8 dHash is deliberately a crude tool. It is good at catching the same image uploaded again, resized, or recompressed. There are at least three things it cannot handle. The first is heavy cropping and flipping, as the test table above shows. The second is images with flat backgrounds that produce similar hashes despite being different images. The third is that it does not understand what an image means. Two photographs of the same place from different angles are different images to it, which was the correct result for this job: the owner only wanted the cards to stop using the same image.

The threshold of 6 worked for this image set with human confirmation of the results. Anyone applying it to another set might adjust it to 4 or 8 depending on the images, but should always keep the contact sheet and final human review. If the threshold changes, check whether the largest group grows unusually large, because union-find merges everything reachable through the links. A threshold that is too loose will bridge unrelated images into one giant group.

To sum up, ids and checksums answer questions about files, while the site owner's question was about what people see. The tool needs to match the question, and its results need to be recorded somewhere the next import cannot erase. If I have missed an explanation or made a typo, I will come back and fix it later.

Want us to set this up?

Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.

Get a quote

Hit something like this? Stuck somewhere?

Come trade notes on the LinuxThai board

→ Continue on the board

Comments 0

No comments yet — be the first