I recently needed to crop a gif to a square and found this command-line tool for working with gifs called gifsicle.

Here’s a simple step-by-step guide to using it.

1. Install gifsicle.

On a Mac, you can install gifsicle using Home-brew with the following command:

brew install gifsicle

2. Determine the final size of your gif.

Here’s a gif of the legendary Jurgen Klopp. It’s 480x270. I want my final gif to be a 1:1 square, so 270x270 is my target size.

Klopp Laughing

3. Crop the image.

Open Terminal and cd to the directory where your image is found.

Next, let’s crop the image. According to the documentation, we need to provide four things.

  1. The name gifsicle to call the tool.
  2. The crop option (tell it the size, positioning, etc. of the crop) .
  3. An input file.
  4. An output file.

Numbers 1, 3, and 4 are self-explanatorry, so let’s focus on #2. The crop option takes four parameters: x1, y1 + width x height. The first two tell it where to start the crop from. 0,0 will start the crop from the top right-hand corner (i.e., x1 = 0 and y1 = 0). We’ll center the image in a later step. For now, let’s just work on getting it to crop the image. Next, we provide the cropped dimension: 270x270 as our width and height respectively.

In all, here’s the command.

gifsicle --crop 0,0+270x270 resize-gif.gif > resize-gif-cropped.gif

The greater than sign tells it to take the original file (i.e., “resize-gif.gif”) and save the cropped version as “resize-gif-cropped.gif” in the same directory.

Here’s the output:

Klopp Laughing

Almost right…but it’s offset to the top right-hand corner, so we’re not getting the middle of the gif cropped to a 1:1 square.

3. Determine the offset.

To keep that crop in the center, then, I’ll need 105px offset. You can find that with this simple formula: ((total longest side) - (total desired length)) / 2

In my example, that’s (480px - 270px)/2 = 105px. Here’s a visual if it helps.

Crop lines for 1:1 gif crop

4. Crop the final image.

We can apply that to our command line input above, adding a 105px offset in the x1 parameter of the crop option. Leaving us with the following:

gifsicle --crop 105,0+270x270 resize-gif.gif > resize-gif-cropped.gif

Here’s the result.

Klopp Laughing

5. Optional additions.

It’s important to note that according to the documentation, “Cropping takes place before any rotation, flipping, resizing, or positioning.” That means if you want to do anything else (like resize, flip, etc.), realize that cropping takes place first. For me, this means I put it first in the command so I don’t forget the order.

Here’s an example. If you want to both resize and crop the image, the crop is done first.

As an example… gifsicle --crop 105,0+270x270 --resize 100x100 resize-gif.gif > resize-gif-cropped-resized.gif

Klopp Laughing