.. _raster.jpeg:

================================================================================
JPEG -- JPEG JFIF File Format
================================================================================

.. shortname:: JPEG

.. build_dependencies:: (internal libjpeg provided)

The JPEG JFIF format is supported for reading, and batch writing, but
not update in place. JPEG files are represented as one band (greyscale)
or three band (RGB) datasets with Byte valued bands.

The driver will automatically convert images whose color space is YCbCr,
CMYK or YCbCrK to RGB, unless GDAL_JPEG_TO_RGB is set to NO (YES is the
default). When color space translation to RGB is done, the source color
space is indicated in the SOURCE_COLOR_SPACE metadata of the
IMAGE_STRUCTURE domain.

EXIF metadata can be read from JPEG files (but this will not result in a
georeferenced image even if the EXIF_GPSLatitude and EXIF_GPSLongitude
tags are set). But if an ESRI world file exists with the .jgw,
.jpgw/.jpegw or .wld suffixes, it will be read and used to establish the
geotransform for the image. If available a MapInfo .tab file will also
be used for georeferencing. Overviews can be built for JPEG files as an
external .ovr file.

The driver also supports the "zlib compressed mask appended to the file"
approach used by a few data providers to add a bitmask to identify
pixels that are not valid data. See :ref:`rfc-15` for further
details.

The driver can deal with bitmask where the
bits are ordered with most significant bit first (whereas the usual
convention is least significant bit first). The driver will try to
autodetect that situation, but the heuristics may fail. In that
circumstance, you can set the JPEG_MASK_BIT_ORDER configuration option
to MSB. Bitmask can also be completely ignored by specifying
JPEG_READ_MASK to NO.

The GDAL JPEG Driver is built using the Independent JPEG Group's jpeg
library. Also note that the GeoTIFF driver supports tiled TIFF with JPEG
compressed tiles.

To be able to read and write JPEG images with 12-bit sample, you can
build GDAL with its internal libjpeg (based on IJG libjpeg-6b, with
additional changes for 12-bit sample support), or explicitly pass
--with-jpeg12=yes to configure script when building with external
libjpeg. See `"8 and 12 bit JPEG in
TIFF" <http://trac.osgeo.org/gdal/wiki/TIFF12BitJPEG>`__ wiki page for
more details.

It is also possible to use the JPEG driver with the libjpeg-turbo, a
version of libjpeg, API and ABI compatible with IJG libjpeg-6b, which
uses MMX, SSE, and SSE2 SIMD instructions to accelerate baseline JPEG
compression/decompression.

XMP metadata can be extracted from the file,
and will be stored as XML raw content in the xml:XMP metadata domain.

Embedded EXIF thumbnails (with JPEG compression)
can be used as overviews, and generated by GDAL.

Driver capabilities
-------------------

.. supports_createcopy::

.. supports_georeferencing::

.. supports_virtualio::

Color Profile Metadata
----------------------

GDAL can deal with the following color profile
metadata in the COLOR_PROFILE domain:

-  SOURCE_ICC_PROFILE (Base64 encoded ICC profile embedded in file.)

Note that this metadata property can only be used on the original raw
pixel data. If automatic conversion to RGB has been done, the color
profile information cannot be used.

This metadata tag can be used as creation options.

Error management
----------------

While decoding, libjpeg has resiliency towards some errors in the JPEG
datastream and will try to recover from them as much of possible.
Such errors will be reported as GDAL
Warnings, but can optionally be considered as true Errors by setting the
GDAL_ERROR_ON_LIBJPEG_WARNING configuration option to TRUE.

Creation Options
----------------

JPEG files are created using the "JPEG" driver code. Only Byte band
types are supported.

Only 1 (greyscale), 3 band (input should be in RGB colorspace.
the driver will convert it automatically to YCbCr colorspace for storage, and
will expose it back as RGB on reading) or 4 band
(input should already by in CMYK colorspace. It will be exposed as RGB on reading
by default, unless the :decl_configoption:`GDAL_JPEG_TO_RGB` configuration option
is set to NO) configurations.

