This is a static copy of a profile report

Home

imwrite (Calls: 10, Time: 0.764 s)
Generated 16-Jul-2020 17:09:39 using performance time.
function in file /Applications/MATLAB_R2020a.app/toolbox/matlab/imagesci/imwrite.m
Copy to new window for comparing multiple runs

Parents (calling functions)

Function NameFunction TypeCalls
mlprintjob>mlprintjob.writeRasterclass method10
Lines where the most time was spent

Line NumberCodeCallsTotal Time% TimeTime Plot
559
feval(fmt_s.write, data, map, ...
100.738 s96.6%
440
[data, map, filename, format, ...
100.014 s1.8%
545
fclose(fid);
100.004 s0.6%
454
fmt_s = imformats(format);
100.002 s0.2%
550
validateSizes(data);
100.002 s0.2%
All other lines  0.005 s0.6%
Totals  0.764 s100% 
Children (called functions)

Function NameFunction TypeCallsTotal Time% TimeTime Plot
imagesci/private/writepngfunction100.735 s96.2%
imwrite>parse_inputssubfunction100.012 s1.6%
imformatsfunction100.001 s0.2%
imwrite>validateSizessubfunction100.001 s0.2%
Self time (built-ins, overhead, etc.)  0.014 s1.9%
Totals  0.764 s100% 
Code Analyzer results
Line numberMessage
479This import statement runs before any other code in function 'imwrite'. Consider placing it at the top of the function body.
Coverage results
Show coverage for parent directory
Total lines in function576
Non-code lines (comments, blank lines)478
Code lines (lines that can run)98
Code lines that did run34
Code lines that did not run64
Coverage (did run/can run)34.69 %
Function listing
time 
Calls 
 line
   1 
function imwrite(varargin)
   2 
%IMWRITE Write image to graphics file.
   3 
%   IMWRITE(A,FILENAME,FMT) writes the image A to the file specified by
   4 
%   FILENAME in the format specified by FMT.
   5 
%
   6 
%   A can be an M-by-N (grayscale image) or M-by-N-by-3 (color image)
   7 
%   array.  A cannot be an empty array.  If the format specified is TIFF,
   8 
%   IMWRITE can also accept an M-by-N-by-4 array containing color data
   9 
%   that uses the CMYK color space.
  10 
%
  11 
%   FILENAME is a character vector or string scalar that specifies the name of the file.
  12 
%
  13 
%   FMT is a character vector or string scalar specifying the format of the file.  See the reference
  14 
%   page, or the output of the IMFORMATS function, for a list of
  15 
%   supported formats.
  16 
%
  17 
%   IMWRITE(X,MAP,FILENAME,FMT) writes the indexed image in X and its
  18 
%   associated colormap MAP to FILENAME in the format specified by FMT.
  19 
%   If X is of class uint8 or uint16, IMWRITE writes the actual values in 
  20 
%   the array to the file.  If X is of class double, IMWRITE offsets the
  21 
%   values in the array before writing, using uint8(X-1).  MAP must be a
  22 
%   valid MATLAB colormap.  Note that most image file formats do not
  23 
%   support colormaps with more than 256 entries.
  24 
%
  25 
%   When writing multiframe GIF images, X should be an 4-dimensional
  26 
%   M-by-N-by-1-by-P array, where P is the number of frames to write.
  27 
%
  28 
%   IMWRITE(...,FILENAME) writes the image to FILENAME, inferring the
  29 
%   format to use from the filename's extension. The extension must be
  30 
%   one of the legal values for FMT. 
  31 
%
  32 
%   IMWRITE(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies parameters that
  33 
%   control various characteristics of the output file. Parameters are
  34 
%   currently supported for GIF, HDF, JPEG, TIFF, PNG, PBM, PGM, and PPM
  35 
%   files.
  36 
%   
  37 
%   IMWRITE(...,IRI) writes image at a remote location. When
  38 
%   writing data to remote locations, you must specify the full path
  39 
%   using an internationalized resource identifier (IRI). For example, to
  40 
%   write an image from Amazon S3 cloud specify the full IRI for the image:
  41 
%       s3://bucketname/path_to_file/my_image.jpg
  42 
%
  43 
%   IMWRITE(...,IRI,'WriteMode','append') appends a frame to a TIF or GIF file
  44 
%   at a remote location. When writing data to remote locations, you must 
  45 
%   specify the full path using an internationalized resource identifier (IRI).
  46 
%   For example, to write an image from Amazon S3 cloud specify the full IRI
  47 
%   for the image:
  48 
%       s3://bucketname/path_to_file/my_image.jpg
  49 
%   For more information on accessing remote data, see "Work With Remote Data"
  50 
%   in the documentation.
  51 
%
  52 
%   Class Support
  53 
%   -------------
  54 
%   The input array A can be of class logical, uint8, uint16, single, or 
  55 
%   double.  Indexed images (X) can be of class uint8, uint16, single, or 
  56 
%   double; the associated colormap, MAP, must be double.  Input values 
  57 
%   must be full (non-sparse).
  58 
%
  59 
%   The class of the image written to the file depends on the format
  60 
%   specified.  For most formats, if the input array is of class uint8,
  61 
%   IMWRITE outputs the data as 8-bit values.  If the input array is of
  62 
%   class uint16 and the format supports 16-bit data (JPEG, PNG, and
  63 
%   TIFF), IMWRITE outputs the data as 16-bit values.  If the format does
  64 
%   not support 16-bit values, IMWRITE issues an error.  Several formats,
  65 
%   such as JPEG and PNG, support a parameter that lets you specify the
  66 
%   bit depth of the output data.
  67 
%
  68 
%   If the input array is of class double, and the image is a grayscale
  69 
%   or RGB color image, IMWRITE assumes the dynamic range is [0,1] and
  70 
%   automatically scales the data by 255 before writing it to the file as
  71 
%   8-bit values.
  72 
%
  73 
%   If the input array is of class double, and the image is an indexed
  74 
%   image, IMWRITE converts the indices to zero-based indices by
  75 
%   subtracting 1 from each element, and then writes the data as uint8.
  76 
%
  77 
%   If the input array is of class logical, IMWRITE assumes the data is a
  78 
%   binary image and writes it to the file with a bit depth of 1, if the
  79 
%   format allows it.  BMP, PNG, or TIFF formats accept binary images as
  80 
%   input arrays.
  81 
%
  82 
%   GIF-specific parameters
  83 
%   -----------------------
  84 
%
  85 
%   'WriteMode'         One of these values: 'overwrite' (the default)
  86 
%                       or 'append'.  In append mode, a single frame is
  87 
%                       added to the existing file.
  88 
%
  89 
%   'Comment'           A character vector or cell array of character
  90 
%                       vector or string scalar or string array,
  91 
%                       containing a comment to be added to the image.  For
  92 
%                       a cell array of character vector or string array,
  93 
%                       a carriage return is added after each row.
  94 
%
  95 
%   'DisposalMethod'    One of the following values, which sets the 
  96 
%                       disposal method of an animated GIF:
  97 
%                       'leaveInPlace', 'restoreBG', 'restorePrevious',
  98 
%                       or 'doNotSpecify'.
  99 
%
 100 
%   'DelayTime'         A scalar value between 0 and 655 inclusive, which
 101 
%                       specifies the delay in seconds before displaying
 102 
%                       the next image. 
 103 
%   
 104 
%   'TransparentColor'  A scalar integer.  This value specifies which
 105 
%                       index in the colormap should be treated as the
 106 
%                       transparent color for the image.  If X is uint8
 107 
%                       or logical, then indexing starts at 0.  If X is
 108 
%                       double, then indexing starts at 1.
 109 
%
 110 
%   'BackgroundColor'   A scalar integer.  This value specifies which
 111 
%                       index in the colormap should be treated as the
 112 
%                       background color for the image and is used for
 113 
%                       certain disposal methods in animated GIFs.  If X
 114 
%                       is uint8 or logical, then indexing starts at 0.
 115 
%                       If X is double, then indexing starts at 1.
 116 
%
 117 
%   'LoopCount'         A finite integer between 0 and 65535 or the value
 118 
%                       Inf (the default) which specifies the number of
 119 
%                       times to repeat the animation.  By default, the
 120 
%                       animation will continuously loop.  For a value of
 121 
%                       0, the animation will be played once.  For a
 122 
%                       value of 1, the animation will be played twice,
 123 
%                       etc.
 124 
%
 125 
%   'ScreenSize'        A two element vector specifying the screen height
 126 
%                       and width of the frame.  When used with
 127 
%                       'Location', this provides a way to write frames
 128 
%                       to the image which are smaller than the whole
 129 
%                       frame.  The remaining values are filled in
 130 
%                       according to the 'DisposalMethod'.
 131 
%
 132 
%   'Location'          A two element vector specifying the offset of the
 133 
%                       top left corner of the screen relative to the top
 134 
%                       left corner of the image.  The first element is
 135 
%                       the offset from the top, and the second element
 136 
%                       is the offset from the left.
 137 
%
 138 
%   HDF-specific parameters
 139 
%   -----------------------
 140 
%   'Compression'  One of these values: 'none' (the default), 
 141 
%                  'rle' (only valid for grayscale and indexed
 142 
%                  images), 'jpeg' (only valid for grayscale
 143 
%                  and RGB images)
 144 
%
 145 
%   'Quality'      A number between 0 and 100; parameter applies
 146 
%                  only if 'Compression' is 'jpeg'; higher
 147 
%                  numbers mean quality is better (less image
 148 
%                  degradation due to compression), but the
 149 
%                  resulting file size is larger 
 150 
%
 151 
%   'WriteMode'    One of these values: 'overwrite' (the
 152 
%                  default) or 'append'
 153 
%
 154 
%   JPEG-specific parameters
 155 
%   ------------------------
 156 
%   'Quality'      A number between 0 and 100; higher numbers
 157 
%                  mean quality is better (less image degradation
 158 
%                  due to compression), but the resulting file
 159 
%                  size is larger
 160 
%
 161 
%   'Comment'      Comment must be a column containing text specified as
 162 
%                  chars, strings, cell array of character vectors, 
 163 
%                  or string array.  Each row of input is written out
 164 
%                  as a comment in the JPEG file.
 165 
%
 166 
%   'Mode'         Either 'lossy' (the default) or 'lossless'
 167 
%
 168 
%   'BitDepth'     A scalar value indicating desired bitdepth;
 169 
%                  for grayscale images this can be 8, 12, or 16;
 170 
%                  for truecolor images this can be 8 or 12.  Only
 171 
%                  lossless mode is supported for 16-bit images.
 172 
%
 173 
%   JPEG2000-specific parameters
 174 
%   ----------------------------
 175 
%   'Mode'             Either 'lossy' (the default) or 'lossless'.
 176 
%   
 177 
%   'CompressionRatio' A real value greater than 1 specifying the target 
 178 
%                      compression ratio which is defined as the ratio of 
 179 
%                      input image size to the output compressed size. For
 180 
%                      example, a value of 2.0 implies that the output
 181 
%                      image size will be half of the input image size or
 182 
%                      less. A higher value implies a smaller file size and
 183 
%                      reduced image quality. This is valid only with
 184 
%                      'lossy' mode. Note that the compression ratio
 185 
%                      doesn't take into account the header size, and hence
 186 
%                      in some cases the output file size can be larger
 187 
%                      than expected.  
 188 
%    
 189 
%   'ProgressionOrder' A character vector or string scalar that is one of 'LRCP', 'RLCP', 'RPCL', 
 190 
%                      'PCRL' or 'CPRL'. The four character identifiers are 
 191 
%                      interpreted as L=layer, R=resolution, C=component
 192 
%                      and P=position. The first character refers to the
 193 
%                      index which progresses most slowly, while the last
 194 
%                      refers to the index which progresses most quickly.
 195 
%                      The default value is 'LRCP'. 
 196 
%     
 197 
%   'QualityLayers'    A positive integer (not exceeding 20) specifying the  
 198 
%                      number of quality layers. The default value is 1.  
 199 
%   
 200 
%   'ReductionLevels'  A positive integer (not exceeding 8) specifying the
 201 
%                      number of reduction levels or the wavelet
 202 
%                      decomposition levels.  
 203 
%  
 204 
%   'TileSize'         A 2-element vector specifying tile height and tile 
 205 
%                      width. The minimum tile size that can be specified
 206 
%                      is [128 128]. The default tile size is same as the
 207 
%                      image size. 
 208 
% 
 209 
%   'Comment'          Comment must be a column containing text specified as
 210 
%                      chars, strings, cell array of character vectors, 
 211 
%                      or string array.  Each row of input is written out
 212 
%                      as a comment in the JPEG2000 file. 
 213 
%
 214 
%   TIFF-specific parameters
 215 
%   ------------------------
 216 
%   'Colorspace'   One of these values: 'rgb', 'cielab', or 
 217 
%                  'icclab'.  The default value is 'rgb'.  This 
 218 
%                  parameter is used only when the input array, 
 219 
%                  A, is M-by-N-by-3.  See the reference page
 220 
%                  for more details about creating L*a*b* TIFF 
 221 
%                  files.
 222 
%
 223 
%                  In order to create a CMYK TIFF, the colorspace
 224 
%                  parameter should not be used.  It is sufficient
 225 
%                  to specify the input array A as M-by-N-by-4.
 226 
%
 227 
%   'Compression'  One of these values: 'none', 'packbits'
 228 
%                  (default for nonbinary images), 'lzw', 'deflate', 
 229 
%                  'jpeg', 'ccitt' (default for binary images), 
 230 
%                  'fax3', 'fax4'; 'ccitt', 'fax3', and 
 231 
%                  'fax4' are valid for binary images only.
 232 
%
 233 
%                  'jpeg' is a lossy compression scheme; other 
 234 
%                  compression modes are lossless.
 235 
% 
 236 
%                  When using JPEG compression, the 'RowsPerStrip' 
 237 
%                  parameter must be specified and must be a multiple 
 238 
%                  of 8.
 239 
%
 240 
%   'Description'  Any character vector or string scalar; fills in the ImageDescription
 241 
%                  field returned by IMFINFO
 242 
%
 243 
%   'Resolution'   A two-element vector containing the
 244 
%                  XResolution and YResolution, or a scalar
 245 
%                  indicating both resolutions; the default value
 246 
%                  is 72
 247 
%
 248 
%   'RowsPerStrip' A scalar value.  The default will be such that each 
 249 
%                  strip is about 8K bytes.
 250 
%
 251 
%   'WriteMode'    One of these values: 'overwrite' (the
 252 
%                  default) or 'append'
 253 
%
 254 
%   PNG-specific parameters
 255 
%   -----------------------
 256 
%   'Author'       A character vector or string scalar
 257 
%
 258 
%   'Description'  A character vector or string scalar
 259 
%
 260 
%   'Copyright'    A character vector or string scalar
 261 
%
 262 
%   'CreationTime' A character vector or string scalar
 263 
%
 264 
%   'ImageModTime' A MATLAB datenum or a character vector or string scalar convertible to a
 265 
%                  date vector via the DATEVEC function.  Values
 266 
%                  should be in UTC time.
 267 
%
 268 
%   'Software'     A character vector or string scalar
 269 
%
 270 
%   'Disclaimer'   A character vector or string scalar
 271 
%
 272 
%   'Warning'      A character vector or string scalar
 273 
%
 274 
%   'Source'       A character vector or string scalar
 275 
%
 276 
%   'Comment'      A character vector or string scalar
 277 
%
 278 
%   'InterlaceType' Either 'none' or 'adam7'
 279 
%
 280 
%   'BitDepth'     A scalar value indicating desired bitdepth;
 281 
%                  for grayscale images this can be 1, 2, 4,
 282 
%                  8, or 16; for grayscale images with an
 283 
%                  alpha channel this can be 8 or 16; for
 284 
%                  indexed images this can be 1, 2, 4, or 8;
 285 
%                  for truecolor images with or without an
 286 
%                  alpha channel this can be 8 or 16
 287 
%
 288 
%   'Transparency' This value is used to indicate transparency
 289 
%                  information when no alpha channel is used.
 290 
%                  
 291 
%                  For indexed images: a Q-element vector in
 292 
%                    the range [0,1]; Q is no larger than the
 293 
%                    colormap length; each value indicates the
 294 
%                    transparency associated with the
 295 
%                    corresponding colormap entry
 296 
%                  For grayscale images: a scalar in the range
 297 
%                    [0,1]; the value indicates the grayscale
 298 
%                    color to be considered transparent
 299 
%                  For truecolor images: a 3-element vector in
 300 
%                    the range [0,1]; the value indicates the
 301 
%                    truecolor color to be considered
 302 
%                    transparent
 303 
%
 304 
%                  You cannot specify 'Transparency' and
 305 
%                  'Alpha' at the same time.
 306 
%
 307 
%   'Background'   The value specifies background color to be
 308 
%                  used when compositing transparent pixels.
 309 
%
 310 
%                  For indexed images: an integer in the range
 311 
%                    [1,P], where P is the colormap length
 312 
%                  For grayscale images: a scalar in the range
 313 
%                    [0,1]
 314 
%                  For truecolor images: a 3-element vector in
 315 
%                    the range [0,1]
 316 
%
 317 
%   'Gamma'        A nonnegative scalar indicating the file
 318 
%                  gamma
 319 
%
 320 
%   'Chromaticities' An 8-element vector [wx wy rx ry gx gy bx
 321 
%                  by] that specifies the reference white
 322 
%                  point and the primary chromaticities 
 323 
%
 324 
%   'XResolution'  A scalar indicating the number of
 325 
%                  pixels/unit in the horizontal direction
 326 
%
 327 
%   'YResolution'  A scalar indicating the number of
 328 
%                  pixels/unit in the vertical direction
 329 
%
 330 
%   'ResolutionUnit' Either 'unknown' or 'meter'
 331 
%
 332 
%   'Alpha'        A matrix specifying the transparency of
 333 
%                  each pixel individually; the row and column
 334 
%                  dimensions must be the same as the data
 335 
%                  array; may be uint8, uint16, or double, in
 336 
%                  which case the values should be in the
 337 
%                  range [0,1]
 338 
%
 339 
%   'SignificantBits' A scalar or vector indicating how many
 340 
%                  bits in the data array should be regarded
 341 
%                  as significant; values must be in the range
 342 
%                  [1,bitdepth]
 343 
%
 344 
%                  For indexed images: a 3-element vector
 345 
%                  For grayscale images: a scalar
 346 
%                  For grayscale images with an alpha channel:
 347 
%                    a 2-element vector
 348 
%                  For truecolor images: a 3-element vector
 349 
%                  For truecolor images with an alpha channel:
 350 
%                    a 4-element vector
 351 
%
 352 
%   In addition to these PNG parameters, you can use any
 353 
%   parameter name that satisfies the PNG specification for
 354 
%   keywords: only printable characters, 80 characters or
 355 
%   fewer, and no leading or trailing spaces.  The value
 356 
%   corresponding to these user-specified parameters must be a
 357 
%   character vector or string scalar that contains no control 
 358 
%   characters except for linefeed.
 359 
%
 360 
%   RAS-specific parameters
 361 
%   -----------------------
 362 
%   'Type'         One of these values: 'standard'
 363 
%                  (uncompressed, b-g-r color order with
 364 
%                  truecolor images), 'rgb' (like 'standard',
 365 
%                  but uses r-g-b color order for truecolor
 366 
%                  images), 'rle' (run-length encoding of 1-bit
 367 
%                  and 8-bit images)
 368 
%
 369 
%   'Alpha'        A matrix specifying the transparency of each
 370 
%                  pixel individually; the row and column
 371 
%                  dimensions must be the same as the data
 372 
%                  array; may be uint8, uint16, or double. May
 373 
%                  only be used with truecolor images.
 374 
%
 375 
%   PBM, PGM, and PPM-specific parameters
 376 
%   ------------------------
 377 
%   'Encoding'     One of these values: 'ASCII' for plain encoding
 378 
%                  or 'rawbits' for binary encoding.  Default is 'rawbits'.
 379 
%   'MaxValue'     A scalar indicating the maximum gray or color
 380 
%                  value.  Available only for PGM and PPM files.
 381 
%                  For PBM files, this value is always 1.  Default
 382 
%                  is 65535 if image array is 'uint16' and 255 otherwise.
 383 
%
 384 
%   Table: summary of supported image types
 385 
%   ---------------------------------------
 386 
%   BMP       1-bit, 8-bit and 24-bit uncompressed images
 387 
%
 388 
%   GIF       8-bit images
 389 
%
 390 
%   HDF       8-bit raster image datasets, with or without associated
 391 
%             colormap; 24-bit raster image datasets; uncompressed or
 392 
%             with RLE or JPEG compression
 393 
%
 394 
%   JPEG      8-bit, 12-bit, and 16-bit Baseline JPEG images
 395 
%
 396 
%   JPEG2000  1-bit, 8-bit, and 16-bit JPEG2000 images 
 397 
%
 398 
%   PBM       Any 1-bit PBM image, ASCII (plain) or raw (binary) encoding.
 399 
%
 400 
%   PCX       8-bit images
 401 
%
 402 
%   PGM       Any standard PGM image. ASCII (plain) encoded with
 403 
%             arbitrary color depth. Raw (binary) encoded with up
 404 
%             to 16 bits per gray value.
 405 
%
 406 
%   PNG       1-bit, 2-bit, 4-bit, 8-bit, and 16-bit grayscale
 407 
%             images; 8-bit and 16-bit grayscale images with alpha
 408 
%             channels; 1-bit, 2-bit, 4-bit, and 8-bit indexed
 409 
%             images; 24-bit and 48-bit truecolor images; 24-bit
 410 
%             and 48-bit truecolor images with alpha channels
 411 
%
 412 
%   PNM       Any of PPM/PGM/PBM (see above) chosen automatically.
 413 
%
 414 
%   PPM       Any standard PPM image. ASCII (plain) encoded with
 415 
%             arbitrary color depth. Raw (binary) encoded with up
 416 
%             to 16 bits per color component.
 417 
%
 418 
%   RAS       Any RAS image, including 1-bit bitmap, 8-bit indexed,
 419 
%             24-bit truecolor and 32-bit truecolor with alpha.
 420 
%
 421 
%   TIFF      Baseline TIFF images, including 1-bit, 8-bit, 16-bit,
 422 
%             and 24-bit uncompressed images, images with packbits 
 423 
%             compression, images with LZW compression, and images
 424 
%             with Deflate compression; 8-bit and 24-bit images with 
 425 
%             JPEG compression; 1-bit images with CCITT 1D, Group 3, 
 426 
%             and Group 4 compression; CIELAB, ICCLAB, and CMYK images.
 427 
%
 428 
%   XWD       8-bit ZPixmaps
 429 
%
 430 
%   Please read the file libtiffcopyright.txt for more information.
 431 
%
 432 
%   See also IMFINFO, IMREAD, IMFORMATS, FWRITE, GETFRAME.
 433 

 434 
%   Copyright 1984-2019 The MathWorks, Inc.
 435 

< 0.001 
     10 
 436
if nargin > 0 
< 0.001 
     10 
 437
    [varargin{:}] = convertStringsToChars(varargin{:}); 
< 0.001 
     10 
 438
end 
 439 

  0.014 
     10 
 440
[data, map, filename, format, paramPairs] = parse_inputs(varargin{:}); 
 441 

< 0.001 
     10 
 442
validateattributes(data,{'numeric','logical'},{'nonempty','nonsparse'},'','DATA'); 
 443 

< 0.001 
     10 
 444
if (isempty(format)) 
 445 

 446 
    format = get_format_from_filename(filename);
 447 
    if (isempty(format))
 448 
        error(message('MATLAB:imagesci:imwrite:fileFormat'));
 449 
    end
 450 
    
< 0.001 
     10 
 451
end 
 452 

 453 
% Get the format details from the registry.
  0.002 
     10 
 454
fmt_s = imformats(format); 
 455 

 456 
% Signed data may cause unexpected results.
< 0.001 
     10 
 457
switch (class(data)) 
< 0.001 
     10 
 458
    case {'int8', 'int16', 'int32', 'int64'} 
 459 
        
 460 
        switch format
 461 
            case {'j2c', 'j2k', 'jp2', 'jpf', 'jpx'}
 462 
                %OK. writejp2 handles int8 and int16, errors for rest
 463 
            case {'jpg', 'jpeg'}
 464 
                error(message('MATLAB:imagesci:imwrite:signedJPEGNotSupported'));
 465 
            case {'tif','tiff'}
 466 
                %writetif will take appropriate action.
 467 
                
 468 
            otherwise
 469 
                warning(message('MATLAB:imagesci:imwrite:signedPixelData'))
 470 
        end
< 0.001 
     10 
 471
end 
 472 

 473 
%Check if filename is regular file or not.
< 0.001 
     10 
 474
URL = matlab.virtualfileio.internal.validators.isIRI(filename); 
< 0.001 
     10 
 475
if URL 
 476 
    try
 477 
        remoteFileName = filename;
 478 
        % check whether credentials are set
 479 
        import matlab.virtualfileio.internal.validators.validateCloudEnvVariables;
 480 
        validateCloudEnvVariables(filename);
 481 
        
 482 
        % Get the correct filename
 483 
        filenameWithoutPath = matlab.virtualfileio.internal.validators.IRIFilename(filename);
 484 
        remoteFolder = extractBefore(filename, filenameWithoutPath);
 485 
        ext = strfind(filenameWithoutPath, ".");
 486 
        if ~isempty(ext)
 487 
            index = ext(end);
 488 
            % Extract the extension along with '.' character
 489 
            ext = extractAfter(filenameWithoutPath, index-1);
 490 
            % Extract the full filename excluding the extension
 491 
            filenameWithoutPath = extractBefore(filenameWithoutPath,index);
 492 
        end
 493 
        
 494 
        localToRemote = matlab.virtualfileio.internal.stream.LocalToRemote(remoteFolder);
 495 
        % Check if Writemode is 'append' and the file exists
 496 
        index = find(ismember(lower(paramPairs(:)),lower('WriteMode')) == 1);
 497 
        if ~isempty(index) %'WriteMode' name is used with imwrite
 498 
            for i = 1 : numel(index)
 499 
                if  lower(paramPairs{index(i)+1}) == lower('append')
 500 
                    remote2Local = matlab.virtualfileio.internal.stream.RemoteToLocal(filename);
 501 
                    tempFile = remote2Local.LocalFileName;
 502 
                    % Set the local and the remote filepath
 503 
                    localToRemote.CurrentLocalFilePath = tempFile;
 504 
                    localToRemote.setRemoteFileName(filenameWithoutPath, ext);                    
 505 
                    break;
 506 
                end
 507 
            end
 508 
        end
 509 
    catch ME
 510 
        if ~strcmp(ME.identifier, 'MATLAB:virtualfileio:stream:fileNotFound')
 511 
            error(message('MATLAB:imagesci:imwrite:writeFailed', remoteFileName, ME.message));
 512 
        end
 513 
    end  
 514 
    % If currentLocalFilePath is empty, it means
 515 
    % 1. 'WriteMode' is not provided. Default is 'overwrite'
 516 
    % 2. 'WriteMode is provided but the value is not 'append'
 517 
    % 3. 'WriteMode' is provided and value is 'append' but file does not
 518 
    % exists in cloud
 519 
    if isempty(localToRemote.CurrentLocalFilePath)
 520 
        setfilename(localToRemote,filename);
 521 
    end
 522 
    filename = localToRemote.CurrentLocalFilePath;
< 0.001 
     10 
 523
end 
 524 

 525 
% Verify that the file can be written to. For TIFF files, sometimes, this
 526 
% call to FOPEN fails sporadically. Retry for a few times to guard against
 527 
% sporadic failures.
< 0.001 
     10 
 528
MAX_NUM_RETRIES = 4; 
< 0.001 
     10 
 529
fileOpenCnt = 1; 
  0.001 
     10 
 530
fid = fopen(filename, 'a'); 
< 0.001 
     10 
 531
while fid == -1 && fileOpenCnt < MAX_NUM_RETRIES 
 532 
    fileOpenCnt = fileOpenCnt + 1;
 533 
    
 534 
    % This might delay processing but it is better than sporadically
 535 
    % erroring out.
 536 
    pause(0.1);
 537 
    fid = fopen(filename, 'a');
 538 
end
 539 

< 0.001 
     10 
 540
if fid == -1 
 541 
    error(message('MATLAB:imagesci:imwrite:fileOpen', filename));
< 0.001 
     10 
 542
else 
 543 
    % File can be created.  Get full filename.
< 0.001 
     10 
 544
    filename = fopen(fid); 
  0.004 
     10 
 545
    fclose(fid); 
< 0.001 
     10 
 546
end 
 547 

 548 
% Currently all image formats use 32-bit offsets to data.
< 0.001 
     10 
 549
try 
  0.002 
     10 
 550
    validateSizes(data); 
 551 
catch myException
 552 
    cleanupEmptyFile(filename);
 553 
    rethrow(myException);
< 0.001 
     10 
 554
end 
 555 

 556 
% Call the writing function if it exists.
< 0.001 
     10 
 557
if (~isempty(fmt_s.write)) 
< 0.001 
     10 
 558
    try 
  0.738 
     10 
 559
        feval(fmt_s.write, data, map, filename, paramPairs{:}); 
 560 
    catch myException
 561 
        cleanupEmptyFile(filename);
 562 
        rethrow(myException);
< 0.001 
     10 
 563
    end 
< 0.001 
     10 
 564
    if URL 
 565 
        % upload the file to the remote location
 566 
        try
 567 
            upload(localToRemote);
 568 
        catch ME
 569 
            error(message('MATLAB:imagesci:imwrite:writeFailed', remoteFileName, ME.message));
 570 
        end
< 0.001 
     10 
 571
    end 
 572 
else
 573 
    cleanupEmptyFile(filename);
 574 
    error(message('MATLAB:imagesci:imwrite:writeFunctionRegistration', format));
< 0.001 
     10 
 575
end 
< 0.001 
     10 
 576
end 

Other subfunctions in this file are not included in this listing.