Documentation Center

  • Trial Software
  • Product Updates

Exporting to Images

To export data from the MATLAB® workspace using one of the standard graphics file formats, use the imwrite function. Using this function, you can export data in formats such as the Tagged Image File Format (TIFF), Joint Photographic Experts Group (JPEG), and Portable Network Graphics (PNG). For a complete list of supported formats, see the imwrite reference page.

The following example writes a multidimensional array of uint8 data I from the MATLAB workspace into a file in TIFF format. The class of the output image written to the file depends on the format specified. For most formats, if the input array is of class uint8, imwrite outputs the data as 8-bit values. See the imwrite reference page for details.

whos I
  Name      Size                           Bytes  Class

  I       650x600x3                      1170000  uint8 array

Grand total is 1170000 elements using 1170000 bytes
imwrite(I, 'my_graphics_file.tif','tif');

    Note   imwrite supports different syntaxes for several of the standard formats. For example, with TIFF file format, you can specify the type of compression MATLAB uses to store the image. See the imwrite reference page for details.

For more control writing data to a TIFF file, use the Tiff object—see Exporting Image Data and Metadata to TIFF Files for more information.

Exporting Image Data and Metadata to TIFF Files

While you can use imwrite to export image data and metadata (tags) to Tagged Image File Format (TIFF) files, the function does have some limitations. For example, when you want to modify image data or metadata in the file, you must write the all the data to the file. You cannot write only the updated portion. Using the Tiff object, you can write portions of the image data and modify or add individual tags to a TIFF file. When you construct a Tiff object, it represents your connection with a TIFF file and provides access to many of the routines in the LibTIFF library.

The following sections provide step-by-step examples of using Tiff object methods and properties to perform some common tasks with TIFF files. To get the most out of the Tiff object, you must be familiar with the TIFF specification and technical notes. View this documentation at LibTIFF - TIFF Library and Utilities

Creating a New TIFF File

  1. Create some image data. This example reads image data from a JPEG file included with MATLAB:

    imgdata = imread('ngc6543a.jpg');
  2. Create a new TIFF file by constructing a Tiff object, specifying the name of the new file as an argument. To create a file you must specify either write mode ('w') or append mode ('a'):

    t = Tiff('myfile.tif','w');

    When you create a new TIFF file, the Tiff constructor creates a file containing an image file directory (IFD). A TIFF file uses this IFD to organize all the data and metadata associated with a particular image. A TIFF file can contain multiple IFDs. The Tiff object makes the IFD it creates the current IFD. Tiff object methods operate on the current IFD. You can navigate among IFDs in a TIFF file and specify which IFD is the current IFD using Tiff object methods.

  3. Set required TIFF tags using the setTag method of the Tiff object. These required tags specify information about the image, such as its length and width. To break the image data into strips, specify a value for the RowsPerStrip tag. To break the image data into tiles, specify values for the TileWidth and TileLength tags. The example creates a structure that contains tag names and values and passes that to setTag. You also can set each tag individually.

    tagstruct.ImageLength = size(imgdata,1)
    tagstruct.ImageWidth = size(imgdata,2)
    tagstruct.Photometric = Tiff.Photometric.RGB
    tagstruct.BitsPerSample = 8
    tagstruct.SamplesPerPixel = 3
    tagstruct.RowsPerStrip = 16
    tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky
    tagstruct.Software = 'MATLAB'
    t.setTag(tagstruct)

    For information about supported TIFF tags and how to set their values, see Setting Tag Values. For example, the Tiff object supports properties that you can use to set the values of certain properties. This example uses the Tiff object PlanarConfiguration property to specify the correct value for the chunky configuration: Tiff.PlanarConfiguration.Chunky.

  4. Write the image data and metadata to the current directory using the write method of the Tiff object.

    t.write(imgdata);
    

    If you wanted to put multiple images into your file, call the writeDirectory method right after performing this write operation. The writeDirectory method sets up a new image file directory in the file and makes this new directory the current directory.

  5. Close your connection to the file by closing the Tiff object:

    t.close();
    
  6. Test that you created a valid TIFF file by using the imread function to read the file, and then display the image:

    imagesc(imread('myfile.tif'));

