import io


def pil2memfile(img_pil, format='jpeg'):
    """
    Write the image into a buffer kept in RAM.
    Format can be 'jpeg' or 'png'.
    """
    memfile = io.BytesIO()
    memfile.name = f'image.{format}'
    img_pil.save(memfile, format)
    memfile.seek(0)
    return memfile