def correct_image_and_call(f, im, *a, **kw):
    """
    Call a function, passing in an image where the canvas size of each frame is
    the same.

    The function will be called as ``f(im, *a, **kw)`` and can return an image
    to post-process or ``None``. Post-processing is currently limited to
    optimizing animated GIFs.

    Parameters:
        f: The function to call.
        im: A sanpera ``Image``.
        *a: Positional arguments with which to call *f*.
        **kw: Keyword arguments with which to call *f*.

    Returns:
        *im*, if *f* returned ``None``, or the ``Image`` returned by *f* after
        post-processing.
    """

    animated = len(im) > 1
    # either of these operations make the image satisfy the contraint
    # `all(im.size == frame.size for frame in im)`
    if animated:
        im = im.coalesced()
    else:
        im = im.cropped(im[0].canvas)
    # returns a new image to post-process or None
    im = f(im, *a, **kw)
    if animated and im is not None:
        im = im.optimized_for_animated_gif()
    return im