imwrite - Write image to graphics file - MATLAB (original) (raw)

Main Content

Write image to graphics file

Syntax

Description

imwrite([A](#btv3cny-1-A),[filename](#btv3cny-1-filename)) writes image data A to the file specified by filename, inferring the file format from the extension. imwrite creates the new file in your current folder. The bit depth of the output image depends on the data type ofA and the file format. For most formats:

If A contains indexed image data, you should additionally specify themap input argument.

example

imwrite([A](#btv3cny-1-A),[map](#btv3cny-1-map),[filename](#btv3cny-1-filename)) writes the indexed image in A and its associated colormapmap to the file specified by filename.

example

imwrite(___,[fmt](#btv3cny-1-fmt)) writes the image in the format specified by fmt, regardless of the file extension infilename. You can specify fmt after the input arguments in any of the previous syntaxes.

imwrite(___,[Name,Value](#namevaluepairarguments)) specifies additional parameters for output GIF, HDF, JPEG, PBM, PGM, PNG, PPM, and TIFF files, using one or more name-value arguments. For example, you can add a comment to an image in PNG format.

example

Examples

collapse all

Write Grayscale Image to PNG

Write a 50-by-50 array of grayscale values to a PNG file in the current folder.

A = rand(50); imwrite(A,"myGray.png")

Write Indexed Image Data to PNG

Write an indexed image array and its associated colormap to a PNG file.

Load sample image data from the file earth.mat.

The image array X and its associated colormap map are loaded into the workspace.

Write the data to a new PNG file.

imwrite(X,map,"myearth.png")

imwrite creates the file myearth.png in your current folder.

View the new PNG file using imshow.

Figure contains an axes object. The hidden axes object contains an object of type image.

Write Indexed Image with MATLAB Colormap

Write image data to a new PNG file with the built-in MATLAB® colormap copper.

Load sample image data from the file earth.mat.

The image array X and its associated colormap map are loaded into the workspace. map is a matrix of 64 RGB vectors.

Create a copper-tone colormap with 64 RGB vectors. Then write the image data to a PNG file using the new colormap.

newmap = copper(64); imwrite(X,newmap,"copperearth.png");

imwrite creates the file copperearth.png in your current folder.

View the new PNG file using imshow.

imshow("copperearth.png")

Figure contains an axes object. The hidden axes object contains an object of type image.

Write Truecolor Image to JPEG

Create and write truecolor image data to a JPEG file.

Create a 49-by-49-by-3 array of random RGB values.

Write the image data to a JPEG file. imwrite automatically chooses this format when you use the .jpg file extension. Add a comment to the file using the Comment name-value argument.

imwrite(A,"newImage.jpg","Comment","My JPEG file")

View information about the new file.

info = imfinfo("newImage.jpg"); info.ColorType

[info.Height,info.Width,info.NumberOfSamples,info.BitDepth]

ans = 1x1 cell array {'My JPEG file'}

Write Multiple Images to TIFF File

Write multiple images to a single multipage TIFF file.

Create two sets of random image data, im1 and im2.

im1 = rand(50,40,3); im2 = rand(50,50,3);

Write the first image to a new TIFF file. Then, append the second image to the same file.

imwrite(im1,"myMultipageFile.tiff") imwrite(im2,"myMultipageFile.tiff","WriteMode","append")

Write Animated GIF

Draw a series of plots, capture them as images, and write them into one animated GIF file.

Plot y=xn for n=3.

x = 0:0.01:1; n = 3; y = x.^n; plot(x,y,LineWidth=3) title("$y = x^n$, n=n = n=" + num2str(n),Interpreter="latex")

Figure contains an axes object. The axes object with title y equals x toThePowerOf n baseline , n equals 3 contains an object of type line.

Capture a series of plots for increasing values of n.

n = 1:0.5:5; nImages = length(n);

fig = figure; for idx = 1:nImages y = x.^n(idx); plot(x,y,LineWidth=3) title("$y = x^n$, n=n = n=" + num2str(n(idx)),Interpreter="latex") drawnow frame = getframe(fig); im{idx} = frame2im(frame); end close;

Display the series of images in one figure.

figure; for idx = 1:nImages subplot(3,3,idx) imshow(im{idx}); end

Figure contains 9 axes objects. Hidden axes object 1 contains an object of type image. Hidden axes object 2 contains an object of type image. Hidden axes object 3 contains an object of type image. Hidden axes object 4 contains an object of type image. Hidden axes object 5 contains an object of type image. Hidden axes object 6 contains an object of type image. Hidden axes object 7 contains an object of type image. Hidden axes object 8 contains an object of type image. Hidden axes object 9 contains an object of type image.

Save the nine images into a GIF file. Because three-dimensional data is not supported for GIF files, call rgb2ind to convert the RGB data in the image to an indexed image A with a colormap map. To append multiple images to the first image, call imwrite with the name-value argument WriteMode set to "append".

filename = "testAnimated.gif"; % Specify the output file name for idx = 1:nImages [A,map] = rgb2ind(im{idx},256); if idx == 1 imwrite(A,map,filename,"gif",LoopCount=Inf, ... DelayTime=1) else imwrite(A,map,filename,"gif",WriteMode="append", ... DelayTime=1) end end

imwrite writes the GIF file to your current folder. Setting LoopCount to Inf causes the animation to loop continuously. Setting DelayTime to 1 specifies a 1-second delay between the display of each image in the animation.

Input Arguments

collapse all

A — Image data

matrix

Image data, specified as a full (nonsparse) matrix.

For TIFF files, A can be an_m_-by-_n_-by-4 array containing color data that uses the CMYK color space.

For multiframe GIF files, A can be an_m_-by-_n_-by-1-by-p array containing grayscale or indexed images, where p is the number of frames to write. RGB images are not supported in this case.

Data Types: double | single | uint8 | uint16 | logical

filename — Name of output file

string scalar | character vector

Name of the output file, specified as a string scalar or character vector.

Depending on the location you are writing to, filename can take on one of these forms.

Location Form
Current folder To write to the current folder, specify the name of the file infilename. filename must include the file extension. For a list of the image types thatimwrite can write, see the description for thefmt input argument.Example: "myImage.jpg"
Other folders To write to a folder different from the current folder, specify the full or relative path name infilename.Example: "C:\myFolder\myImage.ext"Example: "\imgDir\myImage.ext"
Remote Location To write to a remote location, filename must contain the full path of the file specified as a uniform resource locator (URL) of the form:scheme_name://path_to_file/_my_file.ext_Based on the remote location,scheme_name can be one of the values in this table. Remote Location_scheme_name_Amazon S3™s3Windows Azure® Blob Storagewasb, wasbsHDFS™hdfsFor more information, see Work with Remote Data.Example: "s3://bucketname/path_to_file/my_image.jpg"

Data Types: char | string

map — Colormap of indexed image

_m_-by-3 array

Colormap associated with indexed image data in A, specified as an_m_-by-3 array. map must be a valid MATLAB® colormap. See colormap for a list of built-in MATLAB colormaps. Most image file formats do not support colormaps with more than 256 entries.

Example: [0,0,0; 0.5,0.5,0.5; 1,1,1]

Example: jet(60)

Data Types: double

fmt — Format of output file

"bmp" | "gif" | "hdf" | "jpg" | "jp2" | ...

Format of the output file, specified as one of the formats in this table.

This table also summarizes the types of images that imwrite can write. The MATLAB file format registry determines which file formats are supported. See imformats for more information about this registry.

For certain formats, imwrite can accept additional name-value arguments. To view these arguments, click the linked format names below.

Value of fmt Format of Output File Description
"bmp" Windows® Bitmap (BMP) 1-bit, 8-bit, and 24-bit uncompressed images
"gif" GIF — Graphics Interchange Format 8-bit images
"hdf" HDF4 — Hierarchical Data Format 8-bit raster image data sets with or without associated colormap, 24-bit raster image data sets
"jpg" or"jpeg" JPEG — Joint Photographic Experts Group 8-bit, 12-bit, and 16-bit Baseline JPEG images Noteimwrite converts indexed images to RGB before writing data to JPEG files, because the JPEG format does not support indexed images.
"jp2" or"jpx" JPEG 2000— Joint Photographic Experts Group 2000 1-bit, 8-bit, and 16-bit JPEG 2000 images
"pbm" Portable Bitmap (PBM) Any 1-bit PBM image, ASCII (plain) or raw (binary) encoding
"pcx" Windows Paintbrush (PCX) 8-bit images
"pgm" Portable Graymap (PGM) Any standard PGM image; ASCII (plain) encoded with arbitrary color depth; raw (binary) encoded with up to 16 bits per gray value
"png" PNG — Portable Network Graphics 1-bit, 2-bit, 4-bit, 8-bit, and 16-bit grayscale images; 8-bit and 16-bit grayscale images with alpha channels; 1-bit, 2-bit, 4-bit, and 8-bit indexed images; 24-bit and 48-bit truecolor images; 24-bit and 48-bit truecolor images with alpha channels NoteThe imwrite function does not support writing of indexed PNG files that have insufficient colormap entries.
"pnm" Portable Anymap (PNM) Any of the PPM/PGM/PBM formats, chosen automatically
"ppm" Portable Pixmap (PPM) Any standard PPM image: ASCII (plain) encoded with arbitrary color depth or raw (binary) encoded with up to 16 bits per color component
"ras" Sun® Raster (RAS) Any RAS image, including 1-bit bitmap, 8-bit indexed, 24-bit truecolor, and 32-bit truecolor with alpha
"tif" or"tiff" Tagged Image File Format (TIFF) Baseline TIFF images, including: 1-bit, 8-bit, 16-bit, 24-bit, and 48-bit uncompressed images and images with packbits, LZW, or Deflate compression1-bit images with CCITT 1D, Group 3, and Group 4 compressionCIELAB, ICCLAB, and CMYK images
"xwd" X Windows Dump (XWD) 8-bit ZPixmaps

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: imwrite(A,"myFile.png",BitDepth=8) writes the data inA using 8 bits to represent each pixel.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: imwrite(A,"myFile.png","BitDepth",8) writes the data inA using 8 bits to represent each pixel.

GIF — Graphics Interchange Format

collapse all

BackgroundColor — Color to use as background color

nonnegative integer scalar

Color to use as background color for the indexed image, specified as a nonnegative integer scalar corresponding to the colormap index.

The background color is used for some disposal methods in animated GIFs.

The default background color corresponds to the first color in the colormap.

Example: "BackgroundColor",15

Comment to add to the image, specified as a string scalar, a character vector, a 1-by-n string array, or a 1-by-n cell array of character vectors. For a string array or cell array of character vectors,imwrite adds a carriage return after each entry.

Example: "Comment",["Sample #314","January 5, 2013"]

Data Types: string | char | cell

DelayTime — Delay before displaying next image

0.5 (default) | scalar value in the range [0, 655]

Delay before displaying next image, in seconds, specified as a scalar value in the range [0, 655].

Tip

To achieve a high animation rate, set DelayTime to0.02. Setting DelayTime to a lower value will slow down the actual animation rate in many image viewers and web browsers.

Example: "DelayTime",60

DisposalMethod — Disposal method of animated GIF

"doNotSpecify" (default) | "leaveInPlace" | "restoreBG" | "restorePrevious"

Disposal method of an animated GIF, specified as one of the methods in this table.

Value of DisposalMethod Result
"doNotSpecify" (default) Replace one full-size, nontransparent frame with another.
"leaveInPlace" Any pixels not covered up by the next frame continue to display.
"restoreBG" The background color or background tile shows through transparent pixels.
"restorePrevious" Restore to the state of a previous, undisposed frame.

Example: "DisposalMethod","restoreBG"

Location — Offset of screen relative to image

[0,0] (default) | two-element vector

Offset of the screen relative to the image, measured from the top-left corner of each, specified as a two-element vector. The first vector element specifies the offset from the top, and the second element specifies the offset from the left, in pixels.

Example: "Location",[10,15]

Data Types: double

LoopCount — Number of times to repeat animation

0 (default) | integer in the range [0, 65,535] | Inf

Number of times to repeat the animation, specified as either an integer in the range [0, 65,535] or the value Inf. If you specify the value0, the animation plays once; if you specify the value1, the animation plays twice, and so on. ALoopCount value of Inf causes the animation to loop continuously.

To enable animation within Microsoft® PowerPoint®, specify a value for LoopCount within the range [1, 65,535]. Some Microsoft applications interpret the value 0 to mean not to loop at all.

Example: "LoopCount",3

ScreenSize — Height and width of frame

height and width of input image (default) | two-element vector

Height and width of the frame, specified as a two-element vector. You can useScreenSize argument with Location to write frames to the image that are smaller than the whole frame.DisposalMethod determines the fill value for pixels outside the frame.

Example: "ScreenSize",[1000 1060]

Data Types: double

TransparentColor — Color to use as transparent color

nonnegative integer scalar

Color to use as transparent color for the image, specified as a nonnegative integer scalar corresponding to the colormap index.

Example: "TransparentColor",20

WriteMode — Writing mode

"overwrite" (default) | "append"

Writing mode, specified as "overwrite" or"append". In "overwrite" mode,imwrite overwrites an existing file,filename. In "append" mode,imwrite adds a single frame to the existing file.

Example: "WriteMode","append"

HDF4 — Hierarchical Data Format

collapse all

Compression — Compression scheme

"none" (default) | "jpeg" | "rle"

Compression scheme, specified as one of the options in this table.

Value of Compression Result
"none" (default) No compression
"jpeg" JPEG compression. Valid only for grayscale and RGB images.
"rle" Run-length encoding. Valid only for grayscale and indexed images.

Example: "Compression","jpeg"

Quality — Quality of JPEG-compressed file

75 (default) | scalar in the range [0, 100]

Quality of the JPEG-compressed file, specified as a scalar in the range [0, 100], where 0 is lower quality and higher compression, and 100 is higher quality and lower compression. This parameter applies only if Compression is"jpeg".

Example: "Quality",25

WriteMode — Writing mode

"overwrite" (default) | "append"

Writing mode, specified as "overwrite" or"append". In "overwrite" mode,imwrite overwrites an existing file,filename. In "append" mode,imwrite adds a single frame to the existing file.

Example: "WriteMode","append"

JPEG — Joint Photographic Experts Group

collapse all

BitDepth — Number of bits per pixel

8 (default) | 12 | 16

Number of bits per pixel, specified as a scalar.

Example: "BitDepth",12

Comment to add to the image, specified as a string scalar, a character vector, an_n_-by-1 string array, or an _n_-by-1 cell array of character vectors. For a string array or cell array of character vectors,imwrite writes each row of input as a comment in the JPEG file.

Example: "Comment",["First comment";"second comment";"third comment"]

Data Types: string | char | cell

Mode — Type of compression

"lossy" (default) | "lossless"

Type of compression, specified as "lossy" or"lossless".

Example: "Mode","lossless"

Quality — Quality of output file

75 (default) | scalar in the range [0, 100]

Quality of the output file, specified as a scalar in the range [0, 100], where 0 is lower quality and higher compression, and 100 is higher quality and lower compression. A Quality value of 100 does not write a lossless JPEG image. Instead, set the Mode name-value argument to"lossless".

Example: "Quality",100

JPEG 2000— Joint Photographic Experts Group 2000

collapse all

Comment to add to the image, specified as a string scalar, a character vector, a string array, or a cell array of character vectors. For a string array or cell array of character vectors, imwrite writes each entry as a comment in the JPEG 2000 file, in column-major order.

Example: "Comment",["First comment";"second comment";"third comment"]

Example: "Comment",{'First comment','second comment','third comment'}

Data Types: string | char | cell

CompressionRatio — Target compression ratio

1 (default) | positive scalar

Target compression ratio, specified as a positive scalar greater than or equal to 1. The compression ratio is the ratio of the input image size to the output compressed size. For example, a value of 2 implies that the output image size is half of the input image size or less. A higher value implies a smaller file size and more reduced image quality. The compression ratio does not take into account the header size.

Specifying CompressionRatio is valid only whenMode is "lossy".

Example: "CompressionRatio",3

Mode — Type of compression

"lossy" (default) | "lossless"

Type of compression, specified as "lossy" or"lossless".

Example: "Mode","lossless"

ProgressionOrder — Order of packets in code stream

"LRCP" (default) | "RLCP" | "RPCL" | "PCRL" | "CPRL"

Order of packets in the code stream, specified as one of these options:

The characters represent these packets: L = layer,R = resolution, C = component, andP = position.

Example: "ProgressionOrder","RLCP"

QualityLayers — Number of quality layers

1 (default) | integer in the range [1, 20]

Number of quality layers, specified as an integer in the range [1, 20].

Example: "QualityLayers",8

ReductionLevels — Number of reduction levels

4 (default) | integer in the range [1, 8]

Number of reduction levels, or wavelet decomposition levels, specified as an integer in the range [1, 8].

Example: "ReductionLevels",6

TileSize — Tile height and width

image size (default) | two-element vector

Tile height and width, specified as a two-element vector. The minimum size you can specify is [128 128].

Example: "TileSize",[130 130]

PBM, PGM, and PPM — Portable Bitmap, Graymap, Pixmap

collapse all

Encoding — Encoding

"rawbits" (default) | "ASCII"

Encoding, specified as "rawbits" for binary encoding or"ASCII" for plain encoding.

Example: "Encoding","ASCII"

MaxValue — Maximum gray or color value

positive integer scalar

Maximum gray or color value, specified as a positive integer scalar.

Specify this name-value argument only for PGM and PPM files. For PBM files, this value is always 1.

If the image array is uint16, then the default value forMaxValue is 65535. Otherwise, the default value is 255.

Example: "MaxValue",510

PNG — Portable Network Graphics

collapse all

Alpha — Transparency of each pixel

matrix of values in the range [0, 1]

Transparency of each pixel, specified as a matrix of values in the range [0, 1]. The row and column dimensions of the Alpha matrix must be the same as those of the image data array. You can specify Alpha only for grayscale (_m_-by-n) and truecolor (_m_-by-_n_-by-3) image data.

Note

You cannot specify both Alpha andTransparency at the same time.

Data Types: double | uint8 | uint16

Author information, specified as a string scalar or character vector.

Example: "Author","Ann Smith"

Data Types: string | char

Background — Background color when compositing transparent pixels

scalar in the range [0, 1] | integer in the range [1, _P_] | three-element vector in the range [0, 1]

Background color when compositing transparent pixels, specified as a value dependent on the image data, as shown in this table.

Image Type Form of Background Value
Grayscale image Scalar in the range [0, 1].
Indexed image Integer in the range [1, P_], where_P is the colormap length. For example,"Background",50 sets the background color to the color specified by the 50th index in the colormap.
Truecolor image Three-element vector of RGB intensities in the range [0, 1]. For example,"Background",[0 1 1] sets the background color to cyan.

Data Types: double

BitDepth — Number of bits per pixel

1 | 2 | 4 | 8 | 16

Number of bits per pixel, specified as a scalar. Depending on the output image, the scalar can be one of these values.

Image Type Allowed Values for BitDepth
Grayscale image 1, 2, 4,8, or 16
Grayscale image with an alpha channel 8 or 16
Indexed image 1, 2, 4, or8
Truecolor image 8 or 16

Example: "BitDepth",4

Chromaticities — Reference white point and primary chromaticities

eight-element vector

Reference white point and primary chromaticities, specified as an eight-element vector of the form [wx wy rx ry gx gy bx by]. The elementswx and wy are the chromaticity coordinates of the white point, and the elements rx, ry,gx, gy, bx, andby are the chromaticity coordinates of red, green, and blue, respectively.

If you specify Chromaticities, you should also specify theGamma name-value argument.

Example: "Chromaticities",[0.312,0.329,0.002,0.002,0.001,0.001,0.115,0.312]

Data Types: double

Comment to add to the image, specified as a string scalar or character vector.

string scalar | character vector

Copyright notice, specified as a string scalar or character vector.

CreationTime — Time of original image creation

datetime | string scalar | character vector

Time of original image creation, specified as either a datetime, or a string scalar or character vector that represents a point in time. If you specifyCreationTime as a datetime value with a time zone, then imwrite stores the time zone as part of the value.

Example: "CreationTime",datetime("1955-11-12 10:04 PM","TimeZone","America/Los_Angeles")

Description — Description of image

string scalar | character vector

Description of the image, specified as a string scalar or character vector.

string scalar | character vector

Legal disclaimer, specified as a string scalar or character vector.

Gamma — File gamma

numeric scalar

File gamma, specified as a numeric scalar.

Example: "Gamma",2.2

ImageModTime — Time of last image modification

datetime | string scalar | character vector

Time of last image modification, specified as either a datetime, or a string scalar or character vector that represents a point in time. If you specifyImageModTime as a datetime value with a time zone other than UTC, then imwrite converts the value to UTC before storing it. If you specify ImageModTime as adatetime value without a time zone, thenimwrite interprets the value as UTC.

The default ImageModTime value is the time when you callimwrite.

Example: "ImageModTime",datetime("2018-04-01 9:00 AM","TimeZone","Europe/Rome")

InterlaceType — Interlacing scheme

"none" (default) | "adam7"

Interlacing scheme, specified as "none" for no interlacing or"adam7" to use the Adam7 algorithm.

Example: "InterlaceType","adam7"

ResolutionUnit — Unit for image resolution

"unknown" (default) | "meter"

Unit for image resolution, specified as "unknown" or"meter". If you specify ResolutionUnit, you must include at least one of the XResolution andYResolution name-value arguments. When the value ofResolutionUnit is "meter", theXResolution and YResolution values are interpreted as pixels per meter.

Example: "ResolutionUnit","meter","XResolution",1000

SignificantBits — Number of bits to regard as significant

[] (default) | positive integer scalar | positive integer vector

Number of bits in the data array to regard as significant, specified as a scalar or a vector in the range [1, BitDepth]. Depending on the output image type, the value must be in the following form.

Image Type Form of SignificantBits Value
Grayscale image without an alpha channel Scalar
Grayscale image with an alpha channel 2-element vector
Indexed image 3-element vector
Truecolor image without an alpha channel 3-element vector
Truecolor image with an alpha channel 4-element vector

Example: "SignificantBits",[2,3]

Software — Software used to create the image

string scalar | character vector

Software used to create the image, specified as a string scalar or character vector.

Source — Device used to create the image

string scalar | character vector

Device used to create the image, specified as a string scalar or character vector.

Transparency — Pixels to consider transparent

[] (default) | scalar in the range [0, 1] | vector

Pixels to consider transparent when no alpha channel is used, specified as a scalar or vector. Depending on the output image, the value must be in the following form.

Image Type Form of Transparency Value
Grayscale image Scalar in the range [0, 1], indicating the grayscale color to be considered transparent.
Indexed image _Q-element vector of values in the range [0, 1], where_Q is no larger than the colormap length and each value indicates the transparency associated with the corresponding colormap entry. In most cases, Q is 1.
Truecolor image Three-element vector of RGB intensities in the range [0, 1], indicating the truecolor color to consider transparent.

Note

You cannot specify both Transparency andAlpha at the same time.

Example: "Transparency",[1 1 1]

Data Types: double

Warning — Warning of nature of content

string scalar | character vector

Warning of nature of content, specified as a string scalar or character vector.

XResolution — Image resolution in horizontal direction

numeric scalar

Image resolution in the horizontal direction, in pixels/unit, specified as a numeric scalar. Define the unit by specifying the ResolutionUnit name-value argument.

If you do not also specify YResolution, then theXResolution value applies to both the horizontal and vertical directions.

Example: "XResolution",900

YResolution — Image resolution in vertical direction

numeric scalar

Image resolution in the vertical direction, in pixels/unit, specified as a numeric scalar. Define the unit by specifying the ResolutionUnit name-value argument.

If you do not also specify XResolution, then theYResolution value applies to both the vertical and horizontal directions.

Example: "YResolution",900

In addition to the listed name-value arguments for PNG, you can use any parameter name that satisfies the PNG specification for keywords. That is, the name uses only printable characters, contains 80 or fewer characters, and does not contain leading or trailing spaces. The value corresponding to these user-specified names must be a string scalar or character vector that contains no control characters other than linefeeds.

RAS — Sun Raster Graphic

collapse all

Alpha — Transparency of each pixel

[] (default) | matrix

Transparency of each pixel, specified as a matrix with row and column dimensions the same as those of the image data array.

This name-value argument is valid only for truecolor (_m_-by-_n_-by-3) image data.

Data Types: double | single | uint8 | uint16

Type — Image type

"standard" (default) | "rgb" | "rle"

Image type, specified as one of the options in this table.

Value of Type Description
"standard" (default) Uncompressed, B-G-R color order for truecolor images
"rgb" Uncompressed, R-G-B color order for truecolor images
"rle" Run-length encoding of 1-bit and 8-bit images

Example: "Type","rgb"

TIFF — Tagged Image File Format

collapse all

ColorSpace — Color space representing color data

"rgb" (default) | "cielab" | "icclab"

Color space representing the color data, specified as "rgb","cielab", or "icclab".

This name-value argument is valid only when the image data array,A, is truecolor (_m_-by-_n_-by-3). To use the CMYK color space in a TIFF file, do not use the ColorSpace name-value argument. Instead, specify an _m_-by-_n_-by-4 image data array.

imwrite can write color image data that uses the_L*a*b*_ color space to TIFF files. The 1976 CIE_L*a*b*_ specification defines numeric values that represent luminance (L*) and chrominance (a* and_b*_) information. To store L*a*b* color data in a TIFF file, the values must be encoded to fit into either 8-bit or 16-bit storage. imwrite can store L*a*b* color data in a TIFF file using these encodings:

The output class and encoding used by imwrite depends on the class of the input image data array and the ColorSpace value, as shown in this table. (The 8-bit and 16-bit CIELAB encodings cannot be input arrays because they use a mixture of signed and unsigned values and cannot be represented as a single MATLAB array.)

Input Class and Encoding Value of ColorSpace Output Class and Encoding
8-bit ICCLAB Values are integers in the range [0, 255]. L* values are multiplied by 2.55. 128 is added to both the_a*_ and b* values. "icclab" 8-bit ICCLAB
"cielab" 8-bit CIELAB
16-bit ICCLAB Values are integers in the range [0, 65,280]. L* values are multiplied by 652.8. 32768 is added to both the_a*_ and b* values, which are represented as integers in the range [0, 65,535]. "icclab" 16-bit ICCLAB
"cielab" 16-bit CIELAB
Double-precision 1976 CIE L*a*b* values L* is in the dynamic range [0, 100]. a* and b* can take any value. Setting a* and_b*_ to 0 (zero) produces a neutral color (gray). "icclab" 8-bit ICCLAB
"cielab" 8-bit CIELAB

Example: "ColorSpace","cielab"

Compression — Compression scheme

"packbits" | "none" | "lzw" | "deflate" | "jpeg" | "ccitt" | "fax3" | "fax4"

Compression scheme, specified as one of these options:

"jpeg" is a lossy compression scheme; other compression modes are lossless. Also, if you specify "jpeg" compression, you must specify the RowsPerStrip name-value argument and the value must be a multiple of 8.

Example: "Compression","none"

Description — Image description

string scalar | character vector

Image description, specified by a string scalar or character vector. This description is the text that imfinfo returns in theImageDescription field for the output image.

Example: "Description","Sample 2A301"

Resolution — X- and Y-resolution

72 (default) | scalar | two-element vector

X- and Y-resolution, specified as a scalar indicating both X-resolution and Y-resolution, or a two-element vector containing the X-resolution and the Y-resolution.

Example: "Resolution",80

Example: "Resolution",[320,72]

Data Types: double

RowsPerStrip — Number of rows to include in each strip

positive integer scalar

Number of rows to include in each strip, specified as a scalar. The default value is such that each strip is about 8 kilobytes.

You must specify RowsPerStrip if you specify"jpeg" compression. In this case, the value must be a multiple of 8.

Example: "RowsPerStrip",16

Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

WriteMode — Writing mode

"overwrite" (default) | "append"

Writing mode, specified as "overwrite" or"append". In "overwrite" mode,imwrite overwrites an existing file. In"append" mode, imwrite adds a page to the existing file.

Example: "WriteMode","append"

Extended Capabilities

Thread-Based Environment

Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Usage notes and limitations:

For more information, see Run MATLAB Functions in Thread-Based Environment.

GPU Arrays

Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

The imwrite function supports GPU array input with these usage notes and limitations:

For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Version History

Introduced before R2006a

expand all

R2022b: Use datetime for PNG metadata

You can use datetime values to specify theCreationTime and ImageModTime name-value arguments.

R2021b: Support for thread-based environment

You can run imwrite in the background using MATLABbackgroundPool.

R2021b: Pixel differences in JPEG 2000 images

Pixel value differences might exist between JPEG 2000 images in R2021b and previous releases of MATLAB.

R2019b: Writing of indexed PNG files that have insufficient colormap entries is not supported

When writing indexed PNG files, you must specify a colormap with enough entries to interpret the image correctly.