Optimize the image if the IMAGE_OPTIMIZATION_CMD is set.

    IMAGE_OPTIMIZATION_CMD must accept piped input

def optimize(image, fmt='jpeg', quality=80):
    """
    Optimize the image if the IMAGE_OPTIMIZATION_CMD is set.

    IMAGE_OPTIMIZATION_CMD must accept piped input
    """
    from io import BytesIO

    if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD):
        image_buffer = BytesIO()
        image.save(image_buffer, format=fmt, quality=quality)
        image_buffer.seek(0)  # If you don't reset the file pointer, the read command returns an empty string
        p1 = subprocess.Popen(IMAGE_OPTIMIZATION_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        output_optim, output_err = p1.communicate(image_buffer.read())
        if not output_optim:
            logger.debug("No image buffer received from IMAGE_OPTIMIZATION_CMD")
            logger.debug("output_err: {0}".format(output_err))
            return image
        im = Image.open(BytesIO(output_optim))
        return im
    else:
        return image