How to resize img file created with dd


I have a DD image from a 4GB SD card that has two partitions, these two partitions are only using up about 800 MB and as such I wish to reduce the size of the img fie.

Does anyone know of a way to remove the "free space" from the img file?

Best Answer

First make sure the free space is actually empty, and doesn't contain leftovers of deleted files. The easiest way to achieve this is to create a huge file on the disk, containing only null bytes, then delete it.

# losetup --find --partscan foo.img
# lsblk
loop0       7:0    0   4096M  0 loop 
├─loop0p1 259:0    0   2048M  0 loop 
└─loop0p2 259:1    0   2048M  0 loop 
# for part in /dev/loop0p*; do
    mount $part /mnt
    dd if=/dev/zero of=/mnt/filler conv=fsync bs=1M
    rm /mnt/filler
    umount /mnt
dd: error writing ‘/mnt/filler’: No space left on device
dd: error writing ‘/mnt/filler’: No space left on device
# losetup --detach /dev/loop0

Then compress it with a tool like gzip or xz. Even at lowest compression levels, a long series of zeros will compress well:

# ls -s
4096M foo.img
# gzip foo.img
# ls -s
11M foo.img.gz

Note that you must uncompress the image when writing it back to disk. This will uncompress it 'live':

# cat foo.img.gz | gunzip | dd of=/dev/sda

Note that the output device (sda) must be of sufficient size to fit the original image, otherwise data will be lost or corrupted.

An alternative method, if you want to keep using the image – e.g. with a virtual machine – is to convert the raw image to one of the image formats used by virtualization software; e.g. qcow2 for Qemu, VDI for VirtualBox, or VMDK for VMware.

Note that this still requires you to prepare the image by cleaning the free space using the above method.

# qemu-img convert -f raw -O qcow2 foo.img foo.qcow

# qemu-img convert -f raw -O vmdk foo.img foo.vmdk

But if it's going to be written to a real disk again, you have to convert it back to a raw image.