Writing a Strip or Tile of Image Data

    Note:   You can only modify a strip or a tile of image data if the data is not compressed.

  1. Open an existing TIFF file for modification by creating a Tiff object. This example uses the file created in Creating a New TIFF File. The Tiff constructor returns a handle to a Tiff object.

    t = Tiff('myfile.tif','r+');
  2. Generate some data to write to a strip in the image. This example creates a three-dimensional array of zeros that is the size of a strip. The code uses the number of rows in a strip, the width of the image, and the number of samples per pixel as dimensions. The array is an array of uint8 values.

    width = t.getTag('ImageWidth');
    height = t.getTag('RowsPerStrip');
    numSamples = t.getTag('SamplesPerPixel');
    stripData = zeros(height,width,numSamples,'uint8');
    

    If the image data had a tiled layout, you would use the TileWidth and TileLength tags to specify the dimensions.

  3. Write the data to a strip in the file using the writeEncodedStrip method. Specify the index number that identifies the strip you want to modify. The example picks strip 18 because it is easier to see the change in the image.

    t.writeEncodedStrip(18, stripData);
    

    If the image had a tiled layout, you would use the writeEncodedTile method to modify the tile.

  4. Close your connection to the file by closing the Tiff object.

    t.close();
    
  5. Test that you modified a strip of the image in the TIFF file by using the imread function to read the file, and then display the image.

    modified_imgdata = imread('myfile.tif');
    imagesc(modified_imgdata)

    Note the black strip across the middle of the image.

Modifying TIFF File Metadata (Tags)

  1. Open an existing TIFF file for modification using the Tiff object. This example uses the file created in Creating a New TIFF File. The Tiff constructor returns a handle to a Tiff object.

    t = Tiff('myfile.tif','r+');
  2. Verify that the file does not contain the Artist tag, using the getTag method. This code should issue an error message saying that it was unable to retrieve the tag.

    artist_value = t.getTag('Artist');
  3. Add the Artist tag using the setTag method.

    t.setTag('Artist','Pablo Picasso');
  4. Write the new tag data to the TIFF file using the rewriteDirectory method. Use the rewriteDirectory method when modifying existing metadata in a file or adding new metadata to a file.

    t.rewriteDirectory();
  5. Close your connection to the file by closing the Tiff object.

    t.close();
    
  6. Test your work by reopening the TIFF file and getting the value of the Artist tag, using the getTag method.

    t = Tiff('myfile.tif', 'r');
    
    t.getTag('Artist')
    
    ans =
    
    Pablo Picasso
    
    t.close();

Creating Subdirectories in a TIFF File

  1. Create some image data. This example reads image data from a JPEG file included with MATLAB. The example then creates two reduced-resolution (thumbnail) versions of the image data.

    imgdata = imread('ngc6543a.jpg');
    %
    % Reduce number of pixels by a half.
    img_half = imgdata(1:2:end,1:2:end,:);
    %
    % Reduce number of pixels by a third.
    img_third = imgdata(1:3:end,1:3:end,:);
  2. Create a new TIFF file by constructing a Tiff object and specifying the name of the new file as an argument. To create a file you must specify either write mode ('w') or append mode ('a'). The Tiff constructor returns a handle to a Tiff object.

    t = Tiff('my_subimage_file.tif','w');
  3. Set required TIFF tags using the setTag method of the Tiff object. These required tags specify information about the image, such as its length and width. To break the image data into strips, specify a value for the RowsPerStrip tag. To break the image data into tiles, use the TileWidth and TileLength tags. The example creates a structure that contains tag names and values and passes that to setTag. You can also set each tag individually.

    To create subdirectories, you must set the SubIFD tag, specifying the number of subdirectories you want to create. Note that the number you specify isn't the value of the SubIFD tag. The number tells the Tiff software to create a SubIFD that points to two subdirectories. The actual value of the SubIFD tag will be the byte offsets of the two subdirectories.

    tagstruct.ImageLength = size(imgdata,1)
    tagstruct.ImageWidth = size(imgdata,2)
    tagstruct.Photometric = Tiff.Photometric.RGB
    tagstruct.BitsPerSample = 8
    tagstruct.SamplesPerPixel = 3
    tagstruct.RowsPerStrip = 16
    tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky
    tagstruct.Software = 'MATLAB'
    tagstruct.SubIFD = 2  % required to create subdirectories
    t.setTag(tagstruct)

    For information about supported TIFF tags and how to set their values, see Setting Tag Values. For example, the Tiff object supports properties that you can use to set the values of certain properties. This example uses the Tiff object PlanarConfiguration property to specify the correct value for the chunky configuration: Tiff.PlanarConfiguration.Chunky.

  4. Write the image data and metadata to the current directory using the write method of the Tiff object.

    t.write(imgdata);
    
  5. Set up the first subdirectory by calling the writeDirectory method. The writeDirectory method sets up the subdirectory and make the new directory the current directory. Because you specified that you wanted to create two subdirectories, writeDirectory sets up a subdirectory.

    t.writeDirectory();
    
  6. Set required tags, just as you did for the regular directory. According to the LibTIFF API, a subdirectory cannot contain a SubIFD tag.

    tagstruct2.ImageLength = size(img_half,1)
    tagstruct2.ImageWidth = size(img_half,2)
    tagstruct2.Photometric = Tiff.Photometric.RGB
    tagstruct2.BitsPerSample = 8
    tagstruct2.SamplesPerPixel = 3
    tagstruct2.RowsPerStrip = 16
    tagstruct2.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky
    tagstruct2.Software = 'MATLAB'
    t.setTag(tagstruct2)
  7. Write the image data and metadata to the subdirectory using the write method of the Tiff object.

    t.write(img_half);
    
  8. Set up the second subdirectory by calling the writeDirectory method. The writeDirectory method sets up the subdirectory and makes it the current directory.

    t.writeDirectory();
    
  9. Set required tags, just as you would for any directory. According to the LibTIFF API, a subdirectory cannot contain a SubIFD tag.

    tagstruct3.ImageLength = size(img_third,1)
    tagstruct3.ImageWidth = size(img_third,2)
    tagstruct3.Photometric = Tiff.Photometric.RGB
    tagstruct3.BitsPerSample = 8
    tagstruct3.SamplesPerPixel = 3
    tagstruct3.RowsPerStrip = 16
    tagstruct3.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky
    tagstruct3.Software = 'MATLAB'
    t.setTag(tagstruct3)
  10. Write the image data and metadata to the subdirectory using the write method of the Tiff object:

    t.write(img_third);
    
  11. Close your connection to the file by closing the Tiff object:

    t.close();
    

