Skip to content

Please add support for HDR JPG gain maps #4314

Closed

Description

@gregbenz

Feature request

What are you trying to achieve?

Add support for transcoding JPG gain maps. These images enable the ability to share images edited for modern displays that support HDR (high dynamic range). And compared to HDR-only encoding, using a gain map allows the image to be properly adapted to any display which does not support the full HDR encoding. That adaptation is critical to being able to safely share HDR images on any display - including SDR ("standard dynamic range") and monitors with limited HDR capabilities.

These HDR displays are already more common than generally known. Roughly 80% of viewers on Instagram already have HDR support and you can see examples of HDR vs standard images in my Instagram feed in the IG phone app (or using Chrome with an M1+ MacBook Pro).

When you searched for similar feature requests, what did you find that might be related?

There is a request for JXL support (#4263). While that is a great format, JPG (and AVIF) with a gain map is more practical. The JPG format is 100% backwards compatible and already widely supported. The AVIF gain map encoding will be very important and already has support in Adobe software and Chrome. We're probably a year away from having enough critical support to use AVIF, but there is clear and steady progress towards that point. There is little support for JXL and it is unclear if it will gain acceptance on the web (especially as Chrome removed support).

What would you expect the API to look like?

Should support simple transcoding of JPG (crop, resize, compress) while retaining the HDR. That means the base image and auxiliary gain map should be edited in a consistent manner, and the HDR metadata should be retained.

The Google-backed open-source libultrahdr library already supports all of this. All that is needed is some integration with libvips.

What alternatives have you considered?

There is a request for libvips to add support: libvips/libvips#3799

Please provide sample image(s) that help explain this feature

More info on HDR and gain maps.

Here is a sample image. The image will tell you if you are viewing just the SDR base image, or viewing as HDR (when using a supported browser and display, you should see blue text). The image is encoded with both the ISO and Android XMP standards (the ISO encoding is really all that is needed, the XMP encoding is redundant for backwards compatibility, but won't be important for too long).
Image

Developer resources for gain maps: https://gregbenzphotography.com/hdr/#developers

Activity

  1. lovell commented on Jan 20, 2025

    @lovell
    Owner

    This will be dependent on libvips/libvips#3799

  2. gregbenz commented on Sep 3, 2025

    @gregbenz
    Author

    @lovell libvips has added initial support for libultrahdr: libvips/libvips#4645

    This is built on mainline libultrahdr which supports transcoding of JPG (there is ongoing work to add support for AVIF / HEIF to libultrahdr).

  3. lovell commented on Dec 17, 2025

    @lovell
    Owner

    Proposed new API to expose JPEG gain maps (via libultrahdr) now that libvips v8.18.0 is available.

    withGainMap()

    Convert pixel values to HDR via .pipelineColourspace('scrgb') using the input gain map, if any, and then remove it. For JPEG output it also sets .toColourspace('scrgb') to force the creation of a new gain map.

    keepGainMap()

    Open input with gain map attached, process main image and gain map separately on a best-effort basis. Many operations might invalidate/remove the gain map, these will generate a warning and switch to withGainMap() behaviour.

    The list of operations I'd like to support where this will "just work" are:

    • resize
    • extract
    • trim
    • rotate
    • flip/flop
    • auto-orient

    Notes:

    • For output JPEG images with a gain map (reused or regenerated), libultrahdr will ignore all JPEG output properties apart from quality. The prebuilt binaries include mozjpeg so this will be the same as mozjpeg: true, with no further control.
    • libultrahdr appears to generate/attach gain maps using ISO 21496-1 format, which I think is via an APP2 MPF marker. I assume this is suitable for web browsers.
    • Verify tiled output via dzsave, which has some built-in gain map logic.
    • Determine which gain map properties, e.g. content boost, should be exposed via metadata().
    • Determine which of the same gain map properties can be updated, if any.
  4. added this to the v0.35.0 milestone on Dec 17, 2025
  5. gregbenz commented on Dec 20, 2025

    @gregbenz
    Author

    @lovell Can you confirm that keepGainMap() would be the default behavior?

    Many developers aren't yet familiar with gain maps, lack an HDR display for visual confirmation of results, or fail to use gain map source images in validation testing. So opting in to keepGainMap would likely result in a large number of transcodes defaulting to significant loss of quality (no HDR) without this being a deliberate choice by the developer.

    I believe keeping the map should be the default when the following are true:

    • source is encoded with a supported gain map format.
    • requested output is a file format which supports gain maps (JPG for now, but AVIF / HEIF support is coming to libultra)
    • operation is from your supported list (resize, extract, trim, rotate, flip, auto-orient), as these do not request deliberate alterations of the qualitative image content (unlike say applying a filter or some effect to change the image).
  6. lovell commented on Jan 4, 2026

    @lovell
    Owner

    A pre-release containing the (simpler) withGainMap() feature is now available should anyone wish to test.

    The next step is to implement keepGainMap(). This feature will be marked as experimental in its first release so should probably be opt-in until more people have tried it and had a chance to provide feedback.

  7. gregbenz commented on Jan 4, 2026

    @gregbenz
    Author

    @lovell Thank you for all the work to add support!

    I just ran a test and it will transcode a gain map to a new gain map, but the output is incorrect (resulting in significant change to the image brightness and color). I've tested a few approaches, all using withGainMap() and they all seem to fail in a similar manner.

    There are two issues:

    • The metadata has changed in several ways. This is not valid - it must remain unchanged to preserve the image appearance during transcode. The new output feels like it may just be letting the underlying libultrahdr determine values automatically.
    • The map has been altered from full res / full color (ie 1:1 scaling, 3 channels) to half res / luminosity only (1:2 scaling, 1 channel). This would be a valid thing to do, but should generally be avoided. The default should be to keep the resolution / channels of the original map. An option to reduce to lower quality would be ok (though I personally would not use it as it will often cause a significant quality penalty).

    Likely this usage needs to wait for keepGainMap(), but I wanted to note my observations. More importantly, I would not expect this result from withGainMap() - as the output is neither built from the source nor does it throw an error with my lack of an explicit / separate map source.

    Aside from the image appearance, it also strips other metadata (unrelated to the gain map). I assume this is probably a default behavior for Sharp. Could you confirm if there is a command you need to preserve metadata (such as XMP-photoshop:Main)?

  8. gregbenz commented on Jan 4, 2026

    @gregbenz
    Author

    @lovell If you need some images to test, here are sRGB and P3 test images. These include test patterns which catch most of the transcoding errors I have seen over the past few years of testing a wide range of software/services.
    gain map tests.zip

    Comparing source to the transcode on an M1 or later MacBook Pro using Chrome (or any related browser - but not Safari / FireFox) with system brightness no higher than 50% (to get a full 4 stops of headroom) works best to review the results.

  9. lovell commented on Jan 4, 2026

    @lovell
    Owner

    Thanks for taking a look at this Greg.

    The new output feels like it may just be letting the underlying libultrahdr determine values automatically.

    Yes, withGainMap is the "convert pixel values to scRGB, using (then discarding) gain map if present, re-encode with new gain map for JPEG output" approach. The provisional docs for it are available at https://github.com/lovell/sharp/blob/0.35/docs/src/content/docs/api-output.md#withgainmap

    What you describe is more in line with the yet to be implemented keepGainMap.

  10. gregbenz commented on Jan 4, 2026

    @gregbenz
    Author

    @lovell Thanks for the clarification.

    I believe the name "withGainMap" is ambiguous. Any use of libultra for input or output involves a gain map and is therefore "with" a gain map. The "keepGainMap" clearly asks to preserve the map from the input, but it may be better to rename withGainMap to something which makes it clear that a new map will be generated.

    Based on your intended use, perhaps "withGainMap" should be changed to something like "generateGainMap" or "newGainMap".

  11. 3 remaining items

  12. gregbenz commented on Feb 20, 2026

    @gregbenz
    Author

    @lovell I've created a site to help make it easy to compare two images under various levels of HDR headroom support. You can select two images (source and the transcoded result) into the page, then use the slider to see the image anywhere between the SDR result and the best possible HDR supported by the display. Click the image button to toggle between to compare source to result.

    This page should be viewed with a Chromium browser, ideally on a system supporting a full 4 stops of HDR headroom (such as an M1 or later MacBook Pro set to ~50% brightness).

    https://gregbenzphotography.com/hdr-soft-proofing-test-hdr-gain-maps/

  13. lovell commented on Feb 22, 2026

    @lovell
    Owner

    Thanks for the updates Greg, I've finally purchased an HDR monitor (LG GX7) so can start to make progress on this.

  14. gregbenz commented on Feb 22, 2026

    @gregbenz
    Author
  15. lovell commented on Apr 6, 2026

    @lovell
    Owner

    For those interested in advance testing purposes, the latest release candidate contains the proposed new keepGainMap feature.

    npm install [email protected]

    https://github.com/lovell/sharp/blob/0.35/docs/src/content/docs/api-output.md#keepgainmap

    This will be opt-in for now, at least while considered experimental.

  16. gregbenz commented on Apr 8, 2026

    @gregbenz
    Author

    @lovell I'm seeing very good results with 0.35.0-rc.2. The default results look very good to me so far. No concerns with the image results (I did log a potential bug interacting with keepMetadata). Thank you for all your efforts to incorporate gain map support into sharp!

    The performance is very good. I'm seeing a 100 megapixel Hasselblad JPG transcode to a smaller size in about 0.3s. This is considerably faster than wasm-vips (closer to 0.6s for the same operation on the same image). Would you expect wasm-vips to take ~2x longer, or is that something to report for that project?

    I do not see options to control the compression of the map itself (both base and map use a factor consistent with the single compression factor input supported now). I don't see options to scale down the map (such as to 1:2) or convert a 3-channel map to luminosity only. I don't think any of these controls are critical (and down-sampling the map is rather negative for quality), but could be useful for those who wish to optimize for smaller sizes. For reference, these are all available via wasm-vips (and may be evaluated on my wasm-vips HDR demo page).


    Sample code for others who may wish to test:

    import sharp from "sharp";
    
    const input = "input.jpg";
    
    function pipeline() {
      return sharp(input)
        .keepGainMap()
        .keepExif()
        .keepIccProfile()
        .keepXmp();
    }
    
    // 1) Simple transcode to re-compress
    await pipeline()
      .jpeg({ quality: 75 })
      .toFile("output.jpg");
    
    // 2) Resize to 50% of the original size
    const { width, height } = await sharp(input).metadata();
    
    if (!width || !height)
      throw new Error("Could not read image size.");
    
    await pipeline()
      .resize({
        width: Math.round(width / 2),
        height: Math.round(height / 2),
      })
      .jpeg({ quality: 90 })
      .toFile("output-50pct.jpg");
    
    // 3) Resize and center-crop to 500x500
    await pipeline()
      .resize({
        width: 500,
        height: 500,
        fit: "cover",
        position: "centre",
      })
      .jpeg({ quality: 90 })
      .toFile("output-500x500.jpg");
    
  17. lovell commented on Apr 11, 2026

    @lovell
    Owner

    Would you expect wasm-vips to take ~2x longer, or is that something to report for that project?

    The underlying libjpeg-turbo library does not yet support WebAssembly SIMD so this is currently expected behaviour.

    I don't see options to scale down the map (such as to 1:2) or convert a 3-channel map to luminosity only.

    For new, experimental features I generally prefer to minimise optional behaviour and use sensible defaults. As you've probably seen, the gain map scale factor in the output will be the same as the scale factor of the input, and the channel count will also remain the same. Let's see how people use this feature and what feedback we get.

    Thanks again for all your help testing this and, on a wider scale, everything you've been doing to improve HDR support everywhere.

  18. gregbenz commented on Apr 11, 2026

    @gregbenz
    Author

    Good to know libjpeg-turbo is the bottleneck there. It appears there is a long-standing feature request for it.

  19. gregbenz commented on Apr 21, 2026

    @gregbenz
    Author

    @lovell Great to see keepGainMap() getting released!

    With the end goal being for sharp to automatically use this where appropriate (ie no need to request keepGainMap), what are the logical next steps to help get there as quickly as is safe and practical? What may be done to help gain confidence that it it would be safe to automatically route images to use keepGainMap automatically?

  20. lovell commented on Jun 10, 2026

    @lovell
    Owner

    v0.35.0 now available with the (experimental for now) keepGainMap and withGainMap features. Thanks for all your help with this Greg!

    After libvips gets proper CICP support I'll look at improving the API in sharp, including keeping gain maps where possible as a default.

  21. gregbenz commented on Jun 10, 2026

    @gregbenz
    Author

    @lovell Awesome, thank you for all your efforts to incorporate it and move toward support by default when possible!

    For sharp, is there a JPG-specific block now? CICP would impact AVIF transcoding, but is not supported in the JPG codestream (can be added as a tag in an ICC profile in a JPG, but is a bit of a novelty and not important to any use case I currently know). I have been testing sharp (locally as I don't have Node on my server) and seeing good results transcoding JPG gain maps. If you have an experimental which adds default support, I'd be happy to give that a look. I suspect it should work, as this is JPG-only at this time in libultrahdr (anything AVIF would use the default handling outside libultrahdr, which should be treated like any other AVIF without a gain map at this time).

  22. lovell commented on Jun 11, 2026

    @lovell
    Owner

    My comment about the work-in-progress CICP support relates to AVIF/HEIF rather than JPEG.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions