Main Content

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 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.

For example, write a multidimensional array of uint8 data I from the MATLAB workspace to 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, then imwrite outputs the data as 8-bit values. See the imwrite reference page for details.

I = imread("ngc6543a.jpg");
whos I
  Name        Size                 Bytes  Class    Attributes

  I         650x600x3            1170000  uint8              
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. For more information, see Export Image Data and Metadata to TIFF Files.

Export 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 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.

These examples provide step-by-step demonstrations of how to use 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.

Create TIFF File

Create some image data.

imgdata = imread("ngc6543a.jpg");

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.

Set TIFF tags using the setTag method of the Tiff object. These tags include required tags and optional tags, and 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. This 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.Software = "MATLAB";
tagstruct % display tagstruct
tagstruct = struct with fields:
        ImageLength: 650
         ImageWidth: 600
        Photometric: 2
      BitsPerSample: 8
    SamplesPerPixel: 3
       RowsPerStrip: 16
           Software: "MATLAB"

setTag(t,tagstruct)

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

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

write(t,imgdata)

If you wanted to put multiple images into your file, you would 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.

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

close(t)

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"))

Write 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.

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

t = Tiff("myfile.tif","r+");

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 = getTag(t,"ImageWidth");
height = getTag(t,"RowsPerStrip");
numSamples = getTag(t,"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.

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.

writeEncodedStrip(t,18,stripData)

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

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

close(t)

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.

Modify TIFF File Metadata (Tags)

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

t = Tiff("myfile.tif","r+");

The file currently does not contain the Artist tag. If you run getTag(t,"Artist"), you will see an error. Add the Artist tag using the setTag method.

setTag(t,"Artist","Pablo Picasso")

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.

rewriteDirectory(t)

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

close(t)

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");
getTag(t,"Artist")
ans = 
'Pablo Picasso'
close(t)

Create TIFF Subdirectories

This example reads image data from a JPEG file and then creates two reduced-resolution (thumbnail) versions of the image data.

Create some image data.

imgdata = imread("ngc6543a.jpg");
%
% Reduce number of pixels by one half.
img_half = imgdata(1:2:end,1:2:end,:);
%
% Reduce number of pixels by two thirds.
img_third = imgdata(1:3:end,1:3:end,:);

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"). The Tiff constructor returns a handle to a Tiff object.

t = Tiff("my_subimage_file.tif","w");

Set TIFF tags using the setTag method of the Tiff object. These tags include required tags and optional tags, and 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. This example creates a structure that contains tag names and values and passes that to setTag. You also can 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 is not 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.Software = "MATLAB";
tagstruct.SubIFD = 2; % required to create subdirectories
tagstruct % display tagstruct
tagstruct = struct with fields:
        ImageLength: 650
         ImageWidth: 600
        Photometric: 2
      BitsPerSample: 8
    SamplesPerPixel: 3
       RowsPerStrip: 16
           Software: "MATLAB"
             SubIFD: 2

setTag(t,tagstruct)

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

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

write(t,imgdata)

Set up the first subdirectory by calling the writeDirectory method. The writeDirectory method sets up the subdirectory and makes the new directory the current directory. Because you specified that you wanted to create two subdirectories, writeDirectory sets up a subdirectory.

writeDirectory(t)

Set 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.Software = "MATLAB";
tagstruct2 % display tagstruct2
tagstruct2 = struct with fields:
        ImageLength: 325
         ImageWidth: 300
        Photometric: 2
      BitsPerSample: 8
    SamplesPerPixel: 3
       RowsPerStrip: 16
           Software: "MATLAB"

setTag(t,tagstruct2)

Write the image data and metadata to the subdirectory using the write method of the Tiff object.

write(t,img_half)

Set up the second subdirectory by calling the writeDirectory method. The writeDirectory method sets up the subdirectory and makes it the current directory.

writeDirectory(t)

Set tags, just as you would for any directory.

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.Software = "MATLAB";
tagstruct3 % display tagstruct3
tagstruct3 = struct with fields:
        ImageLength: 217
         ImageWidth: 200
        Photometric: 2
      BitsPerSample: 8
    SamplesPerPixel: 3
       RowsPerStrip: 16
           Software: "MATLAB"

setTag(t,tagstruct3)

Write the image data and metadata to the subdirectory using the write method of the Tiff object.

write(t,img_third)

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

close(t)

Set Tag Values

This 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 the Tiff properties structure to specify the supported values for these tags. For example, use Tiff.Compression.JPEG to specify JPEG compression. See the Tiff reference page for a full list of properties.

Table 1: Supported TIFF Tags

TIFF TagClassSizeSupported ValuesNotes
Artistchar1-by-N
BitsPerSampledouble1-by-11, 8, 16, 32, 64See table 2 and table 3.
ColorMapdouble256-by-3Values should be normalized in the interval [0, 1]. Stored internally as uint16 values.Photometric must be Palette.
Compressiondouble1-by-1None: 1
CCITTRLE: 2
CCITTFax3: 3
CCITTFax4: 4
LZW: 5
JPEG: 7
CCITTRLEW: 32771
PackBits: 32773
Deflate: 32946
AdobeDeflate: 8
See table 4.
Copyrightchar 1-by-N
DateTimechar1-by-19Return value is padded to 19 characters if required.
DocumentNamechar1-by-N
DotRangedouble1-by-2Photometric must be Separated.
ExtraSamplesdouble1-by-NUnspecified: 0
AssociatedAlpha: 1
UnassociatedAlpha: 2
FillOrderdouble1-by-1
GeoAsciiParamsTagchar1-by-N
GeoDoubleParamsTagdouble1-by-N
GeoKeyDirectoryTagdoubleN-by-4
Group3Optionsdouble1-by-1Compression must be CCITTFax3.
Group4Optionsdouble1-by-1Compression must be CCITTFax4.
HalfToneHintsdouble1-by-2
HostComputerchar1-by-N
ICCProfileuint81-by-N
ImageDescriptionchar1-by-N
ImageLengthdouble1-by-1
ImageWidthdouble1-by-1
InkNameschar cell array1-by-NumInksPhotometric must be Separated.
InkSetdouble 1-by-1CMYK: 1
MultiInk: 2
Photometric must be Separated.
JPEGQualitydouble1-by-1A value in the interval [1, 100]
Makechar 1-by-N
MaxSampleValuedouble1-by-1A value in the interval [0, 216-1]
MinSampleValuedouble1-by-1A value in the interval [0, 216-1]
Modelchar1-by-N
ModelPixelScaleTagdouble1-by-3
ModelTiepointTagdoubleN-by-6
ModelTransformationMatrixTagdouble1-by-16
NumberOfInksdouble1-by-1NumberOfInks must be equal to SamplesPerPixel.
Orientationdouble1-by-1TopLeft: 1
TopRight: 2
BottomRight: 3
BottomLeft: 4
LeftTop: 5
RightTop: 6
RightBottom: 7
LeftBottom: 8
PageNamechar1-by-N
PageNumberdouble1-by-2
Photometricdouble1-by-1MinIsWhite: 0
MinIsBlack: 1
RGB: 2
Palette: 3
Mask: 4
Separated: 5
YCbCr: 6
CIELab: 8
ICCLab: 9
ITULab: 10
See table 3.
Photoshopuint8 1-by-N
PlanarConfigurationdouble1-by-1Chunky: 1
Separate: 2
PrimaryChromaticitiesdouble1-by-6
ReferenceBlackWhitedouble1-by-6
ResolutionUnitdouble 1-by-1
RICHTIFFIPTCuint81-by-N
RowsPerStripdouble1-by-1
RPCCoefficientTagdouble1-by-92See table 6.
SampleFormatdouble1-by-1Uint: 1
Int: 2
IEEEFP: 3
See table 2.
SamplesPerPixeldouble1-by-1
SMaxSampleValuedouble1-by-1Range of MATLAB data type specified for image data
SMinSampleValuedouble1-by-1Range of MATLAB data type specified for image data
Softwarechar1-by-N
StripByteCountsdouble1-by-NRead-only
StripOffsetsdouble1-by-NRead-only
SubFileTypedouble1-by-1Default : 0
ReducedImage: 1
Page: 2
Mask: 4
SubIFDdouble1-by-1
TargetPrinterchar1-by-N
Thresholdingdouble1-by-1BiLevel: 1
HalfTone: 2
ErrorDiffuse: 3
Photometric must be either MinIsWhite or MinIsBlack.
TileByteCountsdouble1-by-NRead-only
TileLengthdouble1-by-1Must be a multiple of 16
TileOffsetsdouble1-by-NRead-only
TileWidthdouble1-by-1Must be a multiple of 16
TransferFunctiondoubleSee note1Must be in the interval [0, 216-1]SamplesPerPixel must be either 1 or 3.
WhitePointdouble1-by-2Photometric must be RGB, Palette, YCbCr, CIELab, ICCLab, or ITULab.
XMPchar1-by-NN > 5
XPostiondouble1-by-1
XResolutiondouble1-by-1
YCbCrCoefficientsdouble1-by-3Photometric must be YCbCr.
YCbCrPositioningdouble1-by-1Centered: 1
Cosited: 2
Photometric must be YCbCr.
YCbCrSubSamplingdouble1-by-2Photometric must be YCbCr.
YPositiondouble1-by-1
YResolutiondouble1-by-1
ZipQualitydouble1-by-1Must be in the interval [0, 9]

1 Size is 1-by-2BitsPerSample or 3-by-2BitsPerSample.

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

Photometric ValuesBitsPerSample Values
18163264
MinIsWhite UintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
MinIsBlack UintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
RGB UintUintUint
IEEEFP
IEEEFP
PaletteUintUint
Mask Uint
Separated UintUintUint
IEEEFP
IEEEFP
YCbCr UintUintUint
IEEEFP
IEEEFP
CIELab UintUint
ICCLab UintUint
ITULab UintUint

Table 4: Valid SampleFormat Values for BitsPerSample and Compression Combinations

Compression ValuesBitsPerSample Values
18163264
NoneUintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
CCITTRLEUint
CCITTFax3Uint
CCITTFax4Uint
LZWUintUint
Int
Uint
Int
Uint
Int
IEEEFP
IEEEFP
JPEGUint
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 ValuesSamplesPerPixel
MinIsWhite 1+
MinIsBlack 1+
RGB 3+
Palette1
Mask 1
Separated 1+
YCbCr 3
CIELab 3+
ICCLab 3+
ITULab 3+

Table 6: List of RPCCoefficientTag Value Descriptions

Index Value in 92-Element VectorValue Descriptions1Units
1Root mean square bias errormeters per horizontal axis
2Root mean square random errormeters per horizontal axis
3Line offsetpixels
4Sample offsetpixels
5Geodetic latitude offsetdegrees
6Geodetic longitude offsetdegrees
7Geodetic height offsetmeters
8Line scale factorpixels
9Sample scale factorpixels
10Geodetic latitude scaledegrees
11Geodetic longitude scaledegrees
12Geodetic height scale factormeters
13 through 32Numerator coefficients of r(n), a rational polynomial expression2
33 through 52Denominator coefficients of the rational polynomial expression r(n)
53 through 72Numerator coefficients of c(n), a rational polynomial expression2
73 through 92Denominator coefficients of the rational polynomial expression c(n)

1To specify the values in this vector using the RPCCoefficientTag object, see RPCCoefficientTag (Mapping Toolbox) in Mapping Toolbox™.

2Polynomials r(n) and c(n) represent the normalized row and column values of a generic rigorous projection model.

See Also

Related Topics