Setting Tag Values

The following table lists all the TIFF tags that the Tiff object supports and includes information about their MATLAB class and size. For certain tags, the table also indicates the set of values that the Tiff object supports, which is a subset of all the possible values defined by the TIFF specification. You can use Tiff object properties to specify the supported values for these tags. For example, use Tiff.Compression.JPEG to specify JPEG compression. See the Tiff class reference page for a full list of properties.

Table 1: Supported TIFF Tags

TIFF TagClassSizeSupported ValuesNotes
Artistchar1xN  
BitsPerSampledouble1x11,8,16,32,64See Table 2
ColorMapdouble256x3Values should be normalized between 0–1. Stored internally as uint16 values.Photometric must be Palette
Compressiondouble1x1None: 1
CCITTRLE: 2
CCITTFax3: 3
CCITTFax4: 4
LZW: 5
JPEG: 7
CCITTRLEW: 32771
PackBits: 32773
Deflate: 32946
AdobeDeflate: 8
See Table 3.
Copyrightchar 1xN  
DateTimechar1x19Return value is padded to 19 chars if required. 
DocumentNamechar1xN  
DotRangedouble1x2 Photometric must be Separated
ExtraSamplesdouble1xNUnspecified: 0
AssociatedAlpha: 1
UnassociatedAlpha: 2
See Table 4.
FillOrderdouble1x1  
GeoAsciiParamsTagchar1xN  
GeoDoubleParamsTagdouble1xN  
GeoKeyDirectoryTagdoubleNx4  
Group3Optionsdouble1x1 Compression must be CCITTFax3
Group4Optionsdouble1x1 Compression must be CCITTFax4
HalfToneHintsdouble1x2  
HostComputerchar1xn  
ICCProfileuint81xn  
ImageDescriptionchar1xn  
ImageLengthdouble1x1  
ImageWidthdouble1x1  
InkNameschar cell array1x
NumInks
 Photometric must be Separated
InkSetdouble 1x1CMYK: 1
MultiInk: 2
Photometric must be Separated
JPEGQualitydouble1x1A value between 1 and 100 
Makechar 1xn  
MaxSampleValuedouble1x10–65,535 
MinSampleValuedouble1x10–65,535 
Modelchar1xN  
ModelPixelScaleTagdouble1x3  
ModelTiepointTagdoubleNx6  
ModelTransformationMatrixTagdouble1x16  
NumberOfInksdouble1x1 Must be equal to SamplesPerPixel
Orientationdouble1x1TopLeft: 1
TopRight: 2
BottomRight: 3
BottomLeft: 4
LeftTop: 5
RightTop: 6
RightBottom: 7
LeftBottom: 8
 
