How to convert a non-sparse image to a sparse image

Below are the steps how to convert a raw or qcow2 non-sparse image to a sparse image. Basically there are two ways to do the conversion:
1) use virt-sparsify
2) use dd and cp --sparse

Convert a non-sparse image to a sparse image with virt-sparsify

IMPORTANT: make sure the VM is not running/live! It must be shut down or else you will destroy the data in your image.

Make sure virt-sparsify is installed:

Check current image:

The first 10737418240 value is the allocated size and the second 10737418240 value is the file size. Since they are both the same value it means that this image is non-sparse (or 100% full in which case the sparse attempt is irrelevant).

Check again using qemu-img info:

Both the virtual size and the disk size are 10G so this image is not a sparse image.

Now convert the non-sparse image to a sparse image using virt-sparsify:

Check the new image:

The allocated size of 1425852 is much smaller than the file size of 10737418240 which means this is now a sparse image.

Check again using qemu-img info:

The disk size is much smaller than the virtual disk size so the image has indeed been successfully converted to a sparse image.

Convert a non-sparse image to a sparse image with dd and cp

Start the VM/image which you want to make sparse and login to it. Next fill the free space in the VM with zeros using the following command and then shut it down again:

Now convert the non-sparse image to a sparse image using cp:

Check the new image:

The allocated size of 1425852 is much smaller than the file/image size of 10737418240 which means this is now a sparse image.

Check again using qemu-img info:

Again this shows that the image is now a sparse image.

Which method to use?

Both methods work equally well. In terms of options the virt-sparsify method may be preferred as it can for example also convert the image from raw to qcow2 and it needs less steps. See man virt-sparsify for more information. If you just want to make the image sparse than choose the method which you like best.

Tip

If you use rsync to make backups of your images then do not forget to use the --sparse option and realize that --sparse conflicts with --inplace (see man rsync).