JPEG file creation is implemented by the batch (CreateCopy) method.
YCbCrK colorspace is not supported in creation. If the source
dataset has a nodata mask, it will be appended as a zlib compressed mask
to the JPEG file.

-  **WORLDFILE=YES**: Force the generation of an associated ESRI world
   file (with the extension .wld).
-  **QUALITY=n**: By default the quality flag is set to 75, but this
   option can be used to select other values. Values must be in the
   range 10-100. Low values result in higher compression ratios, but
   poorer image quality. Values above 95 are not meaningfully better
   quality but can but substantially larger.
-  **PROGRESSIVE=ON**: Enabled generation of progressive JPEGs. In some
   cases these will display a reduced resolution image in viewers such
   as Netscape, and Internet Explorer, before the full file has been
   downloaded. However, some applications cannot read progressive JPEGs
   at all. GDAL can read progressive JPEGs, but takes no advantage of
   their progressive nature.
-  **INTERNAL_MASK=YES/NO**: By default, if needed, an internal mask in
   the "zlib compressed mask appended to the file" approach is written
   to identify pixels that are not valid data.
   This can be disabled by setting this option to NO.
-  **ARITHMETIC=YES/NO**: To enable arithmetic
   coding. Not enabled in all libjpeg builds, because of possible legal
   restrictions.
-  **BLOCK=1...16**: (libjpeg >= 8c) DCT block
   size. All values from 1 to 16 are possible. Default is 8 (baseline
   format). A value other than 8 will produce files incompatible with
   versions prior to libjpeg 8c.
-  **COLOR_TRANSFORM=RGB or RGB1**: (libjpeg >= 9). Set to RGB1 for
   lossless RGB. Note: this will produce files
   incompatible with versions prior to libjpeg 9.
-  **SOURCE_ICC_PROFILE=value**: ICC profile encoded in Base64.
-  **COMMENT=string**: String to embed in a
   comment JPEG marker. When reading, such strings are exposed in the
   COMMENT metadata item.
-  **EXIF_THUMBNAIL=YES/NO**: Whether to
   generate an EXIF thumbnail(overview), itself JPEG compressed.
   Defaults to NO. If enabled, the maximum dimension of the thumbnail
   will be 128, if neither THUMBNAIL_WIDTH nor THUMBNAIL_HEIGHT are
   specified.
-  **THUMBNAIL_WIDTH=n**: Width of thumbnail.
   Only taken into account if EXIF_THUMBNAIL=YES.
-  **THUMBNAIL_HEIGHT=n**: Height of
   thumbnail. Only taken into account if EXIF_THUMBNAIL=YES.
-  **WRITE_EXIF_METADATA=YES/NO**: (Starting with GDAL 2.3). Whether to
   write EXIF_xxxx metadata items in a EXIF segment. Default to YES.

EXIF and GPS tags
-----------------

The below tables list the EXIF and GPS tags that can be written.

-  The "Metadata item name" column presents the name of the metadata
   item to attach to the source dataset.
-  The "Hex code" column is the value of the corresponding TIFF EXIF/GPS
   tag (for reference only)
-  | The "Type" column is the TIFF type associated.

   -  ASCII is for text values that are NUL-terminated (for a fixed
      length tag, the length includes this NUL-terminating characters).
      e.g EXIF_Make=the_make
   -  BYTE/UNDEFINED is for values that can be made of any byte value.
      The value of the corresponding GDAL metadata item must be a string
      of hexadecimal formatted values, e.g EXIF_GPSVersionID=0x02 0x00
      0x00 0x00. GDAL also accepts an ASCII string: e.g.
      EXIF_ExifVersion=0231
   -  SHORT is for unsigned integer values in the range [0,65535]. Some
      tags may accept multiple values, in which case they must be
      separated by space.
   -  LONG is for unsigned integer values in the range [0,4294967295].
      Some tags may accept multiple values, in which case they must be
      separated by space.
   -  RATIONAL is for positive floating-point values. Some tags may
      accept multiple values, in which case they must be separated by
      space. e.g EXIF_GPSLatitude=49 2 3.5
   -  SRATIONAL is for positive or negative floating-point values. Some
      tags may accept multiple values, in which case they must be
      separated by space.

   When an item accepts a fixed number of values and that more are
   provided, they will be truncated with a warning. In the case they are
   less values provided than needed, they will be padded with
   appropriate spaces / zeroes

