diff --git a/changelogs/4.0.1.md b/changelogs/4.0.1.md index c8edb3b12..a15bdfc37 100644 --- a/changelogs/4.0.1.md +++ b/changelogs/4.0.1.md @@ -7,6 +7,7 @@ * **Tagged annotations (PR #1804, port of #1617).** `PdfStructureElement.addAnnotation(PdfAnnotation)` references a link or another annotation from the structure tree, as PDF/UA requires. The structure tree root gets a `/ParentTreeNextKey` entry. * **PDF/A extension schemas and Factur-X metadata (PR #1808).** `PdfWriter.addXmpSchema(XmpSchema, PdfAExtensionSchema.Schema)` adds custom XMP properties and the PDF/A extension schema that describes them to the metadata of `createXmpMetadata()`. `FacturXSchema` has the `fx` properties of ZUGFeRD and Factur-X invoices, so that a PDF/A-3 invoice with the invoice XML as an associated file passes veraPDF. * **PDF/X-4 (PR #1809).** `PdfWriter.PDFX4` creates PDF/X-4 (ISO 15930-7:2010) documents for print production, with transparency, layers and ICC based colour. OpenPDF writes PDF 1.6, the PDF/X-4 identification and media management properties in the XMP metadata and `/GTS_PDFXVersion` and `/Trapped` in the info dictionary, and requires an output intent with an ICC profile and embedded fonts. +* **CMYK colour conversion (PR #1811).** `CmykColorConverter` converts RGB colours and images to the CMYK colour space of a printing condition with its ICC profile, for example ISOnewspaper26v4 or FOGRA39, and sets that profile as the output intent. An image with transparency gets a soft mask. This prepares content for PDF/X-4 and PDF/A with a CMYK output intent. ## 🛠 Bug Fixes diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/CmykColorConverter.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/CmykColorConverter.java new file mode 100644 index 000000000..7986fc032 --- /dev/null +++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/CmykColorConverter.java @@ -0,0 +1,192 @@ +package org.openpdf.text.pdf; + +import java.awt.Color; +import java.awt.Transparency; +import java.awt.color.ColorSpace; +import java.awt.color.ICC_ColorSpace; +import java.awt.color.ICC_Profile; +import java.awt.image.BufferedImage; +import java.awt.image.ColorConvertOp; +import java.awt.image.DataBuffer; +import java.awt.image.Raster; +import java.awt.image.WritableRaster; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Objects; +import javax.imageio.ImageIO; +import org.openpdf.text.BadElementException; +import org.openpdf.text.DocumentException; +import org.openpdf.text.ExceptionConverter; +import org.openpdf.text.Image; + +/** + * Converts RGB colours and images to the CMYK colour space of a printing condition, with the ICC profile of that + * condition, for example ISOnewspaper26v4 for newspapers or Coated FOGRA39 for offset printing on coated paper. + * Print production formats such as PDF/X-4 with a CMYK output intent expect the content in that colour space, see + * {@link #setOutputIntent(PdfWriter, String, String)}. + *

+ * The conversion uses the colour management of the JDK (Little CMS) with the default rendering intent of the profile, + * usually perceptual. Colours of images are first converted to sRGB, so images with an embedded ICC profile, such as + * Adobe RGB, are converted correctly. + *

{@code
+ * CmykColorConverter converter = new CmykColorConverter(ICC_Profile.getInstance(newspaperProfileBytes));
+ * writer.setPDFXConformance(PdfWriter.PDFX4);
+ * document.open();
+ * converter.setOutputIntent(writer, "ISOnewspaper26v4", "ISO 12647-3:2013, Newspaper");
+ * document.add(converter.toCmykImage(photoBytes));
+ * cb.setColorFill(converter.toCmyk(new Color(200, 30, 30)));
+ * }
+ */ +public class CmykColorConverter { + + private static final int RGB_COMPONENTS = 3; + private static final int CMYK_COMPONENTS = 4; + private static final float MAX_USHORT = 65535f; + private static final int MAX_BYTE = 255; + + private final ICC_Profile profile; + private final ICC_ColorSpace cmykColorSpace; + private final ColorSpace srgb = ColorSpace.getInstance(ColorSpace.CS_sRGB); + + /** + * Creates a converter to the colour space of a CMYK profile. + * + * @param cmykProfile the ICC profile of the printing condition + * @throws IllegalArgumentException if the profile is not a CMYK profile + */ + public CmykColorConverter(ICC_Profile cmykProfile) { + Objects.requireNonNull(cmykProfile, "cmykProfile"); + if (cmykProfile.getColorSpaceType() != ColorSpace.TYPE_CMYK) { + throw new IllegalArgumentException("The ICC profile is not a CMYK profile."); + } + this.profile = cmykProfile; + this.cmykColorSpace = new ICC_ColorSpace(cmykProfile); + } + + /** + * Gets the CMYK profile. + * + * @return the ICC profile of the printing condition + */ + public ICC_Profile getProfile() { + return profile; + } + + /** + * Sets the output intent of the document to the CMYK profile of this converter, so that the converted colours are + * interpreted for the printing condition. For PDF/X the output intent is a {@code GTS_PDFX} intent, for PDF/A a + * {@code GTS_PDFA1} intent. + * + * @param writer the writer + * @param outputConditionIdentifier the identifier of the printing condition, for example + * {@code ISOnewspaper26v4} or {@code FOGRA39} + * @param info a description of the printing condition, or {@code null} + * @throws IOException if the profile cannot be written + */ + public void setOutputIntent(PdfWriter writer, String outputConditionIdentifier, String info) + throws IOException { + writer.setOutputIntents(outputConditionIdentifier, null, "http://www.color.org", info, profile); + } + + /** + * Converts a colour to CMYK. The alpha value of the colour is kept. + * + * @param color the colour, in sRGB + * @return the colour in the CMYK colour space of the profile + */ + public CMYKColor toCmyk(Color color) { + Objects.requireNonNull(color, "color"); + if (color instanceof CMYKColor cmykColor) { + return cmykColor; + } + WritableRaster rgb = Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, 1, 1, RGB_COMPONENTS, null); + rgb.setPixel(0, 0, new int[]{color.getRed() * 257, color.getGreen() * 257, color.getBlue() * 257}); + WritableRaster cmyk = Raster.createInterleavedRaster(DataBuffer.TYPE_USHORT, 1, 1, CMYK_COMPONENTS, null); + new ColorConvertOp(srgb, cmykColorSpace, null).filter(rgb, cmyk); + int[] values = cmyk.getPixel(0, 0, (int[]) null); + return new CMYKColor(values[0] / MAX_USHORT, values[1] / MAX_USHORT, values[2] / MAX_USHORT, + values[3] / MAX_USHORT, color.getAlpha() / (float) MAX_BYTE); + } + + /** + * Reads an image file, for example a PNG or JPEG file, and converts it to CMYK. + * + * @param imageFile the bytes of the image file + * @return the image in the CMYK colour space of the profile, with a soft mask if the image has transparency + * @throws IOException if the image cannot be read + * @throws BadElementException if the image cannot be created + */ + public Image toCmykImage(byte[] imageFile) throws IOException, BadElementException { + BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageFile)); + if (image == null) { + throw new IOException("The image format is not supported."); + } + return toCmykImage(image); + } + + /** + * Converts an image to CMYK. + * + * @param image the image + * @return the image in the CMYK colour space of the profile, with a soft mask if the image has transparency + * @throws BadElementException if the image cannot be created + */ + public Image toCmykImage(java.awt.Image image) throws BadElementException { + BufferedImage source = toBufferedImage(image); + int width = source.getWidth(); + int height = source.getHeight(); + int[] argb = source.getRGB(0, 0, width, height, null, 0, width); + + byte[] rgb = new byte[argb.length * RGB_COMPONENTS]; + byte[] alpha = new byte[argb.length]; + boolean transparent = false; + for (int i = 0; i < argb.length; i++) { + int pixel = argb[i]; + rgb[i * RGB_COMPONENTS] = (byte) (pixel >> 16); + rgb[i * RGB_COMPONENTS + 1] = (byte) (pixel >> 8); + rgb[i * RGB_COMPONENTS + 2] = (byte) pixel; + alpha[i] = (byte) (pixel >>> 24); + transparent |= (pixel >>> 24) != MAX_BYTE; + } + + WritableRaster rgbRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, RGB_COMPONENTS, + null); + rgbRaster.setDataElements(0, 0, width, height, rgb); + WritableRaster cmykRaster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, + CMYK_COMPONENTS, null); + new ColorConvertOp(srgb, cmykColorSpace, null).filter(rgbRaster, cmykRaster); + byte[] cmyk = (byte[]) cmykRaster.getDataElements(0, 0, width, height, null); + + Image result = Image.getInstance(width, height, CMYK_COMPONENTS, 8, cmyk); + if (transparent && source.getTransparency() != Transparency.OPAQUE) { + Image mask = Image.getInstance(width, height, 1, 8, alpha); + try { + mask.makeMask(); + result.setImageMask(mask); + } catch (DocumentException e) { + throw new ExceptionConverter(e); + } + } + return result; + } + + private static BufferedImage toBufferedImage(java.awt.Image image) { + Objects.requireNonNull(image, "image"); + if (image instanceof BufferedImage bufferedImage) { + return bufferedImage; + } + int width = image.getWidth(null); + int height = image.getHeight(null); + if (width <= 0 || height <= 0) { + throw new IllegalArgumentException("The image is not loaded or has no size."); + } + BufferedImage buffered = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + java.awt.Graphics2D g = buffered.createGraphics(); + try { + g.drawImage(image, 0, 0, null); + } finally { + g.dispose(); + } + return buffered; + } +} diff --git a/openpdf-core/src/test/java/org/openpdf/text/pdf/CmykColorConverterTest.java b/openpdf-core/src/test/java/org/openpdf/text/pdf/CmykColorConverterTest.java new file mode 100644 index 000000000..6042b573a --- /dev/null +++ b/openpdf-core/src/test/java/org/openpdf/text/pdf/CmykColorConverterTest.java @@ -0,0 +1,165 @@ +package org.openpdf.text.pdf; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.within; + +import java.awt.Color; +import java.awt.color.ColorSpace; +import java.awt.color.ICC_Profile; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import javax.imageio.ImageIO; +import org.junit.jupiter.api.Test; +import org.openpdf.text.Document; +import org.openpdf.text.Font; +import org.openpdf.text.Image; +import org.openpdf.text.PageSize; +import org.openpdf.text.Paragraph; +import org.verapdf.gf.model.GFModelParser; +import org.verapdf.pdfa.PDFAValidator; +import org.verapdf.pdfa.flavours.PDFAFlavour; +import org.verapdf.pdfa.results.TestAssertion; +import org.verapdf.pdfa.results.ValidationResult; +import org.verapdf.pdfa.validation.validators.ValidatorFactory; + +class CmykColorConverterTest { + + private static final String FONT = "/fonts/liberation/LiberationSerif-Regular.ttf"; + private static final float TOLERANCE = 0.15f; + + private final CmykColorConverter converter = new CmykColorConverter(TestCmykProfile.create()); + + @Test + void profileMustBeCmyk() { + assertThatThrownBy(() -> new CmykColorConverter(ICC_Profile.getInstance(ColorSpace.CS_sRGB))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void whiteHasNoInk() { + assertCmyk(converter.toCmyk(Color.WHITE), 0, 0, 0, 0); + } + + @Test + void blackIsPrintedWithBlackInk() { + CMYKColor black = converter.toCmyk(Color.BLACK); + + assertThat(black.getBlack()).isGreaterThan(0.85f); + } + + @Test + void redIsMagentaAndYellow() { + assertCmyk(converter.toCmyk(Color.RED), 0, 1, 1, 0); + } + + @Test + void alphaIsKeptAndCmykColorIsUnchanged() { + assertThat(converter.toCmyk(new Color(0, 0, 255, 128)).getAlpha()).isEqualTo(128); + CMYKColor cmyk = new CMYKColor(0.1f, 0.2f, 0.3f, 0.4f); + assertThat(converter.toCmyk(cmyk)).isSameAs(cmyk); + } + + @Test + void imageIsConvertedToCmyk() throws Exception { + BufferedImage rgb = new BufferedImage(2, 1, BufferedImage.TYPE_INT_RGB); + rgb.setRGB(0, 0, Color.RED.getRGB()); + rgb.setRGB(1, 0, Color.WHITE.getRGB()); + + Image cmyk = converter.toCmykImage(rgb); + + assertThat(cmyk.getColorspace()).isEqualTo(4); + assertThat(cmyk.getBpc()).isEqualTo(8); + assertThat(cmyk.getImageMask()).isNull(); + byte[] data = cmyk.getRawData(); + assertCmyk(new CMYKColor(data[0] & 0xFF, data[1] & 0xFF, data[2] & 0xFF, data[3] & 0xFF), 0, 1, 1, 0); + assertCmyk(new CMYKColor(data[4] & 0xFF, data[5] & 0xFF, data[6] & 0xFF, data[7] & 0xFF), 0, 0, 0, 0); + } + + @Test + void transparencyBecomesASoftMask() throws Exception { + BufferedImage argb = new BufferedImage(2, 1, BufferedImage.TYPE_INT_ARGB); + argb.setRGB(0, 0, Color.RED.getRGB()); + argb.setRGB(1, 0, new Color(0, 0, 255, 0).getRGB()); + + Image cmyk = converter.toCmykImage(argb); + + Image mask = cmyk.getImageMask(); + assertThat(mask).isNotNull(); + assertThat(mask.getRawData()).containsExactly((byte) 255, (byte) 0); + } + + @Test + void pngFileIsConverted() throws Exception { + Image cmyk = converter.toCmykImage(readResource("/GitHub-Mark-32px.png")); + + BufferedImage original = ImageIO.read(new ByteArrayInputStream(readResource("/GitHub-Mark-32px.png"))); + assertThat(cmyk.getColorspace()).isEqualTo(4); + assertThat((int) cmyk.getWidth()).isEqualTo(original.getWidth()); + assertThat(cmyk.getImageMask()).isNotNull(); + } + + @Test + void unsupportedImageFileIsRejected() { + assertThatThrownBy(() -> converter.toCmykImage(new byte[]{1, 2, 3})) + .isInstanceOf(IOException.class); + } + + @Test + void pdfA2bWithCmykOutputIntentAndConvertedContentIsCompliant() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (Document document = new Document(PageSize.A4)) { + PdfWriter writer = PdfWriter.getInstance(document, out); + writer.setPDFXConformance(PdfWriter.PDFA2B); + document.addTitle("CMYK test"); + document.open(); + converter.setOutputIntent(writer, "OpenPDF test CMYK", "Test printing condition"); + + BaseFont font = BaseFont.createFont("LiberationSerif-Regular.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, + true, readResource(FONT), null); + document.add(new Paragraph("Converted to CMYK", + new Font(font, 14, Font.NORMAL, converter.toCmyk(new Color(200, 30, 30))))); + document.add(converter.toCmykImage(readResource("/imageTest/ImageTest.jpg"))); + document.add(converter.toCmykImage(readResource("/GitHub-Mark-32px.png"))); + writer.createXmpMetadata(); + } + + try (PdfReader reader = new PdfReader(out.toByteArray())) { + PdfDictionary outputIntent = reader.getCatalog().getAsArray(PdfName.OUTPUTINTENTS).getAsDict(0); + assertThat(outputIntent.getAsName(PdfName.S)).isEqualTo(PdfName.GTS_PDFA1); + assertThat(outputIntent.get(PdfName.DESTOUTPUTPROFILE)).isNotNull(); + } + assertThat(validate(out.toByteArray(), PDFAFlavour.PDFA_2_B)).as("veraPDF PDF/A-2b violations").isEmpty(); + } + + private static void assertCmyk(CMYKColor color, float c, float m, float y, float k) { + assertThat(color.getCyan()).as("cyan").isCloseTo(c, within(TOLERANCE)); + assertThat(color.getMagenta()).as("magenta").isCloseTo(m, within(TOLERANCE)); + assertThat(color.getYellow()).as("yellow").isCloseTo(y, within(TOLERANCE)); + assertThat(color.getBlack()).as("black").isCloseTo(k, within(TOLERANCE)); + } + + private static List validate(byte[] pdf, PDFAFlavour flavour) throws Exception { + try (GFModelParser parser = GFModelParser.createModelWithFlavour(new ByteArrayInputStream(pdf), flavour)) { + PDFAValidator validator = ValidatorFactory.createValidator(flavour, false, 100); + ValidationResult result = validator.validate(parser); + return result.getTestAssertions().stream() + .filter(assertion -> assertion.getStatus() == TestAssertion.Status.FAILED) + .map(assertion -> assertion.getRuleId().getClause() + "-" + assertion.getRuleId().getTestNumber() + + ": " + assertion.getMessage()) + .distinct() + .toList(); + } + } + + private static byte[] readResource(String name) throws IOException { + try (InputStream in = CmykColorConverterTest.class.getResourceAsStream(name)) { + assertThat(in).as(name).isNotNull(); + return in.readAllBytes(); + } + } +} diff --git a/openpdf-core/src/test/java/org/openpdf/text/pdf/TestCmykProfile.java b/openpdf-core/src/test/java/org/openpdf/text/pdf/TestCmykProfile.java new file mode 100644 index 000000000..7629b944f --- /dev/null +++ b/openpdf-core/src/test/java/org/openpdf/text/pdf/TestCmykProfile.java @@ -0,0 +1,229 @@ +package org.openpdf.text.pdf; + +import java.awt.color.ICC_Profile; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** + * Creates a small CMYK ICC profile (ICC v2 output profile with Lab lookup tables) for tests, so that the tests need no + * profile file with license restrictions. The profile models a simple printing condition: CMYK is converted to sRGB + * with {@code R = (1 - C)(1 - K)} and back with full gray component replacement. It is not meant for real printing. + */ +final class TestCmykProfile { + + private static final int A2B_GRID = 5; + private static final int B2A_GRID = 17; + private static final double[] D50 = {0.9642, 1.0, 0.8249}; + + private TestCmykProfile() { + } + + static ICC_Profile create() { + return ICC_Profile.getInstance(createBytes()); + } + + static byte[] createBytes() { + List tags = new ArrayList<>(); + tags.add(new Tag("desc", textDescription("OpenPDF test CMYK"))); + tags.add(new Tag("cprt", text("No copyright, use freely"))); + tags.add(new Tag("wtpt", xyz(D50))); + tags.add(new Tag("A2B0", cmykToLab())); + tags.add(new Tag("B2A0", labToCmyk())); + + int offset = 128 + 4 + tags.size() * 12; + ByteArrayOutputStream data = new ByteArrayOutputStream(); + int[] offsets = new int[tags.size()]; + for (int i = 0; i < tags.size(); i++) { + offsets[i] = offset + data.size(); + byte[] tagData = tags.get(i).data(); + data.writeBytes(tagData); + while (data.size() % 4 != 0) { + data.write(0); + } + } + int size = offset + data.size(); + + ByteBuffer profile = ByteBuffer.allocate(size); + profile.putInt(size); + profile.putInt(0); + profile.putInt(0x02100000); + profile.put(ascii("prtr")); + profile.put(ascii("CMYK")); + profile.put(ascii("Lab ")); + profile.putShort((short) 2026).putShort((short) 1).putShort((short) 1); + profile.putShort((short) 0).putShort((short) 0).putShort((short) 0); + profile.put(ascii("acsp")); + profile.position(64); + profile.putInt(0); + profile.putInt(s15Fixed16(D50[0])).putInt(s15Fixed16(D50[1])).putInt(s15Fixed16(D50[2])); + profile.position(128); + profile.putInt(tags.size()); + for (int i = 0; i < tags.size(); i++) { + profile.put(ascii(tags.get(i).signature())); + profile.putInt(offsets[i]); + profile.putInt(tags.get(i).data().length); + } + profile.put(data.toByteArray()); + return profile.array(); + } + + private static byte[] cmykToLab() { + int nodes = (int) Math.pow(A2B_GRID, 4); + short[] clut = new short[nodes * 3]; + int n = 0; + for (int c = 0; c < A2B_GRID; c++) { + for (int m = 0; m < A2B_GRID; m++) { + for (int y = 0; y < A2B_GRID; y++) { + for (int k = 0; k < A2B_GRID; k++) { + double kk = k / (A2B_GRID - 1.0); + double r = (1 - c / (A2B_GRID - 1.0)) * (1 - kk); + double g = (1 - m / (A2B_GRID - 1.0)) * (1 - kk); + double b = (1 - y / (A2B_GRID - 1.0)) * (1 - kk); + double[] lab = srgbToLab(r, g, b); + clut[n++] = (short) Math.round(lab[0] * 652.8); + clut[n++] = (short) Math.round((lab[1] + 128) * 256); + clut[n++] = (short) Math.round((lab[2] + 128) * 256); + } + } + } + } + return lut16(4, 3, A2B_GRID, clut); + } + + private static byte[] labToCmyk() { + int nodes = B2A_GRID * B2A_GRID * B2A_GRID; + short[] clut = new short[nodes * 4]; + int n = 0; + for (int li = 0; li < B2A_GRID; li++) { + for (int ai = 0; ai < B2A_GRID; ai++) { + for (int bi = 0; bi < B2A_GRID; bi++) { + double l = li * 100.0 / (B2A_GRID - 1); + double a = ai * 255.0 / (B2A_GRID - 1) - 128; + double b = bi * 255.0 / (B2A_GRID - 1) - 128; + double[] rgb = labToSrgb(l, a, b); + double k = 1 - Math.max(rgb[0], Math.max(rgb[1], rgb[2])); + double scale = k >= 1 ? 0 : 1 / (1 - k); + clut[n++] = ushort((1 - rgb[0] - k) * scale); + clut[n++] = ushort((1 - rgb[1] - k) * scale); + clut[n++] = ushort((1 - rgb[2] - k) * scale); + clut[n++] = ushort(k); + } + } + } + return lut16(3, 4, B2A_GRID, clut); + } + + private static byte[] lut16(int inputs, int outputs, int grid, short[] clut) { + ByteBuffer lut = ByteBuffer.allocate(52 + inputs * 4 + clut.length * 2 + outputs * 4); + lut.put(ascii("mft2")); + lut.putInt(0); + lut.put((byte) inputs).put((byte) outputs).put((byte) grid).put((byte) 0); + int[] identity = {1, 0, 0, 0, 1, 0, 0, 0, 1}; + for (int value : identity) { + lut.putInt(value << 16); + } + lut.putShort((short) 2).putShort((short) 2); + for (int i = 0; i < inputs; i++) { + lut.putShort((short) 0).putShort((short) 0xFFFF); + } + for (short value : clut) { + lut.putShort(value); + } + for (int i = 0; i < outputs; i++) { + lut.putShort((short) 0).putShort((short) 0xFFFF); + } + return lut.array(); + } + + private static double[] srgbToLab(double r, double g, double b) { + double lr = linear(r); + double lg = linear(g); + double lb = linear(b); + double x = 0.4360747 * lr + 0.3850649 * lg + 0.1430804 * lb; + double y = 0.2225045 * lr + 0.7168786 * lg + 0.0606169 * lb; + double z = 0.0139322 * lr + 0.0971045 * lg + 0.7141733 * lb; + double fx = labF(x / D50[0]); + double fy = labF(y / D50[1]); + double fz = labF(z / D50[2]); + return new double[]{clamp(116 * fy - 16, 0, 100), clamp(500 * (fx - fy), -128, 127.99), + clamp(200 * (fy - fz), -128, 127.99)}; + } + + private static double[] labToSrgb(double l, double a, double b) { + double fy = (l + 16) / 116; + double fx = fy + a / 500; + double fz = fy - b / 200; + double x = labFInverse(fx) * D50[0]; + double y = labFInverse(fy) * D50[1]; + double z = labFInverse(fz) * D50[2]; + double lr = 3.1338561 * x - 1.6168667 * y - 0.4906146 * z; + double lg = -0.9787684 * x + 1.9161415 * y + 0.0334540 * z; + double lb = 0.0719453 * x - 0.2289914 * y + 1.4052427 * z; + return new double[]{gamma(lr), gamma(lg), gamma(lb)}; + } + + private static double linear(double v) { + return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); + } + + private static double gamma(double v) { + double c = clamp(v, 0, 1); + return c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055; + } + + private static double labF(double t) { + return t > 216.0 / 24389 ? Math.cbrt(t) : (24389.0 / 27 * t + 16) / 116; + } + + private static double labFInverse(double f) { + double cube = f * f * f; + return cube > 216.0 / 24389 ? cube : (116 * f - 16) * 27 / 24389; + } + + private static double clamp(double v, double min, double max) { + return Math.max(min, Math.min(max, v)); + } + + private static short ushort(double v) { + return (short) Math.round(clamp(v, 0, 1) * 65535); + } + + private static int s15Fixed16(double v) { + return (int) Math.round(v * 65536); + } + + private static byte[] xyz(double[] xyz) { + ByteBuffer tag = ByteBuffer.allocate(20); + tag.put(ascii("XYZ ")).putInt(0); + for (double v : xyz) { + tag.putInt(s15Fixed16(v)); + } + return tag.array(); + } + + private static byte[] text(String text) { + byte[] ascii = (text + "\0").getBytes(StandardCharsets.US_ASCII); + ByteBuffer tag = ByteBuffer.allocate(8 + ascii.length); + tag.put(ascii("text")).putInt(0).put(ascii); + return tag.array(); + } + + private static byte[] textDescription(String text) { + byte[] ascii = (text + "\0").getBytes(StandardCharsets.US_ASCII); + ByteBuffer tag = ByteBuffer.allocate(12 + ascii.length + 8 + 3 + 67); + tag.put(ascii("desc")).putInt(0).putInt(ascii.length).put(ascii); + tag.putInt(0).putInt(0); + tag.putShort((short) 0).put((byte) 0); + return tag.array(); + } + + private static byte[] ascii(String s) { + return s.getBytes(StandardCharsets.US_ASCII); + } + + private record Tag(String signature, byte[] data) { + } +}