save_untouch_header_only.m 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. % This function is only used to save Analyze or NIfTI header that is
  2. % ended with .hdr and loaded by load_untouch_header_only.m. If you
  3. % have NIfTI file that is ended with .nii and you want to change its
  4. % header only, you can use load_untouch_nii / save_untouch_nii pair.
  5. %
  6. % Usage: save_untouch_header_only(hdr, new_header_file_name)
  7. %
  8. % hdr - struct with NIfTI / Analyze header fields, which is obtained from:
  9. % hdr = load_untouch_header_only(original_header_file_name)
  10. %
  11. % new_header_file_name - NIfTI / Analyze header name ended with .hdr.
  12. % You can either copy original.img(.gz) to new.img(.gz) manually,
  13. % or simply input original.hdr(.gz) in save_untouch_header_only.m
  14. % to overwrite the original header.
  15. %
  16. % - Jimmy Shen (jshen@research.baycrest.org)
  17. %
  18. function save_untouch_header_only(hdr, filename)
  19. if ~exist('hdr','var') | isempty(hdr) | ~exist('filename','var') | isempty(filename)
  20. error('Usage: save_untouch_header_only(hdr, filename)');
  21. end
  22. v = version;
  23. % Check file extension. If .gz, unpack it into temp folder
  24. %
  25. if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
  26. if ~strcmp(filename(end-6:end), '.hdr.gz')
  27. error('Please check filename.');
  28. end
  29. if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
  30. error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
  31. else
  32. gzFile = 1;
  33. filename = filename(1:end-3);
  34. end
  35. end
  36. [p,f] = fileparts(filename);
  37. fileprefix = fullfile(p, f);
  38. write_hdr(hdr, fileprefix);
  39. % gzip output file if requested
  40. %
  41. if exist('gzFile', 'var')
  42. gzip([fileprefix, '.hdr']);
  43. delete([fileprefix, '.hdr']);
  44. end;
  45. return % save_untouch_header_only
  46. %-----------------------------------------------------------------------------------
  47. function write_hdr(hdr, fileprefix)
  48. fid = fopen(sprintf('%s.hdr',fileprefix),'w');
  49. if isfield(hdr.hist,'magic')
  50. save_untouch_nii_hdr(hdr, fid);
  51. else
  52. save_untouch0_nii_hdr(hdr, fid);
  53. end
  54. fclose(fid);
  55. return % write_hdr