.. _Intermediate/WriteAnImageWithMaxBitDepth:

Write an Image to File with a Maximum Bit Depth
===============================================

Problem
-------

You want to write an image to file and specify a maximum bit depth.

Solution
--------

::

    import Draft
    from DraftParamParser import SplitDataType      # Import SplitDataType from the DraftParamParser library
    
    # Read an image from file
    image = Draft.Image.ReadFromFile( '//path/to/in.exr' )
    
    # Get the current file channel map
    fileChannelMap = image.GetFileChannelMap()
    
    # Set a max bit depth of 16
    for key in fileChannelMap:
        splitDataType = SplitDataType( fileChannelMap[key] )
        bitDepth = int( splitDataType[0] )
        dataType = splitDataType[1]
        if bitDepth > 16:
            fileChannelMap[key] = '16' + dataType

    # Set the file channel map
    image.SetFileChannelMap( fileChannelMap )
    
    # Write the image back to file
    image.WriteToFile( '//path/to/out.exr' )

Discussion
----------

If you want to limit the bit depth of an image file that was read from file to a maximum of 16, you need to first get that image's file channel map using::

    fileChannelMap = image.GetFileChannelMap()
    
Then, fileChannelMap will store a dictionary containing the data type for each channel present in the image. The function :func:`~DraftParamParser.SplitDataType` from the :mod:`DraftParamParser` library takes a valid data type string made of a strictly positive number followed by an optional group of letters and split this string in two, the first part being the bit depth and the second the optional group of letters. Looping through all the image channel, you can easily extract the bit depth of each channel by using::

    splitDataType = SplitDataType( fileChannelMap[key] )
    bitDepth = int( splitDataType[0] )
    dataType = splitDataType[1]

and you can modify the channel bit depth using::

    if bitDepth > 16:
        fileChannelMap[key] = '16' + dataType

You can then write the image back to file. Note that even if, in this process, you set the file channel data type to '16ui' before writing an EXR image to file, the channel will still be written as '32ui' since an EXR unsigned integer always has a bit depth of 32.
    

See Also
--------

You can consult the sections :ref:`Concepts/ImageFileChannelMap` in Concepts and :ref:`Basic/WriteAnImageWithFileChannelMap` in the Basic Cookbook.