Skip to content

Commit

Permalink
BUG: Provide itk::Exception for invalid NIFTI write
Browse files Browse the repository at this point in the history
When attempting to write a nifti file to an invalid location (for
example, C:\Windows\something.nii) then no file is created there yet no
error is reported.

The issue is that the error is swallowed in both niftilib and nifti2
(just "reported" with LNI_FERR macro, which does not throw an exception
or reports the error to ITK in any other way):

Resolves: #1958
  • Loading branch information
hjmjohnson committed Aug 8, 2022
1 parent 6a5a715 commit 63590b8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
20 changes: 16 additions & 4 deletions Modules/IO/NIFTI/src/itkNiftiImageIO.cxx
Expand Up @@ -2221,9 +2221,16 @@ NiftiImageIO ::Write(const void * buffer)
// Need a const cast here so that we don't have to copy the memory
// for writing.
this->m_NiftiImage->data = const_cast<void *>(buffer);
nifti_image_write(this->m_NiftiImage);
this->m_NiftiImage->data = nullptr; // if left pointing to data buffer
// nifti_image_free will try and free this memory
const int nifti_write_status = nifti_image_write_status(this->m_NiftiImage);
this->m_NiftiImage->data = nullptr; // Must free before throwing exception.
// if left pointing to data buffer
// nifti_image_free inside Destructor of ITKNiftiIO
// will try and free this memory, and then
// so will destructor of the image that really owns it.
if (nifti_write_status)
{
itkExceptionMacro(<< "ERROR: nifti library failed to write image" << this->GetFileName());
}
}
else /// Image intent is vector image
{
Expand Down Expand Up @@ -2301,8 +2308,13 @@ NiftiImageIO ::Write(const void * buffer)
// Need a const cast here so that we don't have to copy the memory for
// writing.
this->m_NiftiImage->data = static_cast<void *>(nifti_buf);
nifti_image_write(this->m_NiftiImage);
const int nifti_write_status = nifti_image_write_status(this->m_NiftiImage);
this->m_NiftiImage->data = nullptr; // if left pointing to data buffer
if (nifti_write_status)
{
itkExceptionMacro(<< "ERROR: nifti library failed to write image" << this->GetFileName());
}

delete[] nifti_buf;
}
}
Expand Down
10 changes: 8 additions & 2 deletions Modules/IO/NIFTI/test/itkNiftiImageIOTest5.cxx
Expand Up @@ -87,8 +87,14 @@ SlopeInterceptTest()
{
static_cast<PixelType *>(niftiImage->data)[i] = i;
}
nifti_image_write(niftiImage);
nifti_image_free(niftiImage);

const int nifti_write_status = nifti_image_write_status(niftiImage);
nifti_image_free(niftiImage); // Must free before throwing exception.
if (nifti_write_status)
{
itkGenericExceptionMacro(<< "ERROR: nifti library failed to write image" << filename);
}

//
// read the image back in
using ImageType = typename itk::Image<float, 3>;
Expand Down

0 comments on commit 63590b8

Please sign in to comment.