enviSaveRaw.m 1.93 KB
%saves an ENVI file without any manipulation, assumes (X, Y, S)
function enviSaveRaw(M, filename, headername)

    %if a header isn't provided, assume it's just the filename
        % with '.hdr' added to the end
    if nargin == 2
        headername = [filename '.hdr'];
    end

    %open a file for writing
    fid = fopen(filename, 'w');
    
    %write the data to disk
    fwrite(fid, M, class(M));
    
    %close the file
    fclose(fid);
    
    %open a header file for writing
    fid = fopen(headername, 'w');
    fprintf(fid, 'ENVI\n');
    fprintf(fid, 'description = {}\n');
    fprintf(fid, 'samples = %d\n', size(M, 1));
    fprintf(fid, 'lines = %d\n', size(M, 2));
    fprintf(fid, 'bands = %d\n', size(M, 3));
    fprintf(fid, 'header offset = 0\n');
    fprintf(fid, 'file type = ENVI Standard\n');
    
    %get a string representing the matlab data type
    matlab_real = isreal(M);
    
    if(isa(M, 'uchar'))
        envi_type = 1;
    elseif(isa(M, 'short'))
        envi_type = 2;
    elseif(isa(M, 'int'))
        envi_type = 3;
    elseif(isa(M, 'single') && matlab_real)
        envi_type = 4;
    elseif(isa(M, 'double') && matlab_real)
        envi_type = 5;
    elseif(isa(M, 'single') && ~matlab_real)
        envi_type = 6;
    elseif(isa(M, 'double') && ~matlab_real)
        envi_type = 9;
    elseif(isa(M, 'ushort'))
        envi_type = 12;
    elseif(isa(M, 'ulong'))
        envi_type = 13;
    elseif(isa(M, 'int64'))
        envi_type = 14;
    elseif(isa(M, 'uint64'))
        envi_type = 15;
    end
    
    fprintf(fid, 'data type = %d\n', envi_type);
    
    fprintf(fid, 'interleave = bsq\n');
    fprintf(fid, 'sensor type = Unknown\n');
    fprintf(fid, 'byte order = 0\n');
    fprintf(fid, 'x start = 0\n');
    fprintf(fid, 'y start = 0\n');
    fprintf(fid, 'wavelength units = Unknown\n');
    fprintf(fid, 'z plot titles = {Unknown, Unknown}\n');
    fprintf(fid, 'pixel size = {1, 1, units=Meters}\n');
    fclose(fid);