-  The "Number of values" column is the number of values for the item.
   Might be "variable" if there is no restriction, or a fixed value. For
   Type=ASCII, the fixed value includes the NUL-terminating byte, so the
   number of actual printable characters is number of values - 1.
-  The "Optionality" column indicates whether the item should be present
   ("Mandatory"), is "Recommended" or "Optional". GDAL does not enforce
   this.

Many items have more restrictions on the valid content that are not
expressed in the below tables. Consult the EXIF specification for more
information.

============================== ======== ========= ================ =============
Metadata item name             Hex code Type      Number of values Optionality
============================== ======== ========= ================ =============
EXIF_Document_Name             0x010D   ASCII     variable         Optional
EXIF_ImageDescription          0x010E   ASCII     variable         Recommended
EXIF_Make                      0x010F   ASCII     variable         Recommended
EXIF_Model                     0x0110   ASCII     variable         Recommended
EXIF_Orientation               0x0112   SHORT     1                Recommended
EXIF_XResolution               0x011A   RATIONAL  1                **Mandatory**
EXIF_YResolution               0x011B   RATIONAL  1                **Mandatory**
EXIF_ResolutionUnit            0x0128   SHORT     1                **Mandatory**
EXIF_TransferFunction          0x012D   SHORT     768              Optional
EXIF_Software                  0x0131   ASCII     variable         Optional
EXIF_DateTime                  0x0132   ASCII     20               Recommended
EXIF_Artist                    0x013B   ASCII     variable         Optional
EXIF_WhitePoint                0x013E   RATIONAL  2                Optional
EXIF_PrimaryChromaticities     0x013F   RATIONAL  6                Optional
EXIF_YCbCrCoefficients         0x0211   RATIONAL  3                Optional
EXIF_YCbCrPositioning          0x0213   SHORT     1                **Mandatory**
EXIF_ReferenceBlackWhite       0x0214   RATIONAL  6                Optional
EXIF_Copyright                 0x8298   ASCII     variable         Optional
EXIF_ExposureTime              0x829A   RATIONAL  1                Recommended
EXIF_FNumber                   0x829D   RATIONAL  1                Optional
EXIF_ExposureProgram           0x8822   SHORT     1                Optional
EXIF_SpectralSensitivity       0x8824   ASCII     variable         Optional
EXIF_ISOSpeedRatings           0x8827   SHORT     variable         Optional
EXIF_OECF                      0x8828   UNDEFINED variable         Optional
EXIF_SensitivityType           0x8830   SHORT     1                Optional
EXIF_StandardOutputSensitivity 0x8831   LONG      1                Optional
EXIF_RecommendedExposureIndex  0x8832   LONG      1                Optional
EXIF_ISOSpeed                  0x8833   LONG      1                Optional
EXIF_ISOSpeedLatitudeyyy       0x8834   LONG      1                Optional
EXIF_ISOSpeedLatitudezzz       0x8835   LONG      1                Optional
EXIF_ExifVersion               0x9000   UNDEFINED 4                **Mandatory**
EXIF_DateTimeOriginal          0x9003   ASCII     20               Optional
EXIF_DateTimeDigitized         0x9004   ASCII     20               Optional
EXIF_OffsetTime                0x9010   ASCII     7                Optional
EXIF_OffsetTimeOriginal        0x9011   ASCII     7                Optional
EXIF_OffsetTimeDigitized       0x9012   ASCII     7                Optional
EXIF_ComponentsConfiguration   0x9101   UNDEFINED 4                **Mandatory**
EXIF_CompressedBitsPerPixel    0x9102   RATIONAL  1                Optional
EXIF_ShutterSpeedValue         0x9201   SRATIONAL 1                Optional
EXIF_ApertureValue             0x9202   RATIONAL  1                Optional
EXIF_BrightnessValue           0x9203   SRATIONAL 1                Optional
EXIF_ExposureBiasValue         0x9204   SRATIONAL 1                Optional
EXIF_MaxApertureValue          0x9205   RATIONAL  1                Optional
EXIF_SubjectDistance           0x9206   RATIONAL  1                Optional
EXIF_MeteringMode              0x9207   SHORT     1                Optional
EXIF_LightSource               0x9208   SHORT     1                Optional
EXIF_Flash                     0x9209   SHORT     1                Recommended
EXIF_FocalLength               0x920A   RATIONAL  1                Optional
EXIF_SubjectArea               0x9214   SHORT     variable         Optional
EXIF_MakerNote                 0x927C   UNDEFINED variable         Optional
EXIF_UserComment               0x9286   UNDEFINED variable         Optional
EXIF_SubSecTime                0x9290   ASCII     variable         Optional
EXIF_SubSecTime_Original       0x9291   ASCII     variable         Optional
EXIF_SubSecTime_Digitized      0x9292   ASCII     variable         Optional
EXIF_FlashpixVersion           0xA000   UNDEFINED 4                **Mandatory**
EXIF_ColorSpace                0xA001   SHORT     1                **Mandatory**
EXIF_PixelXDimension           0xA002   LONG      1                **Mandatory**
EXIF_PixelYDimension           0xA003   LONG      1                **Mandatory**
EXIF_RelatedSoundFile          0xA004   ASCII     13               Optional
EXIF_FlashEnergy               0xA20B   RATIONAL  1                Optional
EXIF_SpatialFrequencyResponse  0xA20C   UNDEFINED variable         Optional
EXIF_FocalPlaneXResolution     0xA20E   RATIONAL  1                Optional
EXIF_FocalPlaneYResolution     0xA20F   RATIONAL  1                Optional
EXIF_FocalPlaneResolutionUnit  0xA210   SHORT     1                Optional
EXIF_SubjectLocation           0xA214   SHORT     2                Optional
EXIF_ExposureIndex             0xA215   RATIONAL  1                Optional
EXIF_SensingMethod             0xA217   SHORT     1                Optional
EXIF_FileSource                0xA300   UNDEFINED 1                Optional
EXIF_SceneType                 0xA301   UNDEFINED 1                Optional
EXIF_CFAPattern                0xA302   UNDEFINED variable         Optional
EXIF_CustomRendered            0xA401   SHORT     1                Optional
EXIF_ExposureMode              0xA402   SHORT     1                Recommended
EXIF_WhiteBalance              0xA403   SHORT     1                Recommended
EXIF_DigitalZoomRatio          0xA404   RATIONAL  1                Optional
EXIF_FocalLengthIn35mmFilm     0xA405   SHORT     1                Optional
EXIF_SceneCaptureType          0xA406   SHORT     1                Recommended
EXIF_GainControl               0xA407   RATIONAL  1                Optional
EXIF_Contrast                  0xA408   SHORT     1                Optional
EXIF_Saturation                0xA409   SHORT     1                Optional
EXIF_Sharpness                 0xA40A   SHORT     1                Optional
EXIF_DeviceSettingDescription  0xA40B   UNDEFINED variable         Optional
EXIF_SubjectDistanceRange      0xA40C   SHORT     1                Optional
EXIF_ImageUniqueID             0xA420   ASCII     33               Optional
EXIF_CameraOwnerName           0xA430   ASCII     variable         Optional
EXIF_BodySerialNumber          0xA431   ASCII     variable         Optional
EXIF_LensSpecification         0xA432   RATIONAL  4                Optional
EXIF_LensMake                  0xA433   ASCII     variable         Optional
EXIF_LensModel                 0xA434   ASCII     variable         Optional
EXIF_LensSerialNumber          0xA435   ASCII     variable         Optional
============================== ======== ========= ================ =============

