Using hdiutil to resize disk images

I’ve been working on a small project that requires sparse disk images to be resized on the fly, although it ended being a great deal more difficult than I’d had originally hoped.

Originally I was creating disk images using the following code: hdiutil create -size 100m -fs HFS+ -type SPARSE myImage Which worked fine, I’d end up with a fully functional sparse image. However, when I went to resize the image using: hdiutil resize -size 200m myImage.sparseimage I would receive the following error: hdiutil: resize failed - error -5341 Which was quite vague, and doesn’t at all help the debug process (especially since there really hasn’t been much talk of such things online).

After a few hours of tinkering around I was able to work out how to create a disk image using hdiutil and later resize it.

It seems to revolve entirely around the partition type.
After creating a few images using Disk Utility and inspecting their innards using the hdiutil imageinfo command I realised that the layout of the image determined how ‘resizable’ it is.

So, getting to the point, this is how you create a disk image and resize it using hdiutil: # create a 100mb sparse disk image called myImage hdiutil create -fs HFS+ -layout NONE -type SPARSE -size 100m myImage The most important aspect of this command is the -layout NONE argument, it’s what tells hdiutil to only create one single partition on the new image, the default is GUID (or so it seems), which creates a few different partitions which; for some reason; can’t be resized.

I’m not the most savvy person in this field, so maybe someone with a greater understanding of such things could explain the reasons in greater detail

Now for the resize, this is all pretty easy, and runs just as it should: # resize the image to 200mb hdiutil resize -size 200m myImage.sparseimage

I haven’t tinkered on the topic any further (since my requirements are now fulfilled), but I imagine there’s other layout types which will allow resizing, if you work them out, be sure to let me know.

Enjoy.