def apply_opacity(im, opacity):
    """ Apply opacity to an image. """
    if opacity == 255:
        return im

    if im.mode == 'RGB':
        im.putalpha(opacity)
        return im
    elif im.mode in ('RGBA', 'LA'):
        alpha_index = len(im.mode) - 1
        a = im.split()[alpha_index]
        opacity_scale = opacity / 255
        a = a.point(lambda i: i * opacity_scale)
        im.putalpha(a)
        return im
    else:
        raise NotImplementedError()