# Image File Reparing

An image sometimes is corrupeted. We can repair it using some techniques.

### Check the Cause of Damage <a href="#check-the-cause-of-damage" id="check-the-cause-of-damage"></a>

#### Dump Hex from an Image <a href="#dump-hex-from-an-image" id="dump-hex-from-an-image"></a>

We can edit the image Hex header to repair the corrupted image to the correct format.\
To do that, check the hex header at first.

```shellscript
xxd example.jpg | head
xxd example.png | head
```

#### Using Tools <a href="#using-tools" id="using-tools"></a>

```shellscript
# for PNG
pngcheck example.png
# -vv: very verbosely check
pngcheck -vv example.png
```

### Edit Hex to Adding Magic Bytes <a href="#edit-hex-to-adding-magic-bytes" id="edit-hex-to-adding-magic-bytes"></a>

We might be able to repair a corrupted image by inserting magic bytes for each file format.\
We can use **`hexedit`** or **`ghex`** to edit hex manually other than the following techniques.

To check magic bytes for each file, see [wikipedia](https://en.wikipedia.org/wiki/List_of_file_signatures).

#### JPG (FF D8 ...) <a href="#jpg-ff-d8" id="jpg-ff-d8"></a>

To repair a JPG image , run the following command.\
\&#xNAN;**'\xff\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01'** means **‘. . . . . . JFIF . .’**. It identifies JPG format.

```shellscript
# of=example.jpg: Write to file
# bs=N: Read and write up to N bytes at a time. 
# conv=notrunc: Convert the file as per the comma separated symbol list. 'notrunc' means "Do not truncate the output file."
printf '\xff\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01' | dd of=example.jpg bs=1 conv=notrunc
```

Confirm the header repaired.

```shellscript
xxd example.jpg | head

00000000: ffd8 ffe0 0010 4a46 4946 0001 0100 0001  ......JFIF......
00000010: 0001 0000 ffdb 0043 0003 0202 0302 0203  .......C........
00000020: 0303 0304 0303 0405 0805 0504 0405 0a07  ................
...
```

#### PNG (89 50 4E 47 ...) <a href="#png-89-50-4e-47" id="png-89-50-4e-47"></a>

To repair a PNG image, run the following command.\
\&#xNAN;**'\x89\x50\x4E\x47'** means **‘. PNG’**. It identifies PNG format.

```shellscript
printf '\x89\x50\x4e\x47' | dd of=example.png bs=4 conv=notrunc
```

Confirm the header.

```shellscript
xxd example.png | head

00000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452  .PNG........IHDR
00000010: 0000 0320 0000 0320 0806 0000 00db 7006  ... ... ......p.
00000020: 6800 0000 0173 5247 4200 aece 1ce9 0000  h....sRGB.......
...
```
