Skip to content

Commit 9eb7ae8

Browse files
author
Ben Cipollini
committed
save conversion logic is not as strong as needed (should really use maybe_is_image). Use some try...catch to safeguard.
1 parent 71e2e1b commit 9eb7ae8

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

nibabel/loadsave.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,10 @@ def save(img, filename):
105105
# Inline imports, as this module really shouldn't reference any image type
106106
from .nifti1 import Nifti1Image, Nifti1Pair
107107
from .nifti2 import Nifti2Image, Nifti2Pair
108+
109+
klass = None
110+
converted = None
111+
108112
if type(img) == Nifti1Image and lext in ('.img', '.hdr'):
109113
klass = Nifti1Pair
110114
elif type(img) == Nifti2Image and lext in ('.img', '.hdr'):
@@ -119,8 +123,23 @@ def save(img, filename):
119123
if not valid_klasses: # if list is empty
120124
raise ImageFileError('Cannot work out file type of "%s"' %
121125
filename)
122-
klass = valid_klasses[0]
123-
converted = klass.from_image(img)
126+
127+
# Got a list of valid extensions, but that's no guarantee
128+
# the file conversion will work. So, try each image
129+
# in order...
130+
for klass in valid_klasses:
131+
try:
132+
converted = klass.from_image(img)
133+
break
134+
except Exception as e:
135+
continue
136+
# ... and if none of them work, raise an error.
137+
if converted is None:
138+
raise e
139+
140+
# Here, we either have a klass or a converted image.
141+
if converted is None:
142+
converted = klass.from_image(img)
124143
converted.to_filename(filename)
125144

126145

0 commit comments

Comments
 (0)