I have a Raspberry Pi installation on a 32GB SD card but the operating system and files takes up less than 1GB in space. I would like to keep an image of the SD card for potential future use as I did quite a bit of configuration changes and settings.

This is the way it can be done:

1. Check the current partitions

Insert the SD card and run:

lsblk

or

sudo fdisk -l

to see which partition contains the root filesystem (usually /dev/sdX2 for Raspberry Pi OS).


2. Shrink the filesystem

Boot from another system (not the Pi itself) and shrink the filesystem using resize2fs.
For example, if the root partition is /dev/sdX2:

sudo e2fsck -f /dev/sdX2
sudo resize2fs -M /dev/sdX2
  • -M automatically shrinks to the minimum possible size.

  • This only resizes the filesystem, not the partition table yet.


3. Shrink the partition

Now shrink the partition itself to match the new smaller filesystem. You can use:

sudo fdisk /dev/sdX

or a GUI like gparted.
Adjust partition 2 to end exactly where the filesystem ends (fdisk will warn if you try to make it too small).


4. Create the image

Once the filesystem and partition are shrunk, image the whole card:

sudo dd if=/dev/sdX of=pi.img bs=4M status=progress

This will still create a 32 GB file, but only the first few GBs will contain data.


5. Trim the image file

Finally, truncate the .img to the actual used size:

sudo fdisk -l pi.img

Find the last sector used by the last partition, multiply by sector size (usually 512).
Then:

truncate --size=$(( (LAST_SECTOR+1) * 512 )) pi.img

Now the image file is only as big as needed (e.g., ~1 GB instead of 32).


6. (Optional) Compress it

You can also compress the image:

xz -9 pi.img

This usually reduces it even further, since empty space compresses very well.


✅ Result: You’ll end up with a minimal .img that still restores fine to another SD card of the same or larger size.