Shrinking Raspberry Pi SD Card images for transfer/storage

As part of a project I’ve been working on, I’ve been building a customised version of Raspbian on 16GB SD cards. As all good engineers should do I’ve been taking snapshots of my work at various times by copying an image of the dev SD card to my backup storage.

However, each image is 16GB, the size of the card, but only contains about 2.5GB of actual data, the rest is free space in the Raspbian root filesystem.

I’d rather only store the data I need, so here’s a nifty script I whipped up to reduce the image size down to the bare minimum:

Here’s what it does:

  • Attaches the Linux partition in the image as a loopback device
  • Runs and fsck to check for consistency
  • Resizes the filesystem to the minimum possible
  • Disconnects the loopback device
  • Repartitions the image so the Linux partition is just larger than the newly resized filesystem within it
  • Truncates the image file to just after the end of the newly resized partition

The image is assumed to contain a FAT boot partition and an EXT partition only, in that order. I’m not sure how that plays with Noobs, I haven’t tested it.

It works well for me, bringing my 16GB images down to a little over 2.5GB, which can be reduced further still by gzipping or otherwize compressing the image file.

I hope you find it useful too.

Luke.