AI & ML

How SD Card Photo and Video Recovery Works: A Practical Guide With a JPEG Carving Example

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

How SD Card Photo and Video Recovery Works: A Practical Guide With a JPEG Carving Example

DJ
Div John
Published in
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

How SD Card Photo and Video Recovery Works: A Practical Guide With a JPEG Carving Example
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

For photographers, videographers and content creators, an SD card is more than a storage device. It holds the raw material behind a finished project: wedding photographs, travel footage, product demos and drone recordings that may be impossible to recreate. Data loss can happen at almost any stage of that workflow, from a folder deleted to make space to a card formatted before the footage was backed up.

This article explains why files on a card become unavailable, what to do in the first minutes, how recovery tools find data, and how to compare options. It includes a small Python example that recovers JPEG files from a disk image, so you can see the mechanism for yourself. It also compares free open-source tools with paid graphical ones, using criteria you can apply yourself. Recovery is never guaranteed, and tool features change, so confirm details against each vendor’s current documentation.

Key Takeaways

  • Stop writing to the card immediately. New writes can overwrite the space where deleted files still sit.
  • Work on a copy where you can. An image of the card lets you scan repeatedly without touching the original.
  • Recovery and repair are different jobs. Recovery retrieves data, while repair fixes damage that stops a file from opening.
  • Tools use two main methods. File-system analysis restores names and folders, and signature carving finds files by their contents.
  • Verify results. A recovered file can be incomplete or corrupt, so preview and check before you trust it.

Why SD Card Data Loss Is So Difficult

Recovery is not just a matter of finding a deleted filename. Several different problems can make files unavailable, and they call for different approaches.

  • Accidental deletion. On most file systems, deleting a file removes its directory entry or marks its space as free, while the data often remains until something overwrites it.
  • Accidental formatting. A quick format rewrites file system structures but usually leaves much of the old data in place. A full format or overwriting may be more destructive.
  • Interrupted recording. If a camera loses power or the card is removed mid-write, a video can be left without the structural information a player needs.
  • File system or partition problems. Corruption in the allocation table or partition table can make a card appear empty or ask to be formatted even though the data is still there.
  • Physical damage. A cracked or failing card is a different problem, and may need a specialist.

What to Do Before Attempting Recovery

  1. Stop using the card. Do not take more photos or copy files onto it. The PhotoRec documentation gives the same advice: stop saving anything to the affected device.
  2. Do not format the card again. Even if the camera or computer asks you to, decline.
  3. Avoid unneeded repair operations. Disk check and repair tools can rewrite structures you may need to recover from.
  4. Connect the card carefully. Use a reliable card reader and avoid hubs that disconnect.
  5. Prepare a separate destination. Do not save recovered files to the same card or partition they came from.

These steps cannot guarantee recovery, but they reduce avoidable risk.

How Recovery Tools Find Your Files

Most tools combine two methods, and understanding them helps you read scan results.

  • File system analysis. The tool reads leftover directory entries and allocation tables from FAT32 or exFAT, the usual card formats. When this works, you get original names, folders and timestamps back.
  • Signature carving. The tool scans the raw data and looks for the known opening bytes of file types. A JPEG, for example, starts with the bytes FF D8 FF. PhotoRec’s documentation describes this approach: it ignores the file system, checks each block against a database of signatures, and can still work when the file system is badly damaged or was reformatted.

Carving has a cost. Because file system information is ignored, names and folder structure are usually lost, which is why scan results often show generic names. Fragmented files can also be recovered incomplete, since the tool assumes the pieces are stored one after another. Free tools build on these same ideas. Wondershare Recoverit V15, which also offers a free version for Windows and Mac, adds a graphical interface, while PhotoRec and ddrescue stay closer to the command line.

See Carving in Action

The script below is a teaching sketch, not a recovery product. It reads a raw disk image, finds JPEG start markers, and writes out the bytes up to the last end marker before the next start. That detail matters because a JPEG can contain an embedded thumbnail with its own markers, so stopping at the first end marker would cut a file short.

"""Carve JPEG files out of a raw disk image by signature (a teaching sketch, not a product)."""
import sys
from pathlib import Path

SOI = b"\xff\xd8\xff"   # JPEG start: FF D8 FF
EOI = b"\xff\xd9"       # JPEG end:   FF D9
MAX_SIZE = 40 * 1024 * 1024  # ignore anything longer than 40 MB

def carve_jpegs(image: bytes):
    starts, pos = [], 0
    while (i := image.find(SOI, pos)) != -1:
        starts.append(i)
        pos = i + 1
    for n, start in enumerate(starts):
        limit = starts[n + 1] if n + 1 < len(starts) else len(image)
        limit = min(limit, start + MAX_SIZE)
        end = image.rfind(EOI, start, limit)   # last FF D9 before the next header
        if end != -1:
            yield start, image[start:end + 2]

if __name__ == "__main__":
    src, out = Path(sys.argv[1]), Path(sys.argv[2])
    out.mkdir(exist_ok=True)
    data = src.read_bytes()          # fine for small images; stream large ones
    for k, (offset, blob) in enumerate(carve_jpegs(data), 1):
        (out / f"carved_{k:04d}_at_{offset}.jpg").write_bytes(blob)
        print(f"carved_{k:04d}: offset {offset}, {len(blob)} bytes")

A short test builds two real JPEGs, hides them in random bytes, and checks that both are carved and open as valid images:

import io, os
from PIL import Image
from carve import carve_jpegs

def jpeg(color):
    buf = io.BytesIO()
    Image.new("RGB", (64, 48), color).save(buf, "JPEG")
    return buf.getvalue()