PageNamechar1xN  
PageNumberdouble1x2  
Photometricdouble1x1MinIsWhite: 0
MinIsBlack: 1
RGB: 2
Palette: 3
Mask: 4
Separated: 5
YCbCr: 6
CIELab: 8
ICCLab: 9
ITULab: 10
See Table 2.
Photoshopuint8 1xN  
PlanarConfigurationdouble1x1Chunky: 1
Separate: 2
 
PrimaryChromaticitiesdouble1x6  
ReferenceBlackWhitedouble1x6  
ResolutionUnitdouble 1x1  
RICHTIFFIPTCuint81xN  
RowsPerStripdouble1x1  
SampleFormatdouble1x1Uint: 1
Int: 2
IEEEFP: 3
See Table 2
SamplesPerPixeldouble1x1  
SMaxSampleValuedouble1x1Range of MATLAB data type specified for Image data  
SMinSampleValuedouble1x1Range of MATLAB data type specified for Image data  
Softwarechar1xN  
StripByteCountsdouble1xN Read-only
StripOffsetsdouble1xN Read-only
SubFileTypedouble1x1Default : 0
ReducedImage: 1
Page: 2
Mask: 4
 
SubIFDdouble1x1  
TargetPrinterchar1xN  
Thresholdingdouble1x1BiLevel: 1
HalfTone: 2
ErrorDiffuse: 3

Photometric can be either: MinIsWhite MinIsBlack

TileByteCountsdouble1xN Read-only
TileLengthdouble1x1Must be a multiple of 16 
TileOffsetsdouble1xN Read-only
TileWidthdouble1x1Must be a multiple of 16 
TransferFunctiondoubleSee note1Each value should be within 0–2^16-1SamplePerPixel can be either 1 or 3
WhitePointdouble1x2 Photometric can be: RGB
Palette
YCbCr
CIELab
ICCLab
ITULab
XMPchar1xn N>5
XPostiondouble1x1  
XResolutiondouble1x1  
YCbCrCoefficentsdouble1x3 Photometric must be YCbCr
YCbCrPositioningdouble1x1Centered: 1
Cosited: 2
Photometric must be YCbCr
YCbCrSubSamplingdouble1x2 Photometric must be YCbCr
YPositiondouble1x1  
YResolutiondouble1x1  
ZipQualitydouble1x1Value between 1 and 9 

1Size is 1x2^BitsPerSample or3x2^BitsPerSample.

Table 2: Valid SampleFormat Values for BitsPerSample Settings

BitsPerSampleSampleFormatMATLAB Data Type
1Uintlogical
8Uint, Intuint8, int8
16Uint, Intuint16, int16
32Uint, Int, IEEEFPuint32, int32, single
64IEEEFPdouble

Table 3: Valid SampleFormat Values for BitsPerSample and Photometric Combinations

 BitsPerSample Values
Photometric Values18163264
MinIsWhiteUintUint/IntUint
Int
Uint
Int
IEEEFP
IEEEFP
MinIsBlackUintUint/IntUint
Int
Uint
Int
IEEEFP
IEEEFP
RGB UintUintUint
IEEEFP
IEEEFP
Pallette UintUint  
MaskUint    
Separated UintUintUint
IEEEFP
IEEEFP
YCbCr UintUintUint
IEEEFP
IEEEFP
CIELab UintUint  
ICCLab UintUint  
ITULab UintUint  

Table 4: Valid SampleFormat Values for BitsPerSample and Compression Combinations

 BitsPerSample Values
Compression Values18163264
NoneUintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
CCITTRLEUint    
CCITTFax3Uint    
CCITTFax4Uint    
LZWUintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
JPEG Uint
Int
   
CCITTRLEWUint    
PackBitsUintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
DeflateUintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
AdobeDeflateUintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP

Table 5: Valid SamplesPerPixel Values for Photometric Settings

Photometric ValuesSamplesPerPixel1
MinIsWhite1+
MinIsBlack1+
RGB3+
Pallette1
Mask1
Separated1+
YCbCr3
CIELab3+
ICCLab3+
ITULab3+

1 When you specify more than the expected number of samples per pixel (n+), you must set the ExtraSamples tag accordingly.

Was this topic helpful?