<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def image_write(image, filename, ri=False):
 """ Write an ANTsImage to file ANTsR function: `antsImageWrite` Arguments --------- image : ANTsImage image to save to file filename : string name of file to which image will be saved ri : boolean if True, return image. This allows for using this function in a pipeline: if False, do not return image """

    if filename.endswith('.npy'):
        img_array = image.numpy()
        img_header = {'origin': image.origin,'spacing': image.spacing,
                        'direction': image.direction.tolist(), 'components': image.components}

        np.save(filename, img_array)
        with open(filename.replace('.npy','.json'), 'w') as outfile:
            json.dump(img_header, outfile)
    else:
        image.to_file(filename)

    if ri:
        return image