Friday, August 10, 2018

Resizing partitions within an image file

I wanted to backup a 32GB SD Card to a 16GB SD Card. The 32 GB SD Card only contained 10GB of data so it should be possible.

I started by creating an image file of the 32GB SD Card

$ dd if=/dev/sdb of=SDCard.img

To complicate things, the original SD Card had 2 partitions, a FAT32 boot partition and and ext4 root partition. The key to making this work would be to shrink the root partition. I used this guide to accomplish the task.

Create a new loopback device

$ sudo losetup -f

Attach the image file to the new loopback device

$ sudo losetup /dev/loop9 SDCard.img


Run GParted on the attached loopback device

$ sudo gparted /dev/loop0

Use GParted GUI to resize the partitions to suit your need

Then disconnect the loopback device

$ sudo losetup -d /dev/loop0

Use Fdisk to findout the last used sector on the image 

$ fdisk -l SDCard.img

Disk SDCardBackup.img: 29.6 GiB, 31724666880 bytes, 61962240 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x32e07f87

Device Boot Start End Sectors Size Id Type
SDCardBackup.img1 8192 93236 85045 41.5M c W95 FAT32 (LBA)
SDCardBackup.img2 94208 20574207 20480000 9.8G 83 Linux


Calculate the last byte and use truncate to chop the file down to size!

$ truncate --size=$[(20574207+1)*512] SDCardBackup.img


Hope this helps others in the same predicament!

No comments:

Post a Comment