a, b = jpeg("red"), jpeg("blue")
image = os.urandom(5000).replace(b"\xff\xd8\xff", b"\x00\x00\x00") + a + bytes(3000) + b + bytes(2000)
found = list(carve_jpegs(image))
assert len(found) == 2
for _, blob in found:
    Image.open(io.BytesIO(blob)).verify()   # raises if the carved bytes are not a valid JPEG
print("carved", len(found), "valid JPEGs")

Use it on an image rather than the card itself. On Linux you can make one with a read-only copy, for example with the GNU ddrescue tool, which is designed to copy data from failing media. Then run the carver against the image and save the output to a different drive. Real tools handle many more formats, trim files using header information, and deal with video containers, so treat this as a way to understand the idea.

Comparing Recovery Options

The right choice depends on the problem, your platform and how comfortable you are with the command line. The table summarizes what each project’s own documentation states.

OptionWhat its documentation describesStrengthsLimits
PhotoRecFree, open-source recovery that reads media read-only and uses file signatures; recognizes more than 480 file extensionsWorks on cards, disks and many file systems; GPL licensedText interface; names and folders are usually lost
TestDiskFree, open-source tool for recovering lost partitions, repairing boot sectors and undeleting files on FAT, exFAT, NTFS and ext2Good when the partition table or file system is damagedAimed at technical users; not a media browser
ddrescueGNU tool for copying data from failing storage to an imageCreates a safe image to work onCopies only; you still need a tool to extract files
Graphical recovery suites (for example Wondershare Recoverit V15)Graphical tools that typically add previews, filters and sometimes video repair; features vary by product and editionEasier for non-technical usersFree editions may limit what you can save, so check current terms; claims and success rates are the vendor's own, so test on a copy
Do-it-yourself carvingA script like the one aboveTeaches how recovery worksLimited formats and no repair

A Practical Recovery Workflow

The order of steps matters more than the choice of tool. A cautious workflow on Linux or macOS looks like this:

  1. Image the card first. A read-only copy with ddrescue, for example ddrescue -d /dev/sdX card.img card.map, keeps the original untouched and the map file records which areas could not be read. Check the device name carefully before running it.
  2. Scan the image, not the card. Run photorec card.img and choose a destination on a different drive. If the card shows as empty or asks to be formatted, TestDisk can inspect the partition table first.
  3. Sort the output. Carved files have generic names, so sort by type and size, discard tiny thumbnails, and open a sample of each batch.
  4. Verify every file you keep. Open photos fully and play videos through, using the check described below.

Graphical tools follow the same logic and mainly change step 3, with thumbnails, filters and search that make large result sets easier to browse. Whether that is worth paying for depends on how many files you need to sift through and how comfortable you are on the command line. When comparing any tool, ask:

  • Does it read the card read-only? It should never write to the source.
  • Can it scan a disk image? This lets you retry safely.
  • Does it preview files before you pay or save? A preview is a quick integrity check.
  • What does the free version actually let you recover? Limits differ between products and change over time.
  • Are its success claims independently tested? A vendor's recovery rate describes the vendor's own tests, not your card.

Features such as search by capture time, folder or AI-based tagging depend on metadata surviving the loss, and they narrow results without proving a file is intact. Treat them as convenience, not verification.

Recovery Versus Repair

Recovering a video file does not necessarily mean recovering a playable video. A recording interrupted during writing can lack the structural information a player needs, and other files may be damaged in ways that block playback.

The distinction matters. Recovery retrieves missing or inaccessible data, while repair tries to fix damage that affects a file’s usability. Some cases need one, the other or both. Repair has limits too: if essential video data was overwritten or never recorded, software cannot recreate the original footage in full. After any recovery or repair, play the file all the way through and compare it with what you expect.

For a quick check of a recovered clip, ffprobe can show whether the container is readable:

ffprobe -v error -show_entries format=duration,size -of default=noprint_wrappers=1 recovered_clip.mp4

An error or a missing duration suggests the file needs repair or is incomplete.

Preventing the Next Loss

  • Copy cards to two places before reformatting them.
  • Format cards in the camera, not on a computer, and eject them properly.
  • Replace cards that show errors, and do not fill them to the last byte.
  • Use a checklist at the end of each shoot: copy, verify, then clear.

Limits and Open Questions

  • No tool can recover data that has been overwritten.
  • Results vary with the card, camera, file system and how the card was used after the loss.
  • Vendor descriptions of features and success rates reflect their own testing, so test with your own cards, ideally on a copy.
  • The carving script is a teaching sketch. It handles JPEG only and does not rebuild fragmented files.
  • Free open-source tools and paid tools overlap, and the best choice depends on your skills and time.

FAQ

Can deleted photos be recovered from an SD card?

Often yes, if nothing has overwritten them. Stop using the card immediately and scan it or an image of it.

Should I format the card to fix errors?

Not before recovery. Formatting changes file system structures and may make recovery harder.

What is the difference between recovery and repair?

Recovery retrieves missing data. Repair fixes a file that exists but will not open or play correctly.

Do I need paid software?

Not always. PhotoRec and TestDisk are free and open source, while paid tools add a graphical interface and extras such as previews, filtering and video repair.

Where should I save recovered files?

On a different drive from the card. Saving to the same card can overwrite data you still want.

Conclusion

SD card data loss creates two related challenges: getting files back, and working out which recovered files are useful. Stopping use of the card, working on an image and understanding the difference between file system recovery, carving and repair put you in a better position, whichever tool you choose. Graphical tools aim to make large result sets easier to navigate, and free tools such as PhotoRec and TestDisk remain solid options. Try your chosen tool on a copy first, verify what you recover, and keep a backup so you do not need to do this again.

hostinger_2026_11_footer
Source: Div John · www.sitepoint.com