GPS tags:

========================= ======== ========= ================ ===========
Metadata item name        Hex code Type      Number of values Optionality
========================= ======== ========= ================ ===========
EXIF_GPSVersionID         0x0000   BYTE      4                Optional
EXIF_GPSLatitudeRef       0x0001   ASCII     2                Optional
EXIF_GPSLatitude          0x0002   RATIONAL  3                Optional
EXIF_GPSLongitudeRef      0x0003   ASCII     2                Optional
EXIF_GPSLongitude         0x0004   RATIONAL  3                Optional
EXIF_GPSAltitudeRef       0x0005   BYTE      1                Optional
EXIF_GPSAltitude          0x0006   RATIONAL  1                Optional
EXIF_GPSTimeStamp         0x0007   RATIONAL  3                Optional
EXIF_GPSSatellites        0x0008   ASCII     variable         Optional
EXIF_GPSStatus            0x0009   ASCII     2                Optional
EXIF_GPSMeasureMode       0x000A   ASCII     2                Optional
EXIF_GPSDOP               0x000B   RATIONAL  1                Optional
EXIF_GPSSpeedRef          0x000C   ASCII     2                Optional
EXIF_GPSSpeed             0x000D   RATIONAL  1                Optional
EXIF_GPSTrackRef          0x000E   ASCII     2                Optional
EXIF_GPSTrack             0x000F   RATIONAL  1                Optional
EXIF_GPSImgDirectionRef   0x0010   ASCII     2                Optional
EXIF_GPSImgDirection      0x0011   RATIONAL  1                Optional
EXIF_GPSMapDatum          0x0012   ASCII     variable         Optional
EXIF_GPSDestLatitudeRef   0x0013   ASCII     2                Optional
EXIF_GPSDestLatitude      0x0014   RATIONAL  3                Optional
EXIF_GPSDestLongitudeRef  0x0015   ASCII     2                Optional
EXIF_GPSDestLongitude     0x0016   RATIONAL  3                Optional
EXIF_GPSDestBearingRef    0x0017   ASCII     2                Optional
EXIF_GPSDestBearing       0x0018   RATIONAL  1                Optional
EXIF_GPSDestDistanceRef   0x0019   ASCII     2                Optional
EXIF_GPSDestDistance      0x001A   RATIONAL  1                Optional
EXIF_GPSProcessingMethod  0x001B   UNDEFINED variable         Optional
EXIF_GPSAreaInformation   0x001C   UNDEFINED variable         Optional
EXIF_GPSDateStamp         0x001D   ASCII     11               Optional
EXIF_GPSDifferential      0x001E   SHORT     1                Optional
EXIF_GPSHPositioningError 0x001F   RATIONAL  1                Optional
========================= ======== ========= ================ ===========

FLIR metadata
-------------

.. versionadded:: 3.3

Metadata encoded according to the FLIR convention (infrared images) is available
in the ``FLIR`` metadata domain.

Metadata from the following sections is supported:

- Header
- RawData
- CameraInfo
- PaletteInfo
- GPSInfo

Consult https://exiftool.org/TagNames/FLIR.html for details.

The thermal image data, stored either as raw data or in PNG, is exposed as a
GDAL subdataset whose name is ``JPEG:"filename.jpg":FLIR_RAW_THERMAL_IMAGE``

See Also
--------

-  `Independent JPEG Group <http://www.ijg.org/>`__
-  `libjpeg-turbo <http://sourceforge.net/projects/libjpeg-turbo/>`__
-  :ref:`raster.gtiff`
-  `EXIF v2.31
   specification <http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf>`__
