You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2023/05/09 12:56:39 UTC
[commons-imaging] 02/05: Sort members
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-imaging.git
commit 4f47f79662473d6c6e02f5951c54049b3af73f03
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Tue May 9 08:38:35 2023 -0400
Sort members
---
.../org/apache/commons/imaging/ColorTools.java | 236 ++--
.../apache/commons/imaging/FormatCompliance.java | 130 +--
.../java/org/apache/commons/imaging/ImageDump.java | 42 +-
.../org/apache/commons/imaging/ImageFormat.java | 14 +-
.../org/apache/commons/imaging/ImageFormats.java | 8 +-
.../java/org/apache/commons/imaging/ImageInfo.java | 70 +-
.../org/apache/commons/imaging/ImageParser.java | 950 +++++++--------
.../commons/imaging/ImageWriteException.java | 24 +-
.../java/org/apache/commons/imaging/Imaging.java | 878 +++++++-------
.../org/apache/commons/imaging/PixelDensity.java | 90 +-
.../apache/commons/imaging/color/ColorCieLab.java | 10 +-
.../apache/commons/imaging/color/ColorCieLch.java | 10 +-
.../apache/commons/imaging/color/ColorCieLuv.java | 10 +-
.../org/apache/commons/imaging/color/ColorCmy.java | 10 +-
.../apache/commons/imaging/color/ColorCmyk.java | 10 +-
.../commons/imaging/color/ColorConversions.java | 952 +++++++--------
.../commons/imaging/color/ColorDin99Lab.java | 10 +-
.../org/apache/commons/imaging/color/ColorHsl.java | 10 +-
.../org/apache/commons/imaging/color/ColorHsv.java | 10 +-
.../commons/imaging/color/ColorHunterLab.java | 10 +-
.../org/apache/commons/imaging/color/ColorXyz.java | 10 +-
.../commons/imaging/common/BasicCParser.java | 378 +++---
.../commons/imaging/common/BinaryConstant.java | 28 +-
.../commons/imaging/common/BinaryFileParser.java | 40 +-
.../commons/imaging/common/BinaryFunctions.java | 354 +++---
.../commons/imaging/common/ByteConversions.java | 336 +++---
.../imaging/common/FastByteArrayOutputStream.java | 20 +-
.../imaging/common/GenericImageMetadata.java | 72 +-
.../commons/imaging/common/ImageBuilder.java | 170 +--
.../commons/imaging/common/ImageMetadata.java | 12 +-
.../apache/commons/imaging/common/PackBits.java | 96 +-
.../commons/imaging/common/RationalNumber.java | 314 ++---
.../apache/commons/imaging/common/ZlibDeflate.java | 38 +-
.../imaging/common/bytesource/ByteSource.java | 32 +-
.../imaging/common/bytesource/ByteSourceArray.java | 24 +-
.../imaging/common/bytesource/ByteSourceFile.java | 34 +-
.../common/bytesource/ByteSourceInputStream.java | 106 +-
.../common/itu_t4/BitArrayOutputStream.java | 40 +-
.../common/itu_t4/BitInputStreamFlexible.java | 16 +-
.../commons/imaging/common/itu_t4/HuffmanTree.java | 62 +-
.../imaging/common/itu_t4/T4AndT6Compression.java | 432 +++----
.../imaging/common/itu_t4/T4_T6_Tables.java | 42 +-
.../imaging/common/mylzw/MyBitInputStream.java | 22 +-
.../imaging/common/mylzw/MyBitOutputStream.java | 56 +-
.../imaging/common/mylzw/MyLzwCompressor.java | 218 ++--
.../imaging/common/mylzw/MyLzwDecompressor.java | 128 +--
.../commons/imaging/formats/bmp/BmpHeaderInfo.java | 32 +-
.../imaging/formats/bmp/BmpImageParser.java | 468 ++++----
.../commons/imaging/formats/bmp/BmpWriter.java | 8 +-
.../imaging/formats/bmp/BmpWriterPalette.java | 42 +-
.../commons/imaging/formats/bmp/BmpWriterRgb.java | 20 +-
.../commons/imaging/formats/bmp/PixelParser.java | 4 +-
.../imaging/formats/bmp/PixelParserRle.java | 22 +-
.../imaging/formats/dcx/DcxImageParser.java | 122 +-
.../imaging/formats/gif/GifImageMetadata.java | 26 +-
.../imaging/formats/gif/GifImageMetadataItem.java | 8 +-
.../imaging/formats/gif/GifImageParser.java | 1216 ++++++++++----------
.../commons/imaging/formats/icns/IcnsDecoder.java | 110 +-
.../imaging/formats/icns/IcnsImageParser.java | 208 ++--
.../commons/imaging/formats/icns/IcnsType.java | 136 +--
.../imaging/formats/icns/Rle24Compression.java | 6 +-
.../imaging/formats/ico/IcoImageParser.java | 424 +++----
.../imaging/formats/jpeg/JpegImageMetadata.java | 116 +-
.../imaging/formats/jpeg/JpegImageParser.java | 884 +++++++-------
.../commons/imaging/formats/jpeg/JpegUtils.java | 118 +-
.../commons/imaging/formats/jpeg/decoder/Dct.java | 66 +-
.../imaging/formats/jpeg/decoder/JpegDecoder.java | 748 ++++++------
.../formats/jpeg/decoder/YCbCrConverter.java | 14 +-
.../imaging/formats/jpeg/decoder/ZigZag.java | 10 +-
.../imaging/formats/jpeg/exif/ExifRewriter.java | 294 ++---
.../imaging/formats/jpeg/iptc/IptcBlock.java | 8 +-
.../imaging/formats/jpeg/iptc/IptcParser.java | 404 +++----
.../imaging/formats/jpeg/iptc/IptcRecord.java | 10 +-
.../imaging/formats/jpeg/iptc/IptcType.java | 4 +-
.../imaging/formats/jpeg/iptc/IptcTypeLookup.java | 6 +-
.../imaging/formats/jpeg/iptc/IptcTypes.java | 38 +-
.../formats/jpeg/iptc/JpegIptcRewriter.java | 188 +--
.../formats/jpeg/iptc/PhotoshopApp13Data.java | 16 +-
.../formats/jpeg/segments/App14Segment.java | 8 +-
.../imaging/formats/jpeg/segments/App2Segment.java | 20 +-
.../imaging/formats/jpeg/segments/DhtSegment.java | 12 +-
.../imaging/formats/jpeg/segments/DqtSegment.java | 4 +-
.../formats/jpeg/segments/GenericSegment.java | 12 +-
.../imaging/formats/jpeg/segments/JfifSegment.java | 10 +-
.../imaging/formats/jpeg/segments/Segment.java | 10 +-
.../imaging/formats/jpeg/segments/SofnSegment.java | 16 +-
.../imaging/formats/jpeg/segments/SosSegment.java | 18 +-
.../formats/jpeg/segments/UnknownSegment.java | 8 +-
.../imaging/formats/jpeg/xmp/JpegRewriter.java | 204 ++--
.../imaging/formats/jpeg/xmp/JpegXmpRewriter.java | 100 +-
.../imaging/formats/pcx/PcxImageParser.java | 274 ++---
.../commons/imaging/formats/pcx/RleWriter.java | 22 +-
.../imaging/formats/png/GammaCorrection.java | 8 +-
.../commons/imaging/formats/png/PhysicalScale.java | 24 +-
.../commons/imaging/formats/png/PngColorType.java | 58 +-
.../apache/commons/imaging/formats/png/PngCrc.java | 44 +-
.../commons/imaging/formats/png/PngImageInfo.java | 24 +-
.../imaging/formats/png/PngImageParser.java | 844 +++++++-------
.../commons/imaging/formats/png/PngText.java | 40 +-
.../commons/imaging/formats/png/PngWriter.java | 228 ++--
.../commons/imaging/formats/png/ScanExpediter.java | 34 +-
.../formats/png/ScanExpediterInterlaced.java | 14 +-
.../imaging/formats/png/chunks/PngChunk.java | 16 +-
.../imaging/formats/png/chunks/PngChunkItxt.java | 10 +-
.../imaging/formats/png/chunks/PngChunkPlte.java | 20 +-
.../imaging/formats/png/chunks/PngChunkText.java | 10 +-
.../imaging/formats/png/chunks/PngChunkZtxt.java | 10 +-
.../imaging/formats/png/chunks/PngTextChunk.java | 4 +-
.../commons/imaging/formats/pnm/FileInfo.java | 62 +-
.../commons/imaging/formats/pnm/PamFileInfo.java | 152 +--
.../commons/imaging/formats/pnm/PbmFileInfo.java | 32 +-
.../commons/imaging/formats/pnm/PgmFileInfo.java | 22 +-
.../imaging/formats/pnm/PnmImageParser.java | 216 ++--
.../commons/imaging/formats/pnm/PpmFileInfo.java | 22 +-
.../imaging/formats/pnm/WhiteSpaceReader.java | 32 +-
.../imaging/formats/psd/ImageResourceType.java | 8 +-
.../commons/imaging/formats/psd/PsdHeaderInfo.java | 8 +-
.../imaging/formats/psd/PsdImageParser.java | 736 ++++++------
.../formats/psd/dataparsers/DataParser.java | 8 +-
.../formats/psd/dataparsers/DataParserBitmap.java | 10 +-
.../formats/psd/dataparsers/DataParserCmyk.java | 10 +-
.../psd/dataparsers/DataParserGrayscale.java | 10 +-
.../formats/psd/dataparsers/DataParserIndexed.java | 10 +-
.../formats/psd/dataparsers/DataParserLab.java | 10 +-
.../formats/psd/dataparsers/DataParserRgb.java | 10 +-
.../formats/psd/dataparsers/DataParserStub.java | 10 +-
.../imaging/formats/rgbe/RgbeImageParser.java | 68 +-
.../commons/imaging/formats/rgbe/RgbeInfo.java | 162 +--
.../commons/imaging/formats/tiff/TiffContents.java | 76 +-
.../imaging/formats/tiff/TiffDirectory.java | 630 +++++-----
.../commons/imaging/formats/tiff/TiffElement.java | 24 +-
.../commons/imaging/formats/tiff/TiffField.java | 470 ++++----
.../imaging/formats/tiff/TiffImageData.java | 182 +--
.../imaging/formats/tiff/TiffImageMetadata.java | 340 +++---
.../imaging/formats/tiff/TiffImageParser.java | 980 ++++++++--------
.../imaging/formats/tiff/TiffRasterData.java | 174 +--
.../imaging/formats/tiff/TiffRasterDataFloat.java | 186 +--
.../imaging/formats/tiff/TiffRasterDataInt.java | 166 +--
.../imaging/formats/tiff/TiffRasterStatistics.java | 42 +-
.../commons/imaging/formats/tiff/TiffReader.java | 432 +++----
.../commons/imaging/formats/tiff/TiffTags.java | 90 +-
.../formats/tiff/constants/GpsTagConstants.java | 34 +-
.../formats/tiff/constants/TiffDirectoryType.java | 42 +-
.../tiff/constants/TiffPlanarConfiguration.java | 28 +-
.../formats/tiff/datareaders/BitInputStream.java | 16 +-
.../formats/tiff/datareaders/ImageDataReader.java | 588 +++++-----
.../imaging/formats/tiff/fieldtypes/FieldType.java | 36 +-
.../PhotometricInterpreter.java | 6 +-
.../PhotometricInterpreterLogLuv.java | 152 +--
.../PhotometricInterpreterYCbCr.java | 20 +-
.../floatingpoint/PaletteEntry.java | 22 +-
.../floatingpoint/PaletteEntryForRange.java | 46 +-
.../floatingpoint/PaletteEntryForValue.java | 20 +-
.../floatingpoint/PhotometricInterpreterFloat.java | 104 +-
.../imaging/formats/tiff/taginfos/TagInfo.java | 46 +-
.../formats/tiff/taginfos/TagInfoAscii.java | 10 +-
.../imaging/formats/tiff/taginfos/TagInfoByte.java | 10 +-
.../formats/tiff/taginfos/TagInfoBytes.java | 10 +-
.../formats/tiff/taginfos/TagInfoDouble.java | 8 +-
.../formats/tiff/taginfos/TagInfoDoubles.java | 8 +-
.../formats/tiff/taginfos/TagInfoFloat.java | 8 +-
.../formats/tiff/taginfos/TagInfoFloats.java | 8 +-
.../formats/tiff/taginfos/TagInfoGpsText.java | 30 +-
.../imaging/formats/tiff/taginfos/TagInfoLong.java | 14 +-
.../formats/tiff/taginfos/TagInfoLongOrIFD.java | 8 +-
.../formats/tiff/taginfos/TagInfoLongs.java | 8 +-
.../formats/tiff/taginfos/TagInfoRational.java | 8 +-
.../formats/tiff/taginfos/TagInfoRationals.java | 8 +-
.../formats/tiff/taginfos/TagInfoSLong.java | 8 +-
.../formats/tiff/taginfos/TagInfoSLongs.java | 8 +-
.../formats/tiff/taginfos/TagInfoSRational.java | 8 +-
.../formats/tiff/taginfos/TagInfoSRationals.java | 8 +-
.../formats/tiff/taginfos/TagInfoSShort.java | 8 +-
.../formats/tiff/taginfos/TagInfoSShorts.java | 8 +-
.../formats/tiff/taginfos/TagInfoShort.java | 8 +-
.../formats/tiff/taginfos/TagInfoShortOrLong.java | 4 +-
.../taginfos/TagInfoShortOrLongOrRational.java | 6 +-
.../tiff/taginfos/TagInfoShortOrRational.java | 4 +-
.../formats/tiff/taginfos/TagInfoShorts.java | 8 +-
.../formats/tiff/write/TiffImageWriterBase.java | 284 ++---
.../tiff/write/TiffImageWriterLossless.java | 144 +--
.../formats/tiff/write/TiffImageWriterLossy.java | 26 +-
.../formats/tiff/write/TiffOutputDirectory.java | 454 ++++----
.../formats/tiff/write/TiffOutputField.java | 92 +-
.../imaging/formats/tiff/write/TiffOutputItem.java | 46 +-
.../imaging/formats/tiff/write/TiffOutputSet.java | 182 +--
.../formats/tiff/write/TiffOutputSummary.java | 28 +-
.../imaging/formats/wbmp/WbmpImageParser.java | 156 +--
.../imaging/formats/xbm/XbmImageParser.java | 180 +--
.../imaging/formats/xpm/XpmImageParser.java | 434 +++----
.../commons/imaging/icc/CachingInputStream.java | 20 +-
.../apache/commons/imaging/icc/IccProfileInfo.java | 8 +-
.../commons/imaging/icc/IccProfileParser.java | 144 +--
.../org/apache/commons/imaging/icc/IccTag.java | 68 +-
.../apache/commons/imaging/icc/IccTagDataType.java | 4 +-
.../org/apache/commons/imaging/icc/IccTagType.java | 4 +-
.../apache/commons/imaging/icc/IccTagTypes.java | 8 +-
.../org/apache/commons/imaging/internal/Debug.java | 254 ++--
.../imaging/internal/ImageParserFactory.java | 36 +-
.../apache/commons/imaging/palette/ColorCount.java | 10 +-
.../apache/commons/imaging/palette/ColorGroup.java | 16 +-
.../commons/imaging/palette/ColorSpaceSubset.java | 30 +-
.../apache/commons/imaging/palette/Dithering.java | 68 +-
.../imaging/palette/LongestAxisMedianCut.java | 50 +-
.../imaging/palette/MedianCutQuantizer.java | 34 +-
.../apache/commons/imaging/palette/Palette.java | 14 +-
.../commons/imaging/palette/PaletteFactory.java | 556 ++++-----
.../commons/imaging/palette/QuantizedPalette.java | 12 +-
.../commons/imaging/palette/SimplePalette.java | 10 +-
.../org/apache/commons/imaging/ImageDumpTest.java | 16 +-
.../org/apache/commons/imaging/ImagingTest.java | 64 +-
.../org/apache/commons/imaging/TestImageInfo.java | 42 +-
.../commons/imaging/TestImageWriteException.java | 14 +-
.../commons/imaging/color/ColorCieLabTest.java | 20 +-
.../commons/imaging/color/ColorCieLchTest.java | 18 +-
.../commons/imaging/color/ColorCieLuvTest.java | 22 +-
.../apache/commons/imaging/color/ColorCmyTest.java | 30 +-
.../commons/imaging/color/ColorCmykTest.java | 20 +-
.../imaging/color/ColorConversionsTest.java | 64 +-
.../apache/commons/imaging/color/ColorHslTest.java | 38 +-
.../apache/commons/imaging/color/ColorHsvTest.java | 16 +-
.../commons/imaging/color/ColorHunterLabTest.java | 20 +-
.../apache/commons/imaging/color/ColorXyzTest.java | 22 +-
.../imaging/common/BinaryFileFunctionsTest.java | 18 +-
.../commons/imaging/common/ImageBuilderTest.java | 110 +-
.../common/bytesource/ByteSourceDataTest.java | 40 +-
.../common/bytesource/ByteSourceImageTest.java | 152 +--
.../imaging/common/bytesource/ByteSourceTest.java | 28 +-
.../commons/imaging/examples/ImageReadExample.java | 26 +-
.../imaging/examples/WriteExifMetadataExample.java | 16 +-
.../imaging/examples/tiff/ReadTagsAndImages.java | 644 +++++------
.../imaging/examples/tiff/SurveyTiffFile.java | 398 +++----
.../imaging/examples/tiff/SurveyTiffFolder.java | 160 +--
.../commons/imaging/formats/bmp/BmpBaseTest.java | 10 +-
.../imaging/formats/bmp/BmpImageParserTest.java | 18 +-
.../commons/imaging/formats/bmp/BmpReadTest.java | 30 +-
.../imaging/formats/bmp/BmpRoundtripTest.java | 126 +-
.../commons/imaging/formats/dcx/DcxBaseTest.java | 10 +-
.../commons/imaging/formats/dcx/DcxReadTest.java | 14 +-
.../commons/imaging/formats/gif/GifBaseTest.java | 42 +-
.../commons/imaging/formats/gif/GifReadTest.java | 140 +--
.../commons/imaging/formats/icns/IcnsBaseTest.java | 10 +-
.../commons/imaging/formats/icns/IcnsReadTest.java | 28 +-
.../imaging/formats/icns/IcnsRoundTripTest.java | 288 ++---
.../commons/imaging/formats/ico/IcoBaseTest.java | 10 +-
.../commons/imaging/formats/ico/IcoReadTest.java | 14 +-
.../imaging/formats/ico/IcoRoundtripTest.java | 456 ++++----
.../commons/imaging/formats/jpeg/JpegBaseTest.java | 10 +-
.../imaging/formats/jpeg/decoder/DctTest.java | 156 +--
.../imaging/formats/jpeg/exif/ExifBaseTest.java | 26 +-
.../imaging/formats/jpeg/exif/ExifRewriteTest.java | 380 +++---
.../formats/jpeg/exif/MicrosoftTagTest.java | 86 +-
.../formats/jpeg/exif/SpecificExifTagTest.java | 18 +-
.../imaging/formats/jpeg/iptc/IptcBaseTest.java | 34 +-
.../formats/jpeg/iptc/IptcFullDiscardTest.java | 12 +-
.../imaging/formats/jpeg/iptc/IptcParserTest.java | 42 +-
.../imaging/formats/jpeg/iptc/IptcUpdateTest.java | 98 +-
.../formats/jpeg/segments/App2SegmentTest.java | 8 +-
.../formats/jpeg/segments/SosSegmentTest.java | 14 +-
.../imaging/formats/jpeg/xmp/JpegXmpBaseTest.java | 38 +-
.../commons/imaging/formats/pam/PamBaseTest.java | 4 +-
.../commons/imaging/formats/pcx/PcxBaseTest.java | 4 +-
.../commons/imaging/formats/png/PngBaseTest.java | 4 +-
.../commons/imaging/formats/png/PngReadTest.java | 44 +-
.../png/PngWithInvalidPngChunkSizeTest.java | 14 +-
.../imaging/formats/png/PngWritePredictorTest.java | 10 +-
.../imaging/formats/png/PngWriteReadTest.java | 68 +-
.../formats/png/chunks/PngChunkScalTest.java | 44 +-
.../imaging/formats/pnm/PnmImageParserTest.java | 52 +-
.../commons/imaging/formats/psd/PsdBaseTest.java | 4 +-
.../commons/imaging/formats/rgbe/RgbeBaseTest.java | 4 +-
.../formats/tiff/TiffAlphaRoundTripTest.java | 62 +-
.../commons/imaging/formats/tiff/TiffBaseTest.java | 4 +-
.../imaging/formats/tiff/TiffCcittTest.java | 90 +-
.../tiff/TiffFloatingPointMultivariableTest.java | 256 ++---
.../formats/tiff/TiffFloatingPointReadTest.java | 40 +-
.../tiff/TiffFloatingPointRoundTripTest.java | 232 ++--
.../commons/imaging/formats/tiff/TiffLzwTest.java | 92 +-
.../formats/tiff/TiffRasterDataIntTest.java | 204 ++--
.../imaging/formats/tiff/TiffRasterDataTest.java | 184 +--
.../formats/tiff/TiffRasterStatisticsTest.java | 40 +-
.../formats/tiff/TiffRoundTripInt32Test.java | 110 +-
.../formats/tiff/TiffShortIntRoundTripTest.java | 102 +-
.../imaging/formats/tiff/TiffSubImageTest.java | 42 +-
.../tiff/fieldtypes/FieldTypeRationalTest.java | 14 +-
.../PhotometricInterpreterLogLuvTest.java | 46 +-
.../floatingpoint/PaletteEntryForRangeTest.java | 106 +-
.../floatingpoint/PaletteEntryForValueTest.java | 42 +-
.../PhotometricInterpreterFloatTest.java | 124 +-
.../commons/imaging/formats/wbmp/WbmpBaseTest.java | 4 +-
.../commons/imaging/formats/xbm/XbmBaseTest.java | 4 +-
.../commons/imaging/formats/xpm/XpmBaseTest.java | 4 +-
.../imaging/palette/PaletteQuantizationTest.java | 88 +-
.../commons/imaging/roundtrip/ImageAsserts.java | 34 +-
.../commons/imaging/roundtrip/RoundtripBase.java | 8 +-
.../commons/imaging/roundtrip/TestImages.java | 44 +-
.../imaging/test/util/FileSystemTraversal.java | 84 +-
297 files changed, 15506 insertions(+), 15506 deletions(-)
diff --git a/src/main/java/org/apache/commons/imaging/ColorTools.java b/src/main/java/org/apache/commons/imaging/ColorTools.java
index c34c051a..e7de8058 100644
--- a/src/main/java/org/apache/commons/imaging/ColorTools.java
+++ b/src/main/java/org/apache/commons/imaging/ColorTools.java
@@ -41,48 +41,116 @@ import java.io.IOException;
*/
public class ColorTools {
- public BufferedImage correctImage(final BufferedImage src, final File file)
- throws ImageReadException, IOException {
- final ICC_Profile icc = Imaging.getICCProfile(file);
- if (icc == null) {
- return src;
- }
+ public BufferedImage convertBetweenColorSpaces(BufferedImage bi,
+ final ColorSpace from, final ColorSpace to) {
+ final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
+ RenderingHints.VALUE_RENDER_QUALITY);
+ hints.put(RenderingHints.KEY_COLOR_RENDERING,
+ RenderingHints.VALUE_COLOR_RENDER_QUALITY);
+ hints.put(RenderingHints.KEY_DITHERING,
+ RenderingHints.VALUE_DITHER_ENABLE);
- final ICC_ColorSpace cs = new ICC_ColorSpace(icc);
+ final ColorConvertOp op = new ColorConvertOp(from, to, hints);
- return convertFromColorSpace(src, cs);
+ bi = relabelColorSpace(bi, from);
+
+ BufferedImage result = op.filter(bi, null);
+
+ result = relabelColorSpace(result, to);
+
+ return result;
}
- public BufferedImage relabelColorSpace(final BufferedImage bi, final ICC_Profile profile)
- throws ImagingOpException {
- final ICC_ColorSpace cs = new ICC_ColorSpace(profile);
+ public BufferedImage convertBetweenColorSpacesX2(BufferedImage bi,
+ final ColorSpace from, final ColorSpace to) {
+ final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
+ RenderingHints.VALUE_RENDER_QUALITY);
+ hints.put(RenderingHints.KEY_COLOR_RENDERING,
+ RenderingHints.VALUE_COLOR_RENDER_QUALITY);
+ hints.put(RenderingHints.KEY_DITHERING,
+ RenderingHints.VALUE_DITHER_ENABLE);
+
+ // bi = relabelColorSpace(bi, cs);
+ // dumpColorSpace("\tcs_sRGB", cs_sRGB);
+ // dumpColorSpace("\tColorModel.getRGBdefaultc",
+ // ColorModel.getRGBdefault().getColorSpace());
+
+ bi = relabelColorSpace(bi, from);
+ final ColorConvertOp op = new ColorConvertOp(from, to, hints);
+ bi = op.filter(bi, null);
+
+ bi = relabelColorSpace(bi, from);
+
+ bi = op.filter(bi, null);
+
+ bi = relabelColorSpace(bi, to);
+
+ return bi;
- return relabelColorSpace(bi, cs);
}
- public BufferedImage relabelColorSpace(final BufferedImage bi, final ColorSpace cs)
- throws ImagingOpException {
- // This does not do the conversion. It tries to relabel the
- // BufferedImage
- // with its actual (presumably correct) Colorspace.
- // use this when the image is mislabeled, presumably having been
- // wrongly assumed to be sRGB
+ public BufferedImage convertBetweenICCProfiles(final BufferedImage bi, final ICC_Profile from, final ICC_Profile to) {
+ final ICC_ColorSpace csFrom = new ICC_ColorSpace(from);
+ final ICC_ColorSpace csTo = new ICC_ColorSpace(to);
- final ColorModel cm = deriveColorModel(bi, cs);
+ return convertBetweenColorSpaces(bi, csFrom, csTo);
+ }
- return relabelColorSpace(bi, cm);
+ protected BufferedImage convertFromColorSpace(final BufferedImage bi, final ColorSpace from) {
+ final ColorModel srgbCM = ColorModel.getRGBdefault();
+ return convertBetweenColorSpaces(bi, from, srgbCM.getColorSpace());
+ }
+
+ public BufferedImage convertToColorSpace(final BufferedImage bi, final ColorSpace to) {
+ final ColorSpace from = bi.getColorModel().getColorSpace();
+ final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
+ RenderingHints.VALUE_RENDER_QUALITY);
+ hints.put(RenderingHints.KEY_COLOR_RENDERING,
+ RenderingHints.VALUE_COLOR_RENDER_QUALITY);
+ hints.put(RenderingHints.KEY_DITHERING,
+ RenderingHints.VALUE_DITHER_ENABLE);
+
+ final ColorConvertOp op = new ColorConvertOp(from, to, hints);
+
+ BufferedImage result = op.filter(bi, null);
+
+ result = relabelColorSpace(result, to);
+
+ return result;
}
- public BufferedImage relabelColorSpace(final BufferedImage bi, final ColorModel cm)
- throws ImagingOpException {
- // This does not do the conversion. It tries to relabel the
- // BufferedImage
- // with its actual (presumably correct) Colorspace.
- // use this when the image is mislabeled, presumably having been
- // wrongly assumed to be sRGB
+ public BufferedImage convertToICCProfile(final BufferedImage bi, final ICC_Profile to) {
+ final ICC_ColorSpace csTo = new ICC_ColorSpace(to);
+ return convertToColorSpace(bi, csTo);
+ }
- return new BufferedImage(cm, bi.getRaster(), false, null);
+ public BufferedImage convertTosRGB(final BufferedImage bi) {
+ final ColorModel srgbCM = ColorModel.getRGBdefault();
+ return convertToColorSpace(bi, srgbCM.getColorSpace());
+ }
+
+ public BufferedImage correctImage(final BufferedImage src, final File file)
+ throws ImageReadException, IOException {
+ final ICC_Profile icc = Imaging.getICCProfile(file);
+ if (icc == null) {
+ return src;
+ }
+
+ final ICC_ColorSpace cs = new ICC_ColorSpace(icc);
+
+ return convertFromColorSpace(src, cs);
+ }
+
+ private int countBitsInMask(int i) {
+ int count = 0;
+ while (i != 0) {
+ count += (i & 1);
+ // uses the unsigned version of java's right shift operator,
+ // so that left hand bits are zeroed.
+ i >>>= 1;
+ }
+ return count;
}
public ColorModel deriveColorModel(final BufferedImage bi, final ColorSpace cs)
@@ -146,104 +214,36 @@ public class ColorTools {
throw new ImagingOpException("Could not clone unknown ColorModel Type.");
}
- private int countBitsInMask(int i) {
- int count = 0;
- while (i != 0) {
- count += (i & 1);
- // uses the unsigned version of java's right shift operator,
- // so that left hand bits are zeroed.
- i >>>= 1;
- }
- return count;
- }
-
- public BufferedImage convertToColorSpace(final BufferedImage bi, final ColorSpace to) {
- final ColorSpace from = bi.getColorModel().getColorSpace();
-
- final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
- RenderingHints.VALUE_RENDER_QUALITY);
- hints.put(RenderingHints.KEY_COLOR_RENDERING,
- RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- hints.put(RenderingHints.KEY_DITHERING,
- RenderingHints.VALUE_DITHER_ENABLE);
-
- final ColorConvertOp op = new ColorConvertOp(from, to, hints);
-
- BufferedImage result = op.filter(bi, null);
-
- result = relabelColorSpace(result, to);
-
- return result;
- }
-
- public BufferedImage convertTosRGB(final BufferedImage bi) {
- final ColorModel srgbCM = ColorModel.getRGBdefault();
- return convertToColorSpace(bi, srgbCM.getColorSpace());
- }
-
- protected BufferedImage convertFromColorSpace(final BufferedImage bi, final ColorSpace from) {
- final ColorModel srgbCM = ColorModel.getRGBdefault();
- return convertBetweenColorSpaces(bi, from, srgbCM.getColorSpace());
- }
-
- public BufferedImage convertBetweenICCProfiles(final BufferedImage bi, final ICC_Profile from, final ICC_Profile to) {
- final ICC_ColorSpace csFrom = new ICC_ColorSpace(from);
- final ICC_ColorSpace csTo = new ICC_ColorSpace(to);
-
- return convertBetweenColorSpaces(bi, csFrom, csTo);
- }
+ public BufferedImage relabelColorSpace(final BufferedImage bi, final ColorModel cm)
+ throws ImagingOpException {
+ // This does not do the conversion. It tries to relabel the
+ // BufferedImage
+ // with its actual (presumably correct) Colorspace.
+ // use this when the image is mislabeled, presumably having been
+ // wrongly assumed to be sRGB
- public BufferedImage convertToICCProfile(final BufferedImage bi, final ICC_Profile to) {
- final ICC_ColorSpace csTo = new ICC_ColorSpace(to);
- return convertToColorSpace(bi, csTo);
+ return new BufferedImage(cm, bi.getRaster(), false, null);
}
- public BufferedImage convertBetweenColorSpacesX2(BufferedImage bi,
- final ColorSpace from, final ColorSpace to) {
- final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
- RenderingHints.VALUE_RENDER_QUALITY);
- hints.put(RenderingHints.KEY_COLOR_RENDERING,
- RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- hints.put(RenderingHints.KEY_DITHERING,
- RenderingHints.VALUE_DITHER_ENABLE);
-
- // bi = relabelColorSpace(bi, cs);
- // dumpColorSpace("\tcs_sRGB", cs_sRGB);
- // dumpColorSpace("\tColorModel.getRGBdefaultc",
- // ColorModel.getRGBdefault().getColorSpace());
-
- bi = relabelColorSpace(bi, from);
- final ColorConvertOp op = new ColorConvertOp(from, to, hints);
- bi = op.filter(bi, null);
-
- bi = relabelColorSpace(bi, from);
-
- bi = op.filter(bi, null);
+ public BufferedImage relabelColorSpace(final BufferedImage bi, final ColorSpace cs)
+ throws ImagingOpException {
+ // This does not do the conversion. It tries to relabel the
+ // BufferedImage
+ // with its actual (presumably correct) Colorspace.
+ // use this when the image is mislabeled, presumably having been
+ // wrongly assumed to be sRGB
- bi = relabelColorSpace(bi, to);
+ final ColorModel cm = deriveColorModel(bi, cs);
- return bi;
+ return relabelColorSpace(bi, cm);
}
- public BufferedImage convertBetweenColorSpaces(BufferedImage bi,
- final ColorSpace from, final ColorSpace to) {
- final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
- RenderingHints.VALUE_RENDER_QUALITY);
- hints.put(RenderingHints.KEY_COLOR_RENDERING,
- RenderingHints.VALUE_COLOR_RENDER_QUALITY);
- hints.put(RenderingHints.KEY_DITHERING,
- RenderingHints.VALUE_DITHER_ENABLE);
-
- final ColorConvertOp op = new ColorConvertOp(from, to, hints);
-
- bi = relabelColorSpace(bi, from);
-
- BufferedImage result = op.filter(bi, null);
-
- result = relabelColorSpace(result, to);
+ public BufferedImage relabelColorSpace(final BufferedImage bi, final ICC_Profile profile)
+ throws ImagingOpException {
+ final ICC_ColorSpace cs = new ICC_ColorSpace(profile);
- return result;
+ return relabelColorSpace(bi, cs);
}
}
diff --git a/src/main/java/org/apache/commons/imaging/FormatCompliance.java b/src/main/java/org/apache/commons/imaging/FormatCompliance.java
index bd39b374..4611f491 100644
--- a/src/main/java/org/apache/commons/imaging/FormatCompliance.java
+++ b/src/main/java/org/apache/commons/imaging/FormatCompliance.java
@@ -32,8 +32,12 @@ public class FormatCompliance {
private static final Logger LOGGER = Logger.getLogger(FormatCompliance.class.getName());
+ public static FormatCompliance getDefault() {
+ return new FormatCompliance("ignore", false);
+ }
private final boolean failOnError;
private final String description;
+
private final List<String> comments = new ArrayList<>();
public FormatCompliance(final String description) {
@@ -46,10 +50,6 @@ public class FormatCompliance {
this.failOnError = failOnError;
}
- public static FormatCompliance getDefault() {
- return new FormatCompliance("ignore", false);
- }
-
public void addComment(final String comment) throws ImageReadException {
comments.add(comment);
if (failOnError) {
@@ -61,67 +61,6 @@ public class FormatCompliance {
addComment(comment + ": " + getValueDescription(value));
}
- @Override
- public String toString() {
- final StringWriter sw = new StringWriter();
- final PrintWriter pw = new PrintWriter(sw);
-
- dump(pw);
-
- return sw.getBuffer().toString();
- }
-
- public void dump() {
- try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
- dump(pw);
- pw.flush();
- sw.flush();
- LOGGER.fine(sw.toString());
- } catch (final IOException e) {
- LOGGER.log(Level.SEVERE, e.getMessage(), e);
- }
- }
-
- public void dump(final PrintWriter pw) {
- pw.println("Format Compliance: " + description);
-
- if (comments.isEmpty()) {
- pw.println("\t" + "No comments.");
- } else {
- for (int i = 0; i < comments.size(); i++) {
- pw.println("\t" + (i + 1) + ": " + comments.get(i));
- }
- }
- pw.println("");
- pw.flush();
- }
-
- private String getValueDescription(final int value) {
- return value + " (" + Integer.toHexString(value) + ")";
- }
-
- public boolean compareBytes(final String name, final byte[] expected, final byte[] actual)
- throws ImageReadException {
- if (expected.length != actual.length) {
- addComment(name + ": " + "Unexpected length: (expected: "
- + expected.length + ", actual: " + actual.length + ")");
- return false;
- }
- for (int i = 0; i < expected.length; i++) {
- // System.out.println("expected: "
- // + getValueDescription(expected[i]) + ", actual: "
- // + getValueDescription(actual[i]) + ")");
- if (expected[i] != actual[i]) {
- addComment(name + ": " + "Unexpected value: (expected: "
- + getValueDescription(expected[i]) + ", actual: "
- + getValueDescription(actual[i]) + ")");
- return false;
- }
- }
-
- return true;
- }
-
public boolean checkBounds(final String name, final int min, final int max, final int actual)
throws ImageReadException {
if ((actual < min) || (actual > max)) {
@@ -165,4 +104,65 @@ public class FormatCompliance {
addComment(result.toString());
return false;
}
+
+ public boolean compareBytes(final String name, final byte[] expected, final byte[] actual)
+ throws ImageReadException {
+ if (expected.length != actual.length) {
+ addComment(name + ": " + "Unexpected length: (expected: "
+ + expected.length + ", actual: " + actual.length + ")");
+ return false;
+ }
+ for (int i = 0; i < expected.length; i++) {
+ // System.out.println("expected: "
+ // + getValueDescription(expected[i]) + ", actual: "
+ // + getValueDescription(actual[i]) + ")");
+ if (expected[i] != actual[i]) {
+ addComment(name + ": " + "Unexpected value: (expected: "
+ + getValueDescription(expected[i]) + ", actual: "
+ + getValueDescription(actual[i]) + ")");
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public void dump() {
+ try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
+ dump(pw);
+ pw.flush();
+ sw.flush();
+ LOGGER.fine(sw.toString());
+ } catch (final IOException e) {
+ LOGGER.log(Level.SEVERE, e.getMessage(), e);
+ }
+ }
+
+ public void dump(final PrintWriter pw) {
+ pw.println("Format Compliance: " + description);
+
+ if (comments.isEmpty()) {
+ pw.println("\t" + "No comments.");
+ } else {
+ for (int i = 0; i < comments.size(); i++) {
+ pw.println("\t" + (i + 1) + ": " + comments.get(i));
+ }
+ }
+ pw.println("");
+ pw.flush();
+ }
+
+ private String getValueDescription(final int value) {
+ return value + " (" + Integer.toHexString(value) + ")";
+ }
+
+ @Override
+ public String toString() {
+ final StringWriter sw = new StringWriter();
+ final PrintWriter pw = new PrintWriter(sw);
+
+ dump(pw);
+
+ return sw.getBuffer().toString();
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/ImageDump.java b/src/main/java/org/apache/commons/imaging/ImageDump.java
index 25397da9..f19d0885 100644
--- a/src/main/java/org/apache/commons/imaging/ImageDump.java
+++ b/src/main/java/org/apache/commons/imaging/ImageDump.java
@@ -57,27 +57,6 @@ public class ImageDump {
}
}
- public void dumpColorSpace(final String prefix, final ColorSpace cs) {
- LOGGER.fine(prefix + ": " + "type: " + cs.getType() + " ("
- + colorSpaceTypeToName(cs) + ")");
-
- if (!(cs instanceof ICC_ColorSpace)) {
- LOGGER.fine(prefix + ": " + "Unknown ColorSpace: "
- + cs.getClass().getName());
- return;
- }
-
- final ICC_ColorSpace iccColorSpace = (ICC_ColorSpace) cs;
- final ICC_Profile iccProfile = iccColorSpace.getProfile();
-
- final byte[] bytes = iccProfile.getData();
-
- final IccProfileParser parser = new IccProfileParser();
-
- final IccProfileInfo info = parser.getICCProfileInfo(bytes);
- info.dump(prefix);
- }
-
public void dump(final BufferedImage src) {
dump("", src);
}
@@ -100,4 +79,25 @@ public class ImageDump {
}
}
+ public void dumpColorSpace(final String prefix, final ColorSpace cs) {
+ LOGGER.fine(prefix + ": " + "type: " + cs.getType() + " ("
+ + colorSpaceTypeToName(cs) + ")");
+
+ if (!(cs instanceof ICC_ColorSpace)) {
+ LOGGER.fine(prefix + ": " + "Unknown ColorSpace: "
+ + cs.getClass().getName());
+ return;
+ }
+
+ final ICC_ColorSpace iccColorSpace = (ICC_ColorSpace) cs;
+ final ICC_Profile iccProfile = iccColorSpace.getProfile();
+
+ final byte[] bytes = iccProfile.getData();
+
+ final IccProfileParser parser = new IccProfileParser();
+
+ final IccProfileInfo info = parser.getICCProfileInfo(bytes);
+ info.dump(prefix);
+ }
+
}
diff --git a/src/main/java/org/apache/commons/imaging/ImageFormat.java b/src/main/java/org/apache/commons/imaging/ImageFormat.java
index bc97071c..a7aad3b1 100644
--- a/src/main/java/org/apache/commons/imaging/ImageFormat.java
+++ b/src/main/java/org/apache/commons/imaging/ImageFormat.java
@@ -22,12 +22,7 @@ package org.apache.commons.imaging;
*/
public interface ImageFormat {
- /**
- * Gets the name of this {@link ImageFormat}.
- *
- * @return String name
- */
- String getName();
+ String getDefaultExtension();
/**
* Gets the file extension associated with this {@link ImageFormat}.
@@ -36,5 +31,10 @@ public interface ImageFormat {
*/
String[] getExtensions();
- String getDefaultExtension();
+ /**
+ * Gets the name of this {@link ImageFormat}.
+ *
+ * @return String name
+ */
+ String getName();
}
diff --git a/src/main/java/org/apache/commons/imaging/ImageFormats.java b/src/main/java/org/apache/commons/imaging/ImageFormats.java
index 2d339749..d68a8d4e 100644
--- a/src/main/java/org/apache/commons/imaging/ImageFormats.java
+++ b/src/main/java/org/apache/commons/imaging/ImageFormats.java
@@ -50,8 +50,8 @@ public enum ImageFormats implements ImageFormat {
}
@Override
- public String getName() {
- return name();
+ public String getDefaultExtension() {
+ return this.extensions != null ? this.extensions[0] : null;
}
@Override
@@ -60,7 +60,7 @@ public enum ImageFormats implements ImageFormat {
}
@Override
- public String getDefaultExtension() {
- return this.extensions != null ? this.extensions[0] : null;
+ public String getName() {
+ return name();
}
}
diff --git a/src/main/java/org/apache/commons/imaging/ImageInfo.java b/src/main/java/org/apache/commons/imaging/ImageInfo.java
index c6ed5c7c..cc13f604 100644
--- a/src/main/java/org/apache/commons/imaging/ImageInfo.java
+++ b/src/main/java/org/apache/commons/imaging/ImageInfo.java
@@ -137,6 +137,10 @@ public class ImageInfo {
this.compressionAlgorithm = compressionAlgorithm;
}
+ public void dump() {
+ LOGGER.fine(toString());
+ }
+
/**
* Returns the bits per pixel of the image data.
*
@@ -146,6 +150,15 @@ public class ImageInfo {
return bitsPerPixel;
}
+ /**
+ * Returns the {@link org.apache.commons.imaging.ImageInfo.ColorType} of the image.
+ *
+ * @return image color type.
+ */
+ public ColorType getColorType() {
+ return colorType;
+ }
+
/**
* Returns a list of comments from the image file.
*
@@ -157,6 +170,15 @@ public class ImageInfo {
return new ArrayList<>(comments);
}
+ /**
+ * Returns a description of the compression algorithm, if any.
+ *
+ * @return compression algorithm description.
+ */
+ public CompressionAlgorithm getCompressionAlgorithm() {
+ return compressionAlgorithm;
+ }
+
/**
* Returns the image file format, ie. ImageFormat.IMAGE_FORMAT_PNG.
*
@@ -169,6 +191,15 @@ public class ImageInfo {
return format;
}
+ /**
+ * Returns a description of the file format, ie. format version.
+ *
+ * @return file format description.
+ */
+ public String getFormatDetails() {
+ return formatDetails;
+ }
+
/**
* Returns a string with the name of the image file format.
*
@@ -283,16 +314,12 @@ public class ImageInfo {
}
/**
- * Returns the {@link org.apache.commons.imaging.ImageInfo.ColorType} of the image.
+ * Returns true if the image has transparency.
*
- * @return image color type.
+ * @return {@code true} if the image has transparency, {@code false} otherwise.
*/
- public ColorType getColorType() {
- return colorType;
- }
-
- public void dump() {
- LOGGER.fine(toString());
+ public boolean isTransparent() {
+ return transparent;
}
@Override
@@ -341,24 +368,6 @@ public class ImageInfo {
}
- /**
- * Returns a description of the file format, ie. format version.
- *
- * @return file format description.
- */
- public String getFormatDetails() {
- return formatDetails;
- }
-
- /**
- * Returns true if the image has transparency.
- *
- * @return {@code true} if the image has transparency, {@code false} otherwise.
- */
- public boolean isTransparent() {
- return transparent;
- }
-
/**
* Returns true if the image uses a palette.
*
@@ -368,13 +377,4 @@ public class ImageInfo {
return usesPalette;
}
- /**
- * Returns a description of the compression algorithm, if any.
- *
- * @return compression algorithm description.
- */
- public CompressionAlgorithm getCompressionAlgorithm() {
- return compressionAlgorithm;
- }
-
}
diff --git a/src/main/java/org/apache/commons/imaging/ImageParser.java b/src/main/java/org/apache/commons/imaging/ImageParser.java
index 2ba98549..1ae7beac 100644
--- a/src/main/java/org/apache/commons/imaging/ImageParser.java
+++ b/src/main/java/org/apache/commons/imaging/ImageParser.java
@@ -122,315 +122,165 @@ public abstract class ImageParser<T extends ImagingParameters<T>> extends Binary
}
/**
- * Get a default parameters instance for this parser.
- * @return default parameters instance
- */
- public abstract T getDefaultParameters();
-
- /**
- * Get image metadata from the specified byte source. Format-specific
- * ImageParser implementations are expected to return a valid
- * IImageMetadata object or to throw an ImageReadException if unable
- * to process the specified byte source.
+ * Indicates whether the ImageParser implementation can accept
+ * the specified file based on its extension.
*
- * @param byteSource A valid byte source.
- * @return A valid, potentially subject-matter-specific implementation of
- * the IImageMetadata interface describing the content extracted
- * from the source content.
- * @throws ImageReadException In the event that the ByteSource
- * content does not conform to the format of the specific parser
- * implementation.
- * @throws IOException In the event of unsuccessful data read operation.
+ * @param file An valid file reference.
+ * @return If the parser can accept the format, true; otherwise, false.
*/
- public final ImageMetadata getMetadata(final ByteSource byteSource) throws ImageReadException, IOException {
- return getMetadata(byteSource, null);
+ public boolean canAcceptExtension(final File file) {
+ return canAcceptExtension(file.getName());
}
/**
- * Get image metadata from the specified byte source. Format-specific
- * ImageParser implementations are expected to return a valid
- * IImageMetadata object or to throw an ImageReadException if unable
- * to process the specified byte source.
- *
- * <p>The params argument provides a mechanism for individual
- * implementations to pass optional information into the parser.
- * Not all formats will require this capability. Because the
- * base class may call this method with a null params argument,
- * implementations should <strong>always</strong> include logic
- * for ignoring null input.
+ * Indicates whether the ImageParser implementation can accept
+ * the specified file name based on its extension.
*
- * @param byteSource A valid byte source.
- * @param params Optional instructions for special-handling or
- * interpretation of the input data (null objects are permitted and
- * must be supported by implementations).
- * @return A valid, potentially subject-matter-specific implementation of
- * the IImageMetadata interface describing the content extracted
- * from the source content.
- * @throws ImageReadException In the event that the ByteSource
- * content does not conform to the format of the specific parser
- * implementation.
- * @throws IOException In the event of unsuccessful data read operation.
+ * @param fileName A valid string giving a file name or file path.
+ * @return If the parser can accept the format, true; otherwise, false.
*/
- public abstract ImageMetadata getMetadata(ByteSource byteSource, T params)
- throws ImageReadException, IOException;
+ public final boolean canAcceptExtension(final String fileName) {
+ final String[] extensions = getAcceptedExtensions();
+ if (extensions == null) {
+ return true;
+ }
- /**
- * Get image metadata from the specified array of bytes. Format-specific
- * ImageParser implementations are expected to return a valid
- * IImageMetadata object or to throw an ImageReadException if unable
- * to process the specified data.
- *
- * @param bytes A valid array of bytes
- * @return A valid, potentially subject-matter-specific implementation of
- * the IImageMetadata interface describing the content extracted
- * from the source content.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful data read operation.
- */
- public final ImageMetadata getMetadata(final byte[] bytes) throws ImageReadException, IOException {
- return getMetadata(bytes, null);
+ final int index = fileName.lastIndexOf('.');
+ if (index >= 0) {
+ final String fileNameExtension = fileName.substring(index + 1).toLowerCase(Locale.ENGLISH);
+ for (final String extension : extensions) {
+ if (extension.equals(fileNameExtension)) {
+ return true;
+ }
+ }
+ }
+ return false;
}
/**
- * Get image metadata from the specified array of bytes. Format-specific
- * ImageParser implementations are expected to return a valid
- * IImageMetadata object or to throw an ImageReadException if unable
- * to process the specified data.
- *
- * <p>The params argument provides a mechanism for individual
- * implementations to pass optional information into the parser.
- * Not all formats will require this capability. Because the
- * base class may call this method with a null params argument,
- * implementations should <strong>always</strong> include logic
- * for ignoring null input.
+ * Indicates whether the ImageParser implementation can accept
+ * the specified format
*
- * @param bytes A valid array of bytes
- * @param params Optional instructions for special-handling or
- * interpretation of the input data (null objects are permitted and
- * must be supported by implementations).
- * @return A valid image metadata object describing the content extracted
- * from the specified content.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful data read operation.
+ * @param type An instance of ImageFormat.
+ * @return If the parser can accept the format, true; otherwise, false.
*/
- public final ImageMetadata getMetadata(final byte[] bytes, final T params)
- throws ImageReadException, IOException {
- return getMetadata(new ByteSourceArray(bytes), params);
+ public boolean canAcceptType(final ImageFormat type) {
+ final ImageFormat[] types = getAcceptedTypes();
+
+ for (final ImageFormat type2 : types) {
+ if (type2.equals(type)) {
+ return true;
+ }
+ }
+ return false;
}
/**
- * Get image metadata from the specified file. Format-specific
- * ImageParser implementations are expected to return a valid
- * IImageMetadata object or to throw an ImageReadException if unable
- * to process the specified data.
+ * Write the ImageInfo and format-specific information for the image
+ * content of the specified byte array to a string.
*
- * @param file A valid reference to a file.
- * @return A valid image metadata object describing the content extracted
- * from the specified content.
+ * @param bytes A valid array of bytes.
+ * @return A valid string.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
- * @throws IOException In the event of unsuccessful file read or
- * access operation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public final ImageMetadata getMetadata(final File file) throws ImageReadException, IOException {
- return getMetadata(file, null);
+ public final String dumpImageFile(final byte[] bytes) throws ImageReadException, IOException {
+ return dumpImageFile(new ByteSourceArray(bytes));
}
/**
- * Get image metadata from the specified file. Format-specific
- * ImageParser implementations are expected to return a valid
- * IImageMetadata object or to throw an ImageReadException if unable
- * to process the specified data.
- *
- * <p>The params argument provides a mechanism for individual
- * implementations to pass optional information into the parser.
- * Not all formats will require this capability. Because the
- * base class may call this method with a null params argument,
- * implementations should <strong>always</strong> include logic
- * for ignoring null input.
+ * Write the ImageInfo and format-specific information for the image
+ * content of the specified byte source to a string.
*
- * @param file A valid reference to a file.
- * @param params Optional instructions for special-handling or
- * interpretation of the input data (null objects are permitted and
- * must be supported by implementations).
- * @return A valid image metadata object describing the content extracted
- * from the specified content.
+ * @param byteSource A valid byte source.
+ * @return A valid string.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
- * @throws IOException In the event of unsuccessful file read or
- * access operation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public final ImageMetadata getMetadata(final File file, final T params)
+ public final String dumpImageFile(final ByteSource byteSource)
throws ImageReadException, IOException {
- if (LOGGER.isLoggable(Level.FINEST)) {
- LOGGER.finest(getName() + ".getMetadata" + ": " + file.getName());
- }
+ final StringWriter sw = new StringWriter();
+ final PrintWriter pw = new PrintWriter(sw);
- if (!canAcceptExtension(file)) {
- return null;
- }
+ dumpImageFile(pw, byteSource);
- return getMetadata(new ByteSourceFile(file), params);
+ pw.flush();
+
+ return sw.toString();
}
/**
- * Get image information from the specified ByteSource. Format-specific
- * ImageParser implementations are expected to return a valid
- * ImageInfo object or to throw an ImageReadException if unable
- * to process the specified data.
- *
- * <p>The params argument provides a mechanism for individual
- * implementations to pass optional information into the parser.
- * Not all formats will require this capability. Because the
- * base class may call this method with a null params argument,
- * implementations should <strong>always</strong> include logic
- * for ignoring null input.
+ * Write the ImageInfo and format-specific information for the image
+ * content of the specified file to a string.
*
- * @param byteSource A valid ByteSource object
- * @param params Optional instructions for special-handling or interpretation
- * of the input data (null objects are permitted and
- * must be supported by implementations).
- * @return A valid image information object describing the content extracted
- * from the specified data.
+ * @param file A valid file reference.
+ * @return A valid string.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
- * @throws IOException In the event of unsuccessful data access operation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public abstract ImageInfo getImageInfo(ByteSource byteSource, T params)
- throws ImageReadException, IOException;
+ public final String dumpImageFile(final File file) throws ImageReadException, IOException {
+ if (!canAcceptExtension(file)) {
+ return null;
+ }
- /**
- * Get image information from the specified ByteSource. Format-specific
- * ImageParser implementations are expected to return a valid
- * ImageInfo object or to throw an ImageReadException if unable
- * to process the specified data.
- *
- * @param byteSource A valid ByteSource object
- * @return A valid image information object describing the content extracted
- * from the specified data.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful data
- * access operation.
- */
- public final ImageInfo getImageInfo(final ByteSource byteSource) throws ImageReadException, IOException {
- return getImageInfo(byteSource, null);
- }
+ if (LOGGER.isLoggable(Level.FINEST)) {
+ LOGGER.finest(getName() + ": " + file.getName());
+ }
- /**
- * Get image information from the specified array of bytes. Format-specific
- * ImageParser implementations are expected to return a valid
- * ImageInfo object or to throw an ImageReadException if unable
- * to process the specified data.
- * <p>The params argument provides a mechanism for individual
- * implementations to pass optional information into the parser.
- * Not all formats will require this capability. Because the
- * base class may call this method with a null params argument,
- * implementations should <strong>always</strong> include logic
- * for ignoring null input.
- *
- * @param bytes A valid array of bytes
- * @param params Optional instructions for special-handling or
- * interpretation of the input data (null objects are permitted and
- * must be supported by implementations).
- * @return A valid image information object describing the content extracted
- * from the specified data.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful data
- * access operation.
- */
- public final ImageInfo getImageInfo(final byte[] bytes, final T params)
- throws ImageReadException, IOException {
- return getImageInfo(new ByteSourceArray(bytes), params);
+ return dumpImageFile(new ByteSourceFile(file));
}
/**
- * Get image information from the specified file Format-specific
- * ImageParser implementations are expected to return a valid
- * ImageInfo object or to throw an ImageReadException if unable
- * to process the specified data.
- * <p>The params argument provides a mechanism for individual
- * implementations to pass optional information into the parser.
- * Not all formats will require this capability. Because the
- * base class may call this method with a null params argument,
- * implementations should <strong>always</strong> include logic
- * for ignoring null input.
+ * Write the ImageInfo and format-specific information for the image
+ * content of the specified byte source to a PrintWriter
*
- * @param file A valid File object
- * @param params Optional instructions for special-handling or
- * interpretation of the input data (null objects are permitted and
- * must be supported by implementations).
- * @return A valid image information object describing the content extracted
- * from the specified data.
+ * @param pw print writer used for writing the ImageInfo
+ * @param byteSource A valid byte source.
+ * @return A valid PrintWriter.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
- * @throws IOException In the event of unsuccessful file read or
- * access operation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public final ImageInfo getImageInfo(final File file, final T params)
+ public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
throws ImageReadException, IOException {
- if (!canAcceptExtension(file)) {
- return null;
- }
-
- return getImageInfo(new ByteSourceFile(file), params);
+ return false;
}
/**
- * Determines the format compliance of the content of the supplied byte
- * source based on rules provided by a specific implementation.
+ * Get an array of all accepted extensions
*
- * @param byteSource A valid instance of ByteSource
- * @return true if the content is format-compliant; otherwise, false
- * @throws ImageReadException may be thrown by sub-classes
- * @throws IOException may be thrown by sub-classes
+ * @return A valid array of one or more elements.
*/
- public FormatCompliance getFormatCompliance(final ByteSource byteSource)
- throws ImageReadException, IOException {
- return null;
- }
+ protected abstract String[] getAcceptedExtensions();
/**
- * Determines the format compliance of the content of the supplied byte
- * array based on rules provided by a specific implementation.
+ * Get an array of ImageFormat objects describing all accepted types
*
- * @param bytes A valid byte array.
- * @return A valid FormatCompliance object.
- * @throws ImageReadException may be thrown by sub-classes
- * @throws IOException may be thrown by sub-classes
+ * @return A valid array of one or more elements.
*/
- public final FormatCompliance getFormatCompliance(final byte[] bytes)
- throws ImageReadException, IOException {
- return getFormatCompliance(new ByteSourceArray(bytes));
- }
+ protected abstract ImageFormat[] getAcceptedTypes();
/**
- * Determines the format compliance of the specified file based on
- * rules provided by a specific implementation.
+ * Gets all images specified by the byte array (some
+ * formats may include multiple images within a single data source).
*
- * @param file A valid reference to a file.
- * @return A valid format compliance object.
- * @throws ImageReadException may be thrown by sub-classes
- * @throws IOException may be thrown by sub-classes
+ * @param bytes A valid byte array
+ * @return A valid (potentially empty) list of BufferedImage objects.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public final FormatCompliance getFormatCompliance(final File file)
+ public final List<BufferedImage> getAllBufferedImages(final byte[] bytes)
throws ImageReadException, IOException {
- if (!canAcceptExtension(file)) {
- return null;
- }
-
- return getFormatCompliance(new ByteSourceFile(file));
+ return getAllBufferedImages(new ByteSourceArray(bytes));
}
/**
@@ -456,22 +306,6 @@ public abstract class ImageParser<T extends ImagingParameters<T>> extends Binary
return result;
}
- /**
- * Gets all images specified by the byte array (some
- * formats may include multiple images within a single data source).
- *
- * @param bytes A valid byte array
- * @return A valid (potentially empty) list of BufferedImage objects.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
- */
- public final List<BufferedImage> getAllBufferedImages(final byte[] bytes)
- throws ImageReadException, IOException {
- return getAllBufferedImages(new ByteSourceArray(bytes));
- }
-
/**
* Gets all images specified by indicated file (some
* formats may include multiple images within a single data source).
@@ -492,42 +326,42 @@ public abstract class ImageParser<T extends ImagingParameters<T>> extends Binary
}
/**
- * Gets a buffered image specified by the byte source (for
+ * Gets a buffered image specified by the byte array (for
* sources that specify multiple images, choice of which image
* is returned is implementation dependent).
*
- * @param byteSource A valid instance of ByteSource
- * @param params Optional instructions for special-handling or
- * interpretation of the input data (null objects are permitted and
- * must be supported by implementations).
+ * @param bytes A valid byte array
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data (null objects are permitted and
+ * must be supported by implementations).
* @return A valid instance of BufferedImage.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
* @throws IOException In the event of unsuccessful read or access operation.
*/
- public abstract BufferedImage getBufferedImage(ByteSource byteSource, T params)
- throws ImageReadException, IOException;
+ public final BufferedImage getBufferedImage(final byte[] bytes, final T params)
+ throws ImageReadException, IOException {
+ return getBufferedImage(new ByteSourceArray(bytes), params);
+ }
/**
- * Gets a buffered image specified by the byte array (for
+ * Gets a buffered image specified by the byte source (for
* sources that specify multiple images, choice of which image
* is returned is implementation dependent).
*
- * @param bytes A valid byte array
- * @param params Optional instructions for special-handling or
- * interpretation of the input data (null objects are permitted and
- * must be supported by implementations).
+ * @param byteSource A valid instance of ByteSource
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data (null objects are permitted and
+ * must be supported by implementations).
* @return A valid instance of BufferedImage.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
* @throws IOException In the event of unsuccessful read or access operation.
*/
- public final BufferedImage getBufferedImage(final byte[] bytes, final T params)
- throws ImageReadException, IOException {
- return getBufferedImage(new ByteSourceArray(bytes), params);
- }
+ public abstract BufferedImage getBufferedImage(ByteSource byteSource, T params)
+ throws ImageReadException, IOException;
/**
* Gets a buffered image specified by the indicated file (for
@@ -553,112 +387,90 @@ public abstract class ImageParser<T extends ImagingParameters<T>> extends Binary
return getBufferedImage(new ByteSourceFile(file), params);
}
-
/**
- * Writes the content of a BufferedImage to the specified output
- * stream.
- *
- * <p>The params argument provides a mechanism for individual
- * implementations to pass optional information into the parser.
- * Not all formats will support this capability. Currently,
- * some of the parsers do not check for null arguments.</p>
+ * Get an instance of IBufferedImageFactory based on the presence
+ * of a specification for ImagingConstants..BUFFERED_IMAGE_FACTORY
+ * within the supplied params.
*
- * @param src An image giving the source content for output
- * @param os A valid output stream for storing the formatted image
- * @param params optional parameters, defining format-specific instructions for output
- * (such as selections for data compression, color models, etc.)
- * @throws ImageWriteException In the event that the output format
- * cannot handle the input image or invalid params are specified.
- * @throws IOException In the event of an write error from
- * the output stream.
+ * @param params optional parameters.
+ * @return A valid instance of an implementation of a IBufferedImageFactory.
*/
- public void writeImage(final BufferedImage src, final OutputStream os, final T params)
- throws ImageWriteException, IOException {
- throw new ImageWriteException("This image format (" + getName() + ") cannot be written.");
+ protected BufferedImageFactory getBufferedImageFactory(final T params) {
+ if (params == null) {
+ return new SimpleBufferedImageFactory();
+ }
+
+ final BufferedImageFactory result = params.getBufferedImageFactory();
+
+ if (null != result) {
+ return result;
+ }
+
+ return new SimpleBufferedImageFactory();
}
/**
- * Get the size of the image described by the specified byte array.
+ * Get the default extension for the format specified by an implementation
+ * of ImageParser. Some parsers can support more than one extension
+ * (i.e. .JPEG, .JPG; .TIF, .TIFF, etc.).
*
- * @param bytes A valid byte array.
- * @return A valid instance of Dimension.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @return A valid string.
+ */
+ public abstract String getDefaultExtension();
+
+ /**
+ * Get a default parameters instance for this parser.
+ * @return default parameters instance
*/
- public final Dimension getImageSize(final byte[] bytes) throws ImageReadException, IOException {
- return getImageSize(bytes, null);
- }
+ public abstract T getDefaultParameters();
/**
- * Get the size of the image described by the specified byte array.
+ * Determines the format compliance of the content of the supplied byte
+ * array based on rules provided by a specific implementation.
*
- * @param bytes A valid byte array.
- * @param params Optional instructions for special-handling or
- * interpretation of the input data.
- * @return A valid instance of Dimension.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @param bytes A valid byte array.
+ * @return A valid FormatCompliance object.
+ * @throws ImageReadException may be thrown by sub-classes
+ * @throws IOException may be thrown by sub-classes
*/
- public final Dimension getImageSize(final byte[] bytes, final T params)
+ public final FormatCompliance getFormatCompliance(final byte[] bytes)
throws ImageReadException, IOException {
- return getImageSize(new ByteSourceArray(bytes), params);
+ return getFormatCompliance(new ByteSourceArray(bytes));
}
/**
- * Get the size of the image described by the specified file.
+ * Determines the format compliance of the content of the supplied byte
+ * source based on rules provided by a specific implementation.
*
- * @param file A valid reference to a file.
- * @return A valid instance of Dimension.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @param byteSource A valid instance of ByteSource
+ * @return true if the content is format-compliant; otherwise, false
+ * @throws ImageReadException may be thrown by sub-classes
+ * @throws IOException may be thrown by sub-classes
*/
- public final Dimension getImageSize(final File file) throws ImageReadException, IOException {
- return getImageSize(file, null);
+ public FormatCompliance getFormatCompliance(final ByteSource byteSource)
+ throws ImageReadException, IOException {
+ return null;
}
+
/**
- * Get the size of the image described by the specified file.
+ * Determines the format compliance of the specified file based on
+ * rules provided by a specific implementation.
*
- * @param file A valid reference to a file.
- * @param params Optional instructions for special-handling or
- * interpretation of the input data.
- * @return A valid instance of Dimension.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @param file A valid reference to a file.
+ * @return A valid format compliance object.
+ * @throws ImageReadException may be thrown by sub-classes
+ * @throws IOException may be thrown by sub-classes
*/
- public final Dimension getImageSize(final File file, final T params)
+ public final FormatCompliance getFormatCompliance(final File file)
throws ImageReadException, IOException {
-
if (!canAcceptExtension(file)) {
return null;
}
- return getImageSize(new ByteSourceFile(file), params);
+ return getFormatCompliance(new ByteSourceFile(file));
}
- /**
- * Get the size of the image described by the specified ByteSource.
- *
- * @param byteSource A valid reference to a ByteSource.
- * @param params Optional instructions for special-handling or
- * interpretation of the input data.
- * @return A valid instance of Dimension.
- * @throws ImageReadException In the event that the specified content
- * does not conform to the format of the specific
- * parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
- */
- public abstract Dimension getImageSize(ByteSource byteSource, T params)
- throws ImageReadException, IOException;
-
/**
* Get an array of bytes describing the International Color Consortium (ICC)
* specification for the color space of the image contained in the
@@ -694,6 +506,23 @@ public abstract class ImageParser<T extends ImagingParameters<T>> extends Binary
return getICCProfileBytes(new ByteSourceArray(bytes), params);
}
+ /**
+ * Get an array of bytes describing the International Color Consortium (ICC)
+ * specification for the color space of the image contained in the
+ * input byteSource. Not all formats support ICC profiles.
+ *
+ * @param byteSource A valid ByteSource.
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data.
+ * @return If available, a valid array of bytes; otherwise, a null
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
+ */
+ public abstract byte[] getICCProfileBytes(ByteSource byteSource, T params)
+ throws ImageReadException, IOException;
+
/**
* Get an array of bytes describing the International Color Consortium (ICC)
* specification for the color space of the image contained in the
@@ -738,205 +567,376 @@ public abstract class ImageParser<T extends ImagingParameters<T>> extends Binary
}
/**
- * Get an array of bytes describing the International Color Consortium (ICC)
- * specification for the color space of the image contained in the
- * input byteSource. Not all formats support ICC profiles.
+ * Get image information from the specified array of bytes. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * ImageInfo object or to throw an ImageReadException if unable
+ * to process the specified data.
+ * <p>The params argument provides a mechanism for individual
+ * implementations to pass optional information into the parser.
+ * Not all formats will require this capability. Because the
+ * base class may call this method with a null params argument,
+ * implementations should <strong>always</strong> include logic
+ * for ignoring null input.
*
- * @param byteSource A valid ByteSource.
+ * @param bytes A valid array of bytes
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data (null objects are permitted and
+ * must be supported by implementations).
+ * @return A valid image information object describing the content extracted
+ * from the specified data.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful data
+ * access operation.
+ */
+ public final ImageInfo getImageInfo(final byte[] bytes, final T params)
+ throws ImageReadException, IOException {
+ return getImageInfo(new ByteSourceArray(bytes), params);
+ }
+
+ /**
+ * Get image information from the specified ByteSource. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * ImageInfo object or to throw an ImageReadException if unable
+ * to process the specified data.
+ *
+ * @param byteSource A valid ByteSource object
+ * @return A valid image information object describing the content extracted
+ * from the specified data.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful data
+ * access operation.
+ */
+ public final ImageInfo getImageInfo(final ByteSource byteSource) throws ImageReadException, IOException {
+ return getImageInfo(byteSource, null);
+ }
+
+ /**
+ * Get image information from the specified ByteSource. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * ImageInfo object or to throw an ImageReadException if unable
+ * to process the specified data.
+ *
+ * <p>The params argument provides a mechanism for individual
+ * implementations to pass optional information into the parser.
+ * Not all formats will require this capability. Because the
+ * base class may call this method with a null params argument,
+ * implementations should <strong>always</strong> include logic
+ * for ignoring null input.
+ *
+ * @param byteSource A valid ByteSource object
+ * @param params Optional instructions for special-handling or interpretation
+ * of the input data (null objects are permitted and
+ * must be supported by implementations).
+ * @return A valid image information object describing the content extracted
+ * from the specified data.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful data access operation.
+ */
+ public abstract ImageInfo getImageInfo(ByteSource byteSource, T params)
+ throws ImageReadException, IOException;
+
+ /**
+ * Get image information from the specified file Format-specific
+ * ImageParser implementations are expected to return a valid
+ * ImageInfo object or to throw an ImageReadException if unable
+ * to process the specified data.
+ * <p>The params argument provides a mechanism for individual
+ * implementations to pass optional information into the parser.
+ * Not all formats will require this capability. Because the
+ * base class may call this method with a null params argument,
+ * implementations should <strong>always</strong> include logic
+ * for ignoring null input.
+ *
+ * @param file A valid File object
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data (null objects are permitted and
+ * must be supported by implementations).
+ * @return A valid image information object describing the content extracted
+ * from the specified data.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful file read or
+ * access operation.
+ */
+ public final ImageInfo getImageInfo(final File file, final T params)
+ throws ImageReadException, IOException {
+ if (!canAcceptExtension(file)) {
+ return null;
+ }
+
+ return getImageInfo(new ByteSourceFile(file), params);
+ }
+
+ /**
+ * Get the size of the image described by the specified byte array.
+ *
+ * @param bytes A valid byte array.
+ * @return A valid instance of Dimension.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
+ */
+ public final Dimension getImageSize(final byte[] bytes) throws ImageReadException, IOException {
+ return getImageSize(bytes, null);
+ }
+
+ /**
+ * Get the size of the image described by the specified byte array.
+ *
+ * @param bytes A valid byte array.
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data.
+ * @return A valid instance of Dimension.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
+ */
+ public final Dimension getImageSize(final byte[] bytes, final T params)
+ throws ImageReadException, IOException {
+ return getImageSize(new ByteSourceArray(bytes), params);
+ }
+
+
+ /**
+ * Get the size of the image described by the specified ByteSource.
+ *
+ * @param byteSource A valid reference to a ByteSource.
* @param params Optional instructions for special-handling or
* interpretation of the input data.
- * @return If available, a valid array of bytes; otherwise, a null
+ * @return A valid instance of Dimension.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
* @throws IOException In the event of unsuccessful read or access operation.
*/
- public abstract byte[] getICCProfileBytes(ByteSource byteSource, T params)
+ public abstract Dimension getImageSize(ByteSource byteSource, T params)
throws ImageReadException, IOException;
/**
- * Write the ImageInfo and format-specific information for the image
- * content of the specified byte array to a string.
+ * Get the size of the image described by the specified file.
*
- * @param bytes A valid array of bytes.
- * @return A valid string.
+ * @param file A valid reference to a file.
+ * @return A valid instance of Dimension.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
* @throws IOException In the event of unsuccessful read or access operation.
*/
- public final String dumpImageFile(final byte[] bytes) throws ImageReadException, IOException {
- return dumpImageFile(new ByteSourceArray(bytes));
+ public final Dimension getImageSize(final File file) throws ImageReadException, IOException {
+ return getImageSize(file, null);
}
-
/**
- * Write the ImageInfo and format-specific information for the image
- * content of the specified file to a string.
+ * Get the size of the image described by the specified file.
*
- * @param file A valid file reference.
- * @return A valid string.
+ * @param file A valid reference to a file.
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data.
+ * @return A valid instance of Dimension.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
* @throws IOException In the event of unsuccessful read or access operation.
*/
- public final String dumpImageFile(final File file) throws ImageReadException, IOException {
+ public final Dimension getImageSize(final File file, final T params)
+ throws ImageReadException, IOException {
+
if (!canAcceptExtension(file)) {
return null;
}
- if (LOGGER.isLoggable(Level.FINEST)) {
- LOGGER.finest(getName() + ": " + file.getName());
- }
-
- return dumpImageFile(new ByteSourceFile(file));
+ return getImageSize(new ByteSourceFile(file), params);
}
+
/**
- * Write the ImageInfo and format-specific information for the image
- * content of the specified byte source to a string.
+ * Get image metadata from the specified array of bytes. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * IImageMetadata object or to throw an ImageReadException if unable
+ * to process the specified data.
*
- * @param byteSource A valid byte source.
- * @return A valid string.
+ * @param bytes A valid array of bytes
+ * @return A valid, potentially subject-matter-specific implementation of
+ * the IImageMetadata interface describing the content extracted
+ * from the source content.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @throws IOException In the event of unsuccessful data read operation.
*/
- public final String dumpImageFile(final ByteSource byteSource)
- throws ImageReadException, IOException {
- final StringWriter sw = new StringWriter();
- final PrintWriter pw = new PrintWriter(sw);
-
- dumpImageFile(pw, byteSource);
-
- pw.flush();
-
- return sw.toString();
+ public final ImageMetadata getMetadata(final byte[] bytes) throws ImageReadException, IOException {
+ return getMetadata(bytes, null);
}
/**
- * Write the ImageInfo and format-specific information for the image
- * content of the specified byte source to a PrintWriter
+ * Get image metadata from the specified array of bytes. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * IImageMetadata object or to throw an ImageReadException if unable
+ * to process the specified data.
*
- * @param pw print writer used for writing the ImageInfo
- * @param byteSource A valid byte source.
- * @return A valid PrintWriter.
+ * <p>The params argument provides a mechanism for individual
+ * implementations to pass optional information into the parser.
+ * Not all formats will require this capability. Because the
+ * base class may call this method with a null params argument,
+ * implementations should <strong>always</strong> include logic
+ * for ignoring null input.
+ *
+ * @param bytes A valid array of bytes
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data (null objects are permitted and
+ * must be supported by implementations).
+ * @return A valid image metadata object describing the content extracted
+ * from the specified content.
* @throws ImageReadException In the event that the specified content
* does not conform to the format of the specific
* parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @throws IOException In the event of unsuccessful data read operation.
*/
- public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
+ public final ImageMetadata getMetadata(final byte[] bytes, final T params)
throws ImageReadException, IOException {
- return false;
+ return getMetadata(new ByteSourceArray(bytes), params);
}
-
/**
- * Get a descriptive name for the implementation of an ImageParser.
+ * Get image metadata from the specified byte source. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * IImageMetadata object or to throw an ImageReadException if unable
+ * to process the specified byte source.
*
- * @return a valid, subject-matter-specific string.
+ * @param byteSource A valid byte source.
+ * @return A valid, potentially subject-matter-specific implementation of
+ * the IImageMetadata interface describing the content extracted
+ * from the source content.
+ * @throws ImageReadException In the event that the ByteSource
+ * content does not conform to the format of the specific parser
+ * implementation.
+ * @throws IOException In the event of unsuccessful data read operation.
*/
- public abstract String getName();
+ public final ImageMetadata getMetadata(final ByteSource byteSource) throws ImageReadException, IOException {
+ return getMetadata(byteSource, null);
+ }
/**
- * Get the default extension for the format specified by an implementation
- * of ImageParser. Some parsers can support more than one extension
- * (i.e. .JPEG, .JPG; .TIF, .TIFF, etc.).
+ * Get image metadata from the specified byte source. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * IImageMetadata object or to throw an ImageReadException if unable
+ * to process the specified byte source.
*
- * @return A valid string.
- */
- public abstract String getDefaultExtension();
-
- /**
- * Get an array of all accepted extensions
+ * <p>The params argument provides a mechanism for individual
+ * implementations to pass optional information into the parser.
+ * Not all formats will require this capability. Because the
+ * base class may call this method with a null params argument,
+ * implementations should <strong>always</strong> include logic
+ * for ignoring null input.
*
- * @return A valid array of one or more elements.
+ * @param byteSource A valid byte source.
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data (null objects are permitted and
+ * must be supported by implementations).
+ * @return A valid, potentially subject-matter-specific implementation of
+ * the IImageMetadata interface describing the content extracted
+ * from the source content.
+ * @throws ImageReadException In the event that the ByteSource
+ * content does not conform to the format of the specific parser
+ * implementation.
+ * @throws IOException In the event of unsuccessful data read operation.
*/
- protected abstract String[] getAcceptedExtensions();
+ public abstract ImageMetadata getMetadata(ByteSource byteSource, T params)
+ throws ImageReadException, IOException;
/**
- * Get an array of ImageFormat objects describing all accepted types
+ * Get image metadata from the specified file. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * IImageMetadata object or to throw an ImageReadException if unable
+ * to process the specified data.
*
- * @return A valid array of one or more elements.
+ * @param file A valid reference to a file.
+ * @return A valid image metadata object describing the content extracted
+ * from the specified content.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful file read or
+ * access operation.
*/
- protected abstract ImageFormat[] getAcceptedTypes();
+ public final ImageMetadata getMetadata(final File file) throws ImageReadException, IOException {
+ return getMetadata(file, null);
+ }
/**
- * Indicates whether the ImageParser implementation can accept
- * the specified format
+ * Get image metadata from the specified file. Format-specific
+ * ImageParser implementations are expected to return a valid
+ * IImageMetadata object or to throw an ImageReadException if unable
+ * to process the specified data.
*
- * @param type An instance of ImageFormat.
- * @return If the parser can accept the format, true; otherwise, false.
+ * <p>The params argument provides a mechanism for individual
+ * implementations to pass optional information into the parser.
+ * Not all formats will require this capability. Because the
+ * base class may call this method with a null params argument,
+ * implementations should <strong>always</strong> include logic
+ * for ignoring null input.
+ *
+ * @param file A valid reference to a file.
+ * @param params Optional instructions for special-handling or
+ * interpretation of the input data (null objects are permitted and
+ * must be supported by implementations).
+ * @return A valid image metadata object describing the content extracted
+ * from the specified content.
+ * @throws ImageReadException In the event that the specified content
+ * does not conform to the format of the specific
+ * parser implementation.
+ * @throws IOException In the event of unsuccessful file read or
+ * access operation.
*/
- public boolean canAcceptType(final ImageFormat type) {
- final ImageFormat[] types = getAcceptedTypes();
+ public final ImageMetadata getMetadata(final File file, final T params)
+ throws ImageReadException, IOException {
+ if (LOGGER.isLoggable(Level.FINEST)) {
+ LOGGER.finest(getName() + ".getMetadata" + ": " + file.getName());
+ }
- for (final ImageFormat type2 : types) {
- if (type2.equals(type)) {
- return true;
- }
+ if (!canAcceptExtension(file)) {
+ return null;
}
- return false;
- }
- /**
- * Indicates whether the ImageParser implementation can accept
- * the specified file based on its extension.
- *
- * @param file An valid file reference.
- * @return If the parser can accept the format, true; otherwise, false.
- */
- public boolean canAcceptExtension(final File file) {
- return canAcceptExtension(file.getName());
+ return getMetadata(new ByteSourceFile(file), params);
}
/**
- * Indicates whether the ImageParser implementation can accept
- * the specified file name based on its extension.
+ * Get a descriptive name for the implementation of an ImageParser.
*
- * @param fileName A valid string giving a file name or file path.
- * @return If the parser can accept the format, true; otherwise, false.
+ * @return a valid, subject-matter-specific string.
*/
- public final boolean canAcceptExtension(final String fileName) {
- final String[] extensions = getAcceptedExtensions();
- if (extensions == null) {
- return true;
- }
-
- final int index = fileName.lastIndexOf('.');
- if (index >= 0) {
- final String fileNameExtension = fileName.substring(index + 1).toLowerCase(Locale.ENGLISH);
- for (final String extension : extensions) {
- if (extension.equals(fileNameExtension)) {
- return true;
- }
- }
- }
- return false;
- }
+ public abstract String getName();
/**
- * Get an instance of IBufferedImageFactory based on the presence
- * of a specification for ImagingConstants..BUFFERED_IMAGE_FACTORY
- * within the supplied params.
+ * Writes the content of a BufferedImage to the specified output
+ * stream.
*
- * @param params optional parameters.
- * @return A valid instance of an implementation of a IBufferedImageFactory.
+ * <p>The params argument provides a mechanism for individual
+ * implementations to pass optional information into the parser.
+ * Not all formats will support this capability. Currently,
+ * some of the parsers do not check for null arguments.</p>
+ *
+ * @param src An image giving the source content for output
+ * @param os A valid output stream for storing the formatted image
+ * @param params optional parameters, defining format-specific instructions for output
+ * (such as selections for data compression, color models, etc.)
+ * @throws ImageWriteException In the event that the output format
+ * cannot handle the input image or invalid params are specified.
+ * @throws IOException In the event of an write error from
+ * the output stream.
*/
- protected BufferedImageFactory getBufferedImageFactory(final T params) {
- if (params == null) {
- return new SimpleBufferedImageFactory();
- }
-
- final BufferedImageFactory result = params.getBufferedImageFactory();
-
- if (null != result) {
- return result;
- }
-
- return new SimpleBufferedImageFactory();
+ public void writeImage(final BufferedImage src, final OutputStream os, final T params)
+ throws ImageWriteException, IOException {
+ throw new ImageWriteException("This image format (" + getName() + ") cannot be written.");
}
}
diff --git a/src/main/java/org/apache/commons/imaging/ImageWriteException.java b/src/main/java/org/apache/commons/imaging/ImageWriteException.java
index db8fde0f..c8fe0be5 100644
--- a/src/main/java/org/apache/commons/imaging/ImageWriteException.java
+++ b/src/main/java/org/apache/commons/imaging/ImageWriteException.java
@@ -24,18 +24,6 @@ package org.apache.commons.imaging;
public class ImageWriteException extends ImagingException {
private static final long serialVersionUID = -1L;
- public ImageWriteException(final String message) {
- super(message);
- }
-
- public ImageWriteException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
- public ImageWriteException(final String message, final Object data) {
- super(message + ": " + data + " (" + getType(data) + ")");
- }
-
private static String getType(final Object value) {
if (value == null) {
return "null";
@@ -69,4 +57,16 @@ public class ImageWriteException extends ImagingException {
}
return value.getClass().getName();
}
+
+ public ImageWriteException(final String message) {
+ super(message);
+ }
+
+ public ImageWriteException(final String message, final Object data) {
+ super(message + ": " + data + " (" + getType(data) + ")");
+ }
+
+ public ImageWriteException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/Imaging.java b/src/main/java/org/apache/commons/imaging/Imaging.java
index bcf9b7f7..1bf0a079 100644
--- a/src/main/java/org/apache/commons/imaging/Imaging.java
+++ b/src/main/java/org/apache/commons/imaging/Imaging.java
@@ -102,245 +102,210 @@ public final class Imaging {
private static final int[] MAGIC_NUMBERS_DCX = { 0xB1, 0x68, };
private static final int[] MAGIC_NUMBERS_RGBE = { 0x23, 0x3F, };
- private Imaging() {
- // Instances can not be created
+ private static boolean compareBytePair(final int[] a, final int[] b) {
+ if (a.length != 2 && b.length != 2) {
+ throw new IllegalArgumentException("Invalid Byte Pair.");
+ }
+ return (a[0] == b[0]) && (a[1] == b[1]);
}
/**
- * Attempts to determine if a file contains an image recorded in
- * a supported graphics format based on its file-name extension
- * (for example ".jpg", ".gif", ".png", etc.).
+ * Write the ImageInfo and format-specific information for the image content of the specified byte array to a string.
*
- * @param file A valid File object providing a reference to a file that may contain an image.
- * @return true if the file-name includes a supported image format file extension; otherwise, false.
+ * @param bytes A valid array of bytes.
+ * @return A valid string.
+ * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public static boolean hasImageFileExtension(final File file) {
- if (file == null || !file.isFile()) {
- return false;
- }
- return hasImageFileExtension(file.getName());
+ public static String dumpImageFile(final byte[] bytes) throws ImageReadException, IOException {
+ return dumpImageFile(new ByteSourceArray(bytes));
+ }
+
+ private static String dumpImageFile(final ByteSource byteSource) throws ImageReadException, IOException {
+ final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
+ return imageParser.dumpImageFile(byteSource);
}
/**
- * Attempts to determine if a file contains an image recorded in
- * a supported graphics format based on its file-name extension
- * (for example ".jpg", ".gif", ".png", etc.).
+ * Write the ImageInfo and format-specific information for the image content of the specified file to a string.
*
- * @param fileName A valid string representing name of file which may contain an image.
- * @return true if the file name has an image format file extension.
+ * @param file A valid file reference.
+ * @return A valid string.
+ * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public static boolean hasImageFileExtension(final String fileName) {
- if (fileName == null) {
- return false;
- }
-
- final String normalizedFilename = fileName.toLowerCase(Locale.ENGLISH);
+ public static String dumpImageFile(final File file) throws ImageReadException, IOException {
+ return dumpImageFile(new ByteSourceFile(file));
+ }
- for (final ImageParser<?> imageParser : ImageParser.getAllImageParsers()) {
- for (final String extension : imageParser.getAcceptedExtensions()) {
- if (normalizedFilename.endsWith(extension.toLowerCase(Locale.ENGLISH))) {
- return true;
- }
- }
- }
+ /**
+ * Gets all images specified by the byte array (some formats may include multiple images within a single data source).
+ *
+ * @param bytes a valid array of bytes
+ * @return A valid (potentially empty) list of BufferedImage objects.
+ * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
+ */
+ public static List<BufferedImage> getAllBufferedImages(final byte[] bytes) throws ImageReadException, IOException {
+ return getAllBufferedImages(new ByteSourceArray(bytes));
+ }
- return false;
+ private static List<BufferedImage> getAllBufferedImages(final ByteSource byteSource) throws ImageReadException, IOException {
+ final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
+ return imageParser.getAllBufferedImages(byteSource);
}
/**
- * Attempts to determine the image format of a file based on its "magic numbers," the first bytes of the data.
+ * Gets all images specified by the file (some formats may include multiple images within a single data source).
*
- * <p>Many graphics format specify identifying byte
- * values that appear at the beginning of the data file. This method
- * checks for such identifying elements and returns a ImageFormat
- * enumeration indicating what it detects. Note that this
- * method can return "false positives" in cases where non-image files
- * begin with the specified byte values.</p>
+ * @param file A reference to a valid data file.
+ * @return A valid (potentially empty) list of BufferedImage objects.
+ * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
+ */
+ public static List<BufferedImage> getAllBufferedImages(final File file) throws ImageReadException, IOException {
+ return getAllBufferedImages(new ByteSourceFile(file));
+ }
+
+ /**
+ * Gets all images specified by the InputStream (some formats may include multiple images within a single data source).
*
- * @param bytes Byte array containing an image file.
- * @return An ImageFormat, such as ImageFormat.IMAGE_FORMAT_JPEG. Returns ImageFormat.IMAGE_FORMAT_UNKNOWN if the image type cannot be determined.
- * @throws IOException in the event of an unrecoverable I/O condition.
+ * @param is A valid InputStream
+ * @param fileName Filename associated with image data (optional).
+ * @return A valid (potentially empty) list of BufferedImage objects.
+ * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
+ * @throws IOException In the event of unsuccessful read or access operation.
*/
- public static ImageFormat guessFormat(final byte[] bytes) throws IOException {
- return guessFormat(new ByteSourceArray(bytes));
+ public static List<BufferedImage> getAllBufferedImages(final InputStream is, final String fileName) throws ImageReadException, IOException {
+ return getAllBufferedImages(new ByteSourceInputStream(is, fileName));
}
/**
- * Attempts to determine the image format of a file based on its "magic numbers," the first bytes of the data.
+ * Reads the first image from a byte array.
*
- * <p>Many graphics formats specify identifying byte
- * values that appear at the beginning of the data file. This method
- * checks for such identifying elements and returns a ImageFormat
- * enumeration indicating what it detects. Note that this
- * method can return "false positives" in cases where non-image files
- * begin with the specified byte values.</p>
+ * <p>For the most recent information on support for specific formats, refer to
+ * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
+ * at the main project development web site. While the Apache Commons
+ * Imaging package does not fully support all formats, it can read
+ * image info, metadata and ICC profiles from all image formats that
+ * provide this data.</p>
*
- * @param file File containing image data.
- * @return An ImageFormat, such as ImageFormat.IMAGE_FORMAT_JPEG. Returns ImageFormat.IMAGE_FORMAT_UNKNOWN if the image type cannot be determined.
- * @throws IOException in the event of an unrecoverable I/O condition.
+ * @param bytes a valid array of bytes from which to read data.
+ * @return if successful, a valid buffered image
+ * @throws ImageReadException in the event of a processing error while reading an image (i.e. a format violation, etc.).
+ * @throws IOException in the event of an unrecoverable I/O exception.
*/
- public static ImageFormat guessFormat(final File file) throws IOException {
- return guessFormat(new ByteSourceFile(file));
+ public static BufferedImage getBufferedImage(final byte[] bytes) throws ImageReadException, IOException {
+ return getBufferedImage(new ByteSourceArray(bytes));
}
- private static boolean compareBytePair(final int[] a, final int[] b) {
- if (a.length != 2 && b.length != 2) {
- throw new IllegalArgumentException("Invalid Byte Pair.");
- }
- return (a[0] == b[0]) && (a[1] == b[1]);
+ private static BufferedImage getBufferedImage(final ByteSource byteSource) throws ImageReadException, IOException {
+ final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
+ return imageParser.getBufferedImage(byteSource, null);
}
/**
- * Attempts to determine the image format of a file based on its "magic numbers," the first bytes of the data.
+ * Reads the first image from a file.
*
- * <p>Many graphics formats specify identifying byte
- * values that appear at the beginning of the data file. This method
- * checks for such identifying elements and returns a ImageFormat
- * enumeration indicating what it detects. Note that this
- * method can return "false positives" in cases where non-image files
- * begin with the specified byte values.</p>
+ * <p>For the most recent information on support for specific formats, refer to
+ * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
+ * at the main project development web site. While the Apache Commons
+ * Imaging package does not fully support all formats, it can read
+ * image info, metadata and ICC profiles from all image formats that
+ * provide this data.</p>
*
- * @param byteSource a valid ByteSource object potentially supplying data for an image.
- * @return An ImageFormat, such as ImageFormat.IMAGE_FORMAT_JPEG. Returns ImageFormat.IMAGE_FORMAT_UNKNOWN if the image type cannot be determined.
- * @throws IllegalArgumentException in the event of an unsuccessful attempt to read the image data
- * @throws IOException in the event of an unrecoverable I/O condition.
+ * @param file a valid reference to a file containing image data.
+ * @return if successful, a valid buffered image
+ * @throws ImageReadException in the event of a processing error while reading an image (i.e. a format violation, etc.).
+ * @throws IOException in the event of an unrecoverable I/O exception.
*/
- public static ImageFormat guessFormat(final ByteSource byteSource) throws IOException {
- if (byteSource == null) {
- return ImageFormats.UNKNOWN;
- }
-
- try (InputStream is = byteSource.getInputStream()) {
- final int i1 = is.read();
- final int i2 = is.read();
- if ((i1 < 0) || (i2 < 0)) {
- throw new IllegalArgumentException("Couldn't read magic numbers to guess format.");
- }
-
- final int b1 = i1 & 0xff;
- final int b2 = i2 & 0xff;
- final int[] bytePair = { b1, b2, };
+ public static BufferedImage getBufferedImage(final File file) throws ImageReadException, IOException {
+ return getBufferedImage(new ByteSourceFile(file));
+ }
- if (compareBytePair(MAGIC_NUMBERS_GIF, bytePair)) {
- return ImageFormats.GIF;
- // } else if (b1 == 0x00 && b2 == 0x00) // too similar to TGA
- // {
- // return ImageFormat.IMAGE_FORMAT_ICO;
- }
- if (compareBytePair(MAGIC_NUMBERS_PNG, bytePair)) {
- return ImageFormats.PNG;
- }
- if (compareBytePair(MAGIC_NUMBERS_JPEG, bytePair)) {
- return ImageFormats.JPEG;
- }
- if (compareBytePair(MAGIC_NUMBERS_BMP, bytePair)) {
- return ImageFormats.BMP;
- }
- if (compareBytePair(MAGIC_NUMBERS_TIFF_MOTOROLA, bytePair)) {
- return ImageFormats.TIFF;
- }
- if (compareBytePair(MAGIC_NUMBERS_TIFF_INTEL, bytePair)) {
- return ImageFormats.TIFF;
- }
- if (compareBytePair(MAGIC_NUMBERS_PSD, bytePair)) {
- return ImageFormats.PSD;
- }
- if (compareBytePair(MAGIC_NUMBERS_PAM, bytePair)) {
- return ImageFormats.PAM;
- }
- if (compareBytePair(MAGIC_NUMBERS_PBM_A, bytePair)) {
- return ImageFormats.PBM;
- }
- if (compareBytePair(MAGIC_NUMBERS_PBM_B, bytePair)) {
- return ImageFormats.PBM;
- }
- if (compareBytePair(MAGIC_NUMBERS_PGM_A, bytePair)) {
- return ImageFormats.PGM;
- }
- if (compareBytePair(MAGIC_NUMBERS_PGM_B, bytePair)) {
- return ImageFormats.PGM;
- }
- if (compareBytePair(MAGIC_NUMBERS_PPM_A, bytePair)) {
- return ImageFormats.PPM;
- }
- if (compareBytePair(MAGIC_NUMBERS_PPM_B, bytePair)) {
- return ImageFormats.PPM;
- }
- if (compareBytePair(MAGIC_NUMBERS_JBIG2_1, bytePair)) {
- final int i3 = is.read();
- final int i4 = is.read();
- if ((i3 < 0) || (i4 < 0)) {
- throw new IllegalArgumentException("Couldn't read magic numbers to guess format.");
- }
+ /**
+ * Reads the first image from an InputStream.
+ *
+ * <p>For the most recent information on support for specific formats, refer to
+ * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
+ * at the main project development web site. While the Apache Commons
+ * Imaging package does not fully support all formats, it can read
+ * image info, metadata and ICC profiles from all image formats that
+ * provide this data.</p>
+ *
+ * @param is a valid ImageStream from which to read data.
+ * @return if successful, a valid buffered image
+ * @throws ImageReadException in the event of a processing errorfileName while reading an image (i.e. a format violation, etc.).
+ * @throws IOException in the event of an unrecoverable I/O exception.
+ */
+ public static BufferedImage getBufferedImage(final InputStream is) throws ImageReadException, IOException {
+ return getBufferedImage(is, null);
+ }
- final int b3 = i3 & 0xff;
- final int b4 = i4 & 0xff;
- final int[] bytePair2 = { b3, b4, };
- if (compareBytePair(MAGIC_NUMBERS_JBIG2_2, bytePair2)) {
- return ImageFormats.JBIG2;
- }
- } else if (compareBytePair(MAGIC_NUMBERS_ICNS, bytePair)) {
- return ImageFormats.ICNS;
- } else if (compareBytePair(MAGIC_NUMBERS_DCX, bytePair)) {
- return ImageFormats.DCX;
- } else if (compareBytePair(MAGIC_NUMBERS_RGBE, bytePair)) {
- return ImageFormats.RGBE;
- }
- return Stream
- .of(ImageFormats.values())
- .filter(imageFormat -> Stream
- .of(imageFormat.getExtensions())
- .anyMatch((extension) -> {
- final String fileName = byteSource.getFileName();
- if (fileName == null || fileName.trim().length() == 0) {
- return false;
- }
- final String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
- return extension != null
- && extension.trim().length() > 0
- && fileExtension.equalsIgnoreCase(extension);
- }))
- .findFirst()
- .orElse(ImageFormats.UNKNOWN)
- ;
- }
+ /**
+ * Reads the first image from an InputStream.
+ *
+ * <p>For the most recent information on support for specific formats, refer to
+ * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
+ * at the main project development web site. While the Apache Commons
+ * Imaging package does not fully support all formats, it can read
+ * image info, metadata and ICC profiles from all image formats that
+ * provide this data.</p>
+ *
+ * @param is a valid ImageStream from which to read data.
+ * @param fileName the image file name.
+ * @return if successful, a valid buffered image
+ * @throws ImageReadException in the event of a processing error while reading an image (i.e. a format violation, etc.).
+ * @throws IOException in the event of an unrecoverable I/O exception.
+ */
+ public static BufferedImage getBufferedImage(final InputStream is, final String fileName) throws ImageReadException, IOException {
+ return getBufferedImage(new ByteSourceInputStream(is, fileName));
}
/**
- * Extracts an ICC Profile (if present) from JPEG, PNG, PSD (Photoshop) and TIFF images.
+ * Attempts to determine the image format of the specified data and evaluates its format compliance.
*
- * @param bytes Byte array containing an image file.
- * @return An instance of ICC_Profile or null if the image contains no ICC profile.
- * @throws ImageReadException if it fails to parse the image
- * @throws IOException if it fails to read the image data
+ * <p>This method returns a FormatCompliance object which includes information about the data's compliance to a specific format.</p>
+ *
+ * @param bytes a valid array of bytes containing image data.
+ * @return if successful, a valid FormatCompliance object.
+ * @throws ImageReadException in the event of unreadable data.
+ * @throws IOException in the event of an unrecoverable I/O condition.
*/
- public static ICC_Profile getICCProfile(final byte[] bytes) throws ImageReadException, IOException {
- return getICCProfile(new ByteSourceArray(bytes));
+ public static FormatCompliance getFormatCompliance(final byte[] bytes) throws ImageReadException, IOException {
+ return getFormatCompliance(new ByteSourceArray(bytes));
+ }
+
+ private static FormatCompliance getFormatCompliance(final ByteSource byteSource) throws ImageReadException, IOException {
+ final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
+ return imageParser.getFormatCompliance(byteSource);
}
/**
- * Extracts an ICC Profile (if present) from JPEG, PNG, PSD (Photoshop) and TIFF images.
+ * Attempts to determine the image format of the specified data and
+ * evaluates its format compliance. This method
+ * returns a FormatCompliance object which includes information
+ * about the data's compliance to a specific format.
*
- * @param is InputStream from which to read image data.
- * @param fileName Filename associated with image data (optional).
- * @return An instance of ICC_Profile or null if the image contains no ICC profile.
- * @throws ImageReadException if it fails to parse the image
- * @throws IOException if it fails to read the image data
+ * @param file valid file containing image data
+ * @return if successful, a valid FormatCompliance object.
+ * @throws ImageReadException in the event of unreadable data.
+ * @throws IOException in the event of an unrecoverable I/O condition.
*/
- public static ICC_Profile getICCProfile(final InputStream is, final String fileName) throws ImageReadException, IOException {
- return getICCProfile(new ByteSourceInputStream(is, fileName));
+ public static FormatCompliance getFormatCompliance(final File file) throws ImageReadException, IOException {
+ return getFormatCompliance(new ByteSourceFile(file));
}
/**
* Extracts an ICC Profile (if present) from JPEG, PNG, PSD (Photoshop) and TIFF images.
*
- * @param file File containing image data.
+ * @param bytes Byte array containing an image file.
* @return An instance of ICC_Profile or null if the image contains no ICC profile.
* @throws ImageReadException if it fails to parse the image
* @throws IOException if it fails to read the image data
*/
- public static ICC_Profile getICCProfile(final File file) throws ImageReadException, IOException {
- return getICCProfile(new ByteSourceFile(file));
+ public static ICC_Profile getICCProfile(final byte[] bytes) throws ImageReadException, IOException {
+ return getICCProfile(new ByteSourceArray(bytes));
}
protected static ICC_Profile getICCProfile(final ByteSource byteSource) throws ImageReadException, IOException {
@@ -361,6 +326,31 @@ public final class Imaging {
return ICC_Profile.getInstance(bytes);
}
+ /**
+ * Extracts an ICC Profile (if present) from JPEG, PNG, PSD (Photoshop) and TIFF images.
+ *
+ * @param file File containing image data.
+ * @return An instance of ICC_Profile or null if the image contains no ICC profile.
+ * @throws ImageReadException if it fails to parse the image
+ * @throws IOException if it fails to read the image data
+ */
+ public static ICC_Profile getICCProfile(final File file) throws ImageReadException, IOException {
+ return getICCProfile(new ByteSourceFile(file));
+ }
+
+ /**
+ * Extracts an ICC Profile (if present) from JPEG, PNG, PSD (Photoshop) and TIFF images.
+ *
+ * @param is InputStream from which to read image data.
+ * @param fileName Filename associated with image data (optional).
+ * @return An instance of ICC_Profile or null if the image contains no ICC profile.
+ * @throws ImageReadException if it fails to parse the image
+ * @throws IOException if it fails to read the image data
+ */
+ public static ICC_Profile getICCProfile(final InputStream is, final String fileName) throws ImageReadException, IOException {
+ return getICCProfile(new ByteSourceInputStream(is, fileName));
+ }
+
/**
* Extracts the raw bytes of an ICC Profile (if present) from JPEG, PNG, PSD
* (Photoshop) and TIFF images.
@@ -380,6 +370,11 @@ public final class Imaging {
return getICCProfileBytes(new ByteSourceArray(bytes));
}
+ private static byte[] getICCProfileBytes(final ByteSource byteSource) throws ImageReadException, IOException {
+ final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
+ return imageParser.getICCProfileBytes(byteSource, null);
+ }
+
/**
* Extracts the raw bytes of an ICC Profile (if present) from JPEG, PNG, PSD
* (Photoshop) and TIFF images.
@@ -399,11 +394,6 @@ public final class Imaging {
return getICCProfileBytes(new ByteSourceFile(file));
}
- private static byte[] getICCProfileBytes(final ByteSource byteSource) throws ImageReadException, IOException {
- final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
- return imageParser.getICCProfileBytes(byteSource, null);
- }
-
/**
* Parses the "image info" of an image.
*
@@ -412,34 +402,36 @@ public final class Imaging {
*
* <p>Not to be confused with "image metadata."</p>
*
- * @param fileName String.
* @param bytes Byte array containing an image file.
* @return An instance of ImageInfo.
* @see ImageInfo
* @throws ImageReadException if it fails to parse the image
* @throws IOException if it fails to read the image data
*/
- public static ImageInfo getImageInfo(final String fileName, final byte[] bytes) throws ImageReadException, IOException {
- return getImageInfo(new ByteSourceArray(fileName, bytes));
+ public static ImageInfo getImageInfo(final byte[] bytes) throws ImageReadException, IOException {
+ return getImageInfo(new ByteSourceArray(bytes));
+ }
+
+ private static ImageInfo getImageInfo(final ByteSource byteSource) throws ImageReadException, IOException {
+ return ImageParserFactory.getImageParser(byteSource).getImageInfo(byteSource, null);
}
/**
- * Parses the "image info" of an image.
+ * Parses the "image info" of an image file.
*
* <p>"Image info" is a summary of basic information about the image such as:
* width, height, file format, bit depth, color type, etc.</p>
*
* <p>Not to be confused with "image metadata."</p>
*
- * @param is InputStream from which to read image data.
- * @param fileName Filename associated with image data (optional).
+ * @param file File containing image data.
* @return An instance of ImageInfo.
* @see ImageInfo
* @throws ImageReadException if it fails to parse the image
* @throws IOException if it fails to read the image data
*/
- public static ImageInfo getImageInfo(final InputStream is, final String fileName) throws ImageReadException, IOException {
- return getImageInfo(new ByteSourceInputStream(is, fileName));
+ public static ImageInfo getImageInfo(final File file) throws ImageReadException, IOException {
+ return getImageInfo(new ByteSourceFile(file));
}
/**
@@ -450,49 +442,34 @@ public final class Imaging {
*
* <p>Not to be confused with "image metadata."</p>
*
- * @param bytes Byte array containing an image file.
+ * @param is InputStream from which to read image data.
+ * @param fileName Filename associated with image data (optional).
* @return An instance of ImageInfo.
* @see ImageInfo
* @throws ImageReadException if it fails to parse the image
* @throws IOException if it fails to read the image data
*/
- public static ImageInfo getImageInfo(final byte[] bytes) throws ImageReadException, IOException {
- return getImageInfo(new ByteSourceArray(bytes));
+ public static ImageInfo getImageInfo(final InputStream is, final String fileName) throws ImageReadException, IOException {
+ return getImageInfo(new ByteSourceInputStream(is, fileName));
}
/**
- * Parses the "image info" of an image file.
+ * Parses the "image info" of an image.
*
* <p>"Image info" is a summary of basic information about the image such as:
* width, height, file format, bit depth, color type, etc.</p>
*
* <p>Not to be confused with "image metadata."</p>
*
- * @param file File containing image data.
+ * @param fileName String.
+ * @param bytes Byte array containing an image file.
* @return An instance of ImageInfo.
* @see ImageInfo
* @throws ImageReadException if it fails to parse the image
* @throws IOException if it fails to read the image data
*/
- public static ImageInfo getImageInfo(final File file) throws ImageReadException, IOException {
- return getImageInfo(new ByteSourceFile(file));
- }
-
- private static ImageInfo getImageInfo(final ByteSource byteSource) throws ImageReadException, IOException {
- return ImageParserFactory.getImageParser(byteSource).getImageInfo(byteSource, null);
- }
-
- /**
- * Determines the width and height of an image.
- *
- * @param is InputStream from which to read image data.
- * @param fileName Filename associated with image data (optional).
- * @return The width and height of the image.
- * @throws ImageReadException if it fails to parse the image
- * @throws IOException if it fails to read the image data
- */
- public static Dimension getImageSize(final InputStream is, final String fileName) throws ImageReadException, IOException {
- return getImageSize(new ByteSourceInputStream(is, fileName));
+ public static ImageInfo getImageInfo(final String fileName, final byte[] bytes) throws ImageReadException, IOException {
+ return getImageInfo(new ByteSourceArray(fileName, bytes));
}
/**
@@ -507,18 +484,6 @@ public final class Imaging {
return getImageSize(new ByteSourceArray(bytes));
}
- /**
- * Determines the width and height of an image file.
- *
- * @param file File containing image data.
- * @return The width and height of the image.
- * @throws ImageReadException if it fails to parse the image
- * @throws IOException if it fails to read the image data
- */
- public static Dimension getImageSize(final File file) throws ImageReadException, IOException {
- return getImageSize(new ByteSourceFile(file));
- }
-
/**
* Determines the width and height of an image byte source.
*
@@ -533,56 +498,28 @@ public final class Imaging {
}
/**
- * Extracts the embedded XML metadata as an XML string.
- *
- * @param is InputStream from which to read image data.
- * @param fileName Filename associated with image data (optional).
- * @return Xmp Xml as String, if present. Otherwise, returns null.
- * @throws ImageReadException if it fails to parse the image
- * @throws IOException if it fails to read the image data
- */
- public static String getXmpXml(final InputStream is, final String fileName) throws ImageReadException, IOException {
- return getXmpXml(new ByteSourceInputStream(is, fileName));
- }
-
- /**
- * Extracts the embedded XML metadata as an XML string.
- *
- * @param bytes Byte array containing an image file.
- * @return Xmp Xml as String, if present. Otherwise, returns null.
- * @throws ImageReadException if it fails to parse the image
- * @throws IOException if it fails to read the image data
- */
- public static String getXmpXml(final byte[] bytes) throws ImageReadException, IOException {
- return getXmpXml(new ByteSourceArray(bytes));
- }
-
- /**
- * Extracts the embedded XML metadata as an XML string.
+ * Determines the width and height of an image file.
*
* @param file File containing image data.
- * @return Xmp Xml as String, if present. Otherwise, returns null.
+ * @return The width and height of the image.
* @throws ImageReadException if it fails to parse the image
* @throws IOException if it fails to read the image data
*/
- public static String getXmpXml(final File file) throws ImageReadException, IOException {
- return getXmpXml(new ByteSourceFile(file));
+ public static Dimension getImageSize(final File file) throws ImageReadException, IOException {
+ return getImageSize(new ByteSourceFile(file));
}
/**
- * Extracts the embedded XML metadata as an XML string.
+ * Determines the width and height of an image.
*
- * @param byteSource File containing image data.
- * @return Xmp Xml as String, if present. Otherwise, returns null.
+ * @param is InputStream from which to read image data.
+ * @param fileName Filename associated with image data (optional).
+ * @return The width and height of the image.
* @throws ImageReadException if it fails to parse the image
* @throws IOException if it fails to read the image data
*/
- public static String getXmpXml(final ByteSource byteSource) throws ImageReadException, IOException {
- final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
- if (imageParser instanceof XmpEmbeddable) {
- return ((XmpEmbeddable) imageParser).getXmpXml(byteSource, null);
- }
- return null;
+ public static Dimension getImageSize(final InputStream is, final String fileName) throws ImageReadException, IOException {
+ return getImageSize(new ByteSourceInputStream(is, fileName));
}
/**
@@ -606,25 +543,30 @@ public final class Imaging {
return getMetadata(new ByteSourceArray(bytes));
}
+ private static ImageMetadata getMetadata(final ByteSource byteSource) throws ImageReadException, IOException {
+ final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
+ return imageParser.getMetadata(byteSource, null);
+ }
+
/**
* Parses the metadata of an image file. This metadata depends on the format of the image.
*
* <p>JPEG/JFIF files may contain EXIF and/or IPTC metadata. PNG files may
* contain comments. TIFF files may contain metadata.</p>
*
- * <p>The instance of IImageMetadata returned by getMetadata() should be upcast (depending on image format).</p>
+ * <p>The instance of IImageMetadata returned by getMetadata() should be upcast
+ * (depending on image format).</p>
*
* <p>Not to be confused with "image info."</p>
*
- * @param is InputStream from which to read image data.
- * @param fileName Filename associated with image data (optional).
+ * @param file File containing image data.
* @return An instance of IImageMetadata.
* @see org.apache.commons.imaging.common.ImageMetadata
* @throws ImageReadException if it fails to read the image metadata
* @throws IOException if it fails to read the image data
*/
- public static ImageMetadata getMetadata(final InputStream is, final String fileName) throws ImageReadException, IOException {
- return getMetadata(new ByteSourceInputStream(is, fileName));
+ public static ImageMetadata getMetadata(final File file) throws ImageReadException, IOException {
+ return getMetadata(new ByteSourceFile(file));
}
/**
@@ -633,211 +575,265 @@ public final class Imaging {
* <p>JPEG/JFIF files may contain EXIF and/or IPTC metadata. PNG files may
* contain comments. TIFF files may contain metadata.</p>
*
- * <p>The instance of IImageMetadata returned by getMetadata() should be upcast
- * (depending on image format).</p>
+ * <p>The instance of IImageMetadata returned by getMetadata() should be upcast (depending on image format).</p>
*
* <p>Not to be confused with "image info."</p>
*
- * @param file File containing image data.
+ * @param is InputStream from which to read image data.
+ * @param fileName Filename associated with image data (optional).
* @return An instance of IImageMetadata.
* @see org.apache.commons.imaging.common.ImageMetadata
* @throws ImageReadException if it fails to read the image metadata
* @throws IOException if it fails to read the image data
*/
- public static ImageMetadata getMetadata(final File file) throws ImageReadException, IOException {
- return getMetadata(new ByteSourceFile(file));
- }
-
- private static ImageMetadata getMetadata(final ByteSource byteSource) throws ImageReadException, IOException {
- final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
- return imageParser.getMetadata(byteSource, null);
+ public static ImageMetadata getMetadata(final InputStream is, final String fileName) throws ImageReadException, IOException {
+ return getMetadata(new ByteSourceInputStream(is, fileName));
}
/**
- * Write the ImageInfo and format-specific information for the image content of the specified byte array to a string.
+ * Extracts the embedded XML metadata as an XML string.
*
- * @param bytes A valid array of bytes.
- * @return A valid string.
- * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @param bytes Byte array containing an image file.
+ * @return Xmp Xml as String, if present. Otherwise, returns null.
+ * @throws ImageReadException if it fails to parse the image
+ * @throws IOException if it fails to read the image data
*/
- public static String dumpImageFile(final byte[] bytes) throws ImageReadException, IOException {
- return dumpImageFile(new ByteSourceArray(bytes));
+ public static String getXmpXml(final byte[] bytes) throws ImageReadException, IOException {
+ return getXmpXml(new ByteSourceArray(bytes));
}
/**
- * Write the ImageInfo and format-specific information for the image content of the specified file to a string.
+ * Extracts the embedded XML metadata as an XML string.
*
- * @param file A valid file reference.
- * @return A valid string.
- * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @param byteSource File containing image data.
+ * @return Xmp Xml as String, if present. Otherwise, returns null.
+ * @throws ImageReadException if it fails to parse the image
+ * @throws IOException if it fails to read the image data
*/
- public static String dumpImageFile(final File file) throws ImageReadException, IOException {
- return dumpImageFile(new ByteSourceFile(file));
- }
-
- private static String dumpImageFile(final ByteSource byteSource) throws ImageReadException, IOException {
+ public static String getXmpXml(final ByteSource byteSource) throws ImageReadException, IOException {
final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
- return imageParser.dumpImageFile(byteSource);
- }
-
- /**
- * Attempts to determine the image format of the specified data and evaluates its format compliance.
- *
- * <p>This method returns a FormatCompliance object which includes information about the data's compliance to a specific format.</p>
- *
- * @param bytes a valid array of bytes containing image data.
- * @return if successful, a valid FormatCompliance object.
- * @throws ImageReadException in the event of unreadable data.
- * @throws IOException in the event of an unrecoverable I/O condition.
- */
- public static FormatCompliance getFormatCompliance(final byte[] bytes) throws ImageReadException, IOException {
- return getFormatCompliance(new ByteSourceArray(bytes));
+ if (imageParser instanceof XmpEmbeddable) {
+ return ((XmpEmbeddable) imageParser).getXmpXml(byteSource, null);
+ }
+ return null;
}
/**
- * Attempts to determine the image format of the specified data and
- * evaluates its format compliance. This method
- * returns a FormatCompliance object which includes information
- * about the data's compliance to a specific format.
+ * Extracts the embedded XML metadata as an XML string.
*
- * @param file valid file containing image data
- * @return if successful, a valid FormatCompliance object.
- * @throws ImageReadException in the event of unreadable data.
- * @throws IOException in the event of an unrecoverable I/O condition.
+ * @param file File containing image data.
+ * @return Xmp Xml as String, if present. Otherwise, returns null.
+ * @throws ImageReadException if it fails to parse the image
+ * @throws IOException if it fails to read the image data
*/
- public static FormatCompliance getFormatCompliance(final File file) throws ImageReadException, IOException {
- return getFormatCompliance(new ByteSourceFile(file));
- }
-
- private static FormatCompliance getFormatCompliance(final ByteSource byteSource) throws ImageReadException, IOException {
- final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
- return imageParser.getFormatCompliance(byteSource);
+ public static String getXmpXml(final File file) throws ImageReadException, IOException {
+ return getXmpXml(new ByteSourceFile(file));
}
/**
- * Gets all images specified by the InputStream (some formats may include multiple images within a single data source).
+ * Extracts the embedded XML metadata as an XML string.
*
- * @param is A valid InputStream
+ * @param is InputStream from which to read image data.
* @param fileName Filename associated with image data (optional).
- * @return A valid (potentially empty) list of BufferedImage objects.
- * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @return Xmp Xml as String, if present. Otherwise, returns null.
+ * @throws ImageReadException if it fails to parse the image
+ * @throws IOException if it fails to read the image data
*/
- public static List<BufferedImage> getAllBufferedImages(final InputStream is, final String fileName) throws ImageReadException, IOException {
- return getAllBufferedImages(new ByteSourceInputStream(is, fileName));
+ public static String getXmpXml(final InputStream is, final String fileName) throws ImageReadException, IOException {
+ return getXmpXml(new ByteSourceInputStream(is, fileName));
}
/**
- * Gets all images specified by the byte array (some formats may include multiple images within a single data source).
+ * Attempts to determine the image format of a file based on its "magic numbers," the first bytes of the data.
*
- * @param bytes a valid array of bytes
- * @return A valid (potentially empty) list of BufferedImage objects.
- * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
- */
- public static List<BufferedImage> getAllBufferedImages(final byte[] bytes) throws ImageReadException, IOException {
- return getAllBufferedImages(new ByteSourceArray(bytes));
- }
-
- /**
- * Gets all images specified by the file (some formats may include multiple images within a single data source).
+ * <p>Many graphics format specify identifying byte
+ * values that appear at the beginning of the data file. This method
+ * checks for such identifying elements and returns a ImageFormat
+ * enumeration indicating what it detects. Note that this
+ * method can return "false positives" in cases where non-image files
+ * begin with the specified byte values.</p>
*
- * @param file A reference to a valid data file.
- * @return A valid (potentially empty) list of BufferedImage objects.
- * @throws ImageReadException In the event that the specified content does not conform to the format of the specific parser implementation.
- * @throws IOException In the event of unsuccessful read or access operation.
+ * @param bytes Byte array containing an image file.
+ * @return An ImageFormat, such as ImageFormat.IMAGE_FORMAT_JPEG. Returns ImageFormat.IMAGE_FORMAT_UNKNOWN if the image type cannot be determined.
+ * @throws IOException in the event of an unrecoverable I/O condition.
*/
- public static List<BufferedImage> getAllBufferedImages(final File file) throws ImageReadException, IOException {
- return getAllBufferedImages(new ByteSourceFile(file));
- }
-
- private static List<BufferedImage> getAllBufferedImages(final ByteSource byteSource) throws ImageReadException, IOException {
- final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
- return imageParser.getAllBufferedImages(byteSource);
+ public static ImageFormat guessFormat(final byte[] bytes) throws IOException {
+ return guessFormat(new ByteSourceArray(bytes));
}
/**
- * Reads the first image from an InputStream.
+ * Attempts to determine the image format of a file based on its "magic numbers," the first bytes of the data.
*
- * <p>For the most recent information on support for specific formats, refer to
- * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
- * at the main project development web site. While the Apache Commons
- * Imaging package does not fully support all formats, it can read
- * image info, metadata and ICC profiles from all image formats that
- * provide this data.</p>
+ * <p>Many graphics formats specify identifying byte
+ * values that appear at the beginning of the data file. This method
+ * checks for such identifying elements and returns a ImageFormat
+ * enumeration indicating what it detects. Note that this
+ * method can return "false positives" in cases where non-image files
+ * begin with the specified byte values.</p>
*
- * @param is a valid ImageStream from which to read data.
- * @return if successful, a valid buffered image
- * @throws ImageReadException in the event of a processing errorfileName while reading an image (i.e. a format violation, etc.).
- * @throws IOException in the event of an unrecoverable I/O exception.
+ * @param byteSource a valid ByteSource object potentially supplying data for an image.
+ * @return An ImageFormat, such as ImageFormat.IMAGE_FORMAT_JPEG. Returns ImageFormat.IMAGE_FORMAT_UNKNOWN if the image type cannot be determined.
+ * @throws IllegalArgumentException in the event of an unsuccessful attempt to read the image data
+ * @throws IOException in the event of an unrecoverable I/O condition.
*/
- public static BufferedImage getBufferedImage(final InputStream is) throws ImageReadException, IOException {
- return getBufferedImage(is, null);
+ public static ImageFormat guessFormat(final ByteSource byteSource) throws IOException {
+ if (byteSource == null) {
+ return ImageFormats.UNKNOWN;
+ }
+
+ try (InputStream is = byteSource.getInputStream()) {
+ final int i1 = is.read();
+ final int i2 = is.read();
+ if ((i1 < 0) || (i2 < 0)) {
+ throw new IllegalArgumentException("Couldn't read magic numbers to guess format.");
+ }
+
+ final int b1 = i1 & 0xff;
+ final int b2 = i2 & 0xff;
+ final int[] bytePair = { b1, b2, };
+
+ if (compareBytePair(MAGIC_NUMBERS_GIF, bytePair)) {
+ return ImageFormats.GIF;
+ // } else if (b1 == 0x00 && b2 == 0x00) // too similar to TGA
+ // {
+ // return ImageFormat.IMAGE_FORMAT_ICO;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PNG, bytePair)) {
+ return ImageFormats.PNG;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_JPEG, bytePair)) {
+ return ImageFormats.JPEG;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_BMP, bytePair)) {
+ return ImageFormats.BMP;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_TIFF_MOTOROLA, bytePair)) {
+ return ImageFormats.TIFF;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_TIFF_INTEL, bytePair)) {
+ return ImageFormats.TIFF;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PSD, bytePair)) {
+ return ImageFormats.PSD;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PAM, bytePair)) {
+ return ImageFormats.PAM;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PBM_A, bytePair)) {
+ return ImageFormats.PBM;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PBM_B, bytePair)) {
+ return ImageFormats.PBM;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PGM_A, bytePair)) {
+ return ImageFormats.PGM;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PGM_B, bytePair)) {
+ return ImageFormats.PGM;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PPM_A, bytePair)) {
+ return ImageFormats.PPM;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_PPM_B, bytePair)) {
+ return ImageFormats.PPM;
+ }
+ if (compareBytePair(MAGIC_NUMBERS_JBIG2_1, bytePair)) {
+ final int i3 = is.read();
+ final int i4 = is.read();
+ if ((i3 < 0) || (i4 < 0)) {
+ throw new IllegalArgumentException("Couldn't read magic numbers to guess format.");
+ }
+
+ final int b3 = i3 & 0xff;
+ final int b4 = i4 & 0xff;
+ final int[] bytePair2 = { b3, b4, };
+ if (compareBytePair(MAGIC_NUMBERS_JBIG2_2, bytePair2)) {
+ return ImageFormats.JBIG2;
+ }
+ } else if (compareBytePair(MAGIC_NUMBERS_ICNS, bytePair)) {
+ return ImageFormats.ICNS;
+ } else if (compareBytePair(MAGIC_NUMBERS_DCX, bytePair)) {
+ return ImageFormats.DCX;
+ } else if (compareBytePair(MAGIC_NUMBERS_RGBE, bytePair)) {
+ return ImageFormats.RGBE;
+ }
+ return Stream
+ .of(ImageFormats.values())
+ .filter(imageFormat -> Stream
+ .of(imageFormat.getExtensions())
+ .anyMatch((extension) -> {
+ final String fileName = byteSource.getFileName();
+ if (fileName == null || fileName.trim().length() == 0) {
+ return false;
+ }
+ final String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
+ return extension != null
+ && extension.trim().length() > 0
+ && fileExtension.equalsIgnoreCase(extension);
+ }))
+ .findFirst()
+ .orElse(ImageFormats.UNKNOWN)
+ ;
+ }
}
/**
- * Reads the first image from an InputStream.
+ * Attempts to determine the image format of a file based on its "magic numbers," the first bytes of the data.
*
- * <p>For the most recent information on support for specific formats, refer to
- * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
- * at the main project development web site. While the Apache Commons
- * Imaging package does not fully support all formats, it can read
- * image info, metadata and ICC profiles from all image formats that
- * provide this data.</p>
+ * <p>Many graphics formats specify identifying byte
+ * values that appear at the beginning of the data file. This method
+ * checks for such identifying elements and returns a ImageFormat
+ * enumeration indicating what it detects. Note that this
+ * method can return "false positives" in cases where non-image files
+ * begin with the specified byte values.</p>
*
- * @param is a valid ImageStream from which to read data.
- * @param fileName the image file name.
- * @return if successful, a valid buffered image
- * @throws ImageReadException in the event of a processing error while reading an image (i.e. a format violation, etc.).
- * @throws IOException in the event of an unrecoverable I/O exception.
+ * @param file File containing image data.
+ * @return An ImageFormat, such as ImageFormat.IMAGE_FORMAT_JPEG. Returns ImageFormat.IMAGE_FORMAT_UNKNOWN if the image type cannot be determined.
+ * @throws IOException in the event of an unrecoverable I/O condition.
*/
- public static BufferedImage getBufferedImage(final InputStream is, final String fileName) throws ImageReadException, IOException {
- return getBufferedImage(new ByteSourceInputStream(is, fileName));
+ public static ImageFormat guessFormat(final File file) throws IOException {
+ return guessFormat(new ByteSourceFile(file));
}
/**
- * Reads the first image from a byte array.
- *
- * <p>For the most recent information on support for specific formats, refer to
- * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
- * at the main project development web site. While the Apache Commons
- * Imaging package does not fully support all formats, it can read
- * image info, metadata and ICC profiles from all image formats that
- * provide this data.</p>
+ * Attempts to determine if a file contains an image recorded in
+ * a supported graphics format based on its file-name extension
+ * (for example ".jpg", ".gif", ".png", etc.).
*
- * @param bytes a valid array of bytes from which to read data.
- * @return if successful, a valid buffered image
- * @throws ImageReadException in the event of a processing error while reading an image (i.e. a format violation, etc.).
- * @throws IOException in the event of an unrecoverable I/O exception.
+ * @param file A valid File object providing a reference to a file that may contain an image.
+ * @return true if the file-name includes a supported image format file extension; otherwise, false.
*/
- public static BufferedImage getBufferedImage(final byte[] bytes) throws ImageReadException, IOException {
- return getBufferedImage(new ByteSourceArray(bytes));
+ public static boolean hasImageFileExtension(final File file) {
+ if (file == null || !file.isFile()) {
+ return false;
+ }
+ return hasImageFileExtension(file.getName());
}
/**
- * Reads the first image from a file.
- *
- * <p>For the most recent information on support for specific formats, refer to
- * <a href="https://commons.apache.org/imaging/formatsupport.html">Format Support</a>
- * at the main project development web site. While the Apache Commons
- * Imaging package does not fully support all formats, it can read
- * image info, metadata and ICC profiles from all image formats that
- * provide this data.</p>
+ * Attempts to determine if a file contains an image recorded in
+ * a supported graphics format based on its file-name extension
+ * (for example ".jpg", ".gif", ".png", etc.).
*
- * @param file a valid reference to a file containing image data.
- * @return if successful, a valid buffered image
- * @throws ImageReadException in the event of a processing error while reading an image (i.e. a format violation, etc.).
- * @throws IOException in the event of an unrecoverable I/O exception.
+ * @param fileName A valid string representing name of file which may contain an image.
+ * @return true if the file name has an image format file extension.
*/
- public static BufferedImage getBufferedImage(final File file) throws ImageReadException, IOException {
- return getBufferedImage(new ByteSourceFile(file));
- }
+ public static boolean hasImageFileExtension(final String fileName) {
+ if (fileName == null) {
+ return false;
+ }
- private static BufferedImage getBufferedImage(final ByteSource byteSource) throws ImageReadException, IOException {
- final ImageParser<?> imageParser = ImageParserFactory.getImageParser(byteSource);
- return imageParser.getBufferedImage(byteSource, null);
+ final String normalizedFilename = fileName.toLowerCase(Locale.ENGLISH);
+
+ for (final ImageParser<?> imageParser : ImageParser.getAllImageParsers()) {
+ for (final String extension : imageParser.getAcceptedExtensions()) {
+ if (normalizedFilename.endsWith(extension.toLowerCase(Locale.ENGLISH))) {
+ return true;
+ }
+ }
+ }
+
+ return false;
}
/**
@@ -865,7 +861,7 @@ public final class Imaging {
}
/**
- * Writes the content of a BufferedImage to a byte array using the specified image format.
+ * Writes the content of a BufferedImage to an OutputStream using the specified image format.
*
* <p>Image writing is not supported for all graphics formats.
* For the most recent information on support for specific formats, refer to
@@ -876,21 +872,23 @@ public final class Imaging {
* provide this data.</p>
*
* @param src a valid BufferedImage object
+ * @param outputStream the OutputStream to which the output image is to be written
* @param format the format in which the output image is to be written
- * @return if successful, a valid array of bytes.
* @throws ImageWriteException in the event of a format violation, unsupported image format, etc.
* @throws IOException in the event of an unrecoverable I/O exception.
* @see ImagingConstants
*/
- public static byte[] writeImageToBytes(final BufferedImage src, final ImageFormat format) throws ImageWriteException, IOException {
- try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
- writeImage(src, os, format);
- return os.toByteArray();
- }
+ public static void writeImage(final BufferedImage src, final OutputStream outputStream, final ImageFormat format) throws ImageWriteException, IOException {
+ Objects.requireNonNull(src, "src");
+ Objects.requireNonNull(outputStream, "outputStream");
+ Objects.requireNonNull(format, "format");
+
+ final ImageParser<?> imageParser = ImageParserFactory.getImageParser(format);
+ imageParser.writeImage(src, outputStream, null);
}
/**
- * Writes the content of a BufferedImage to an OutputStream using the specified image format.
+ * Writes the content of a BufferedImage to a byte array using the specified image format.
*
* <p>Image writing is not supported for all graphics formats.
* For the most recent information on support for specific formats, refer to
@@ -901,18 +899,20 @@ public final class Imaging {
* provide this data.</p>
*
* @param src a valid BufferedImage object
- * @param outputStream the OutputStream to which the output image is to be written
* @param format the format in which the output image is to be written
+ * @return if successful, a valid array of bytes.
* @throws ImageWriteException in the event of a format violation, unsupported image format, etc.
* @throws IOException in the event of an unrecoverable I/O exception.
* @see ImagingConstants
*/
- public static void writeImage(final BufferedImage src, final OutputStream outputStream, final ImageFormat format) throws ImageWriteException, IOException {
- Objects.requireNonNull(src, "src");
- Objects.requireNonNull(outputStream, "outputStream");
- Objects.requireNonNull(format, "format");
+ public static byte[] writeImageToBytes(final BufferedImage src, final ImageFormat format) throws ImageWriteException, IOException {
+ try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
+ writeImage(src, os, format);
+ return os.toByteArray();
+ }
+ }
- final ImageParser<?> imageParser = ImageParserFactory.getImageParser(format);
- imageParser.writeImage(src, outputStream, null);
+ private Imaging() {
+ // Instances can not be created
}
}
diff --git a/src/main/java/org/apache/commons/imaging/PixelDensity.java b/src/main/java/org/apache/commons/imaging/PixelDensity.java
index 2297d199..7e06b153 100644
--- a/src/main/java/org/apache/commons/imaging/PixelDensity.java
+++ b/src/main/java/org/apache/commons/imaging/PixelDensity.java
@@ -26,48 +26,32 @@ public final class PixelDensity {
private static final int PIXEL_PER_METRE = 10000;
private static final int PIXEL_PER_CENTIMETRE = 100;
- private final double horizontalDensity;
- private final double verticalDensity;
- // / One-tenth of a millimetre units.
- private final int unitLength;
-
- private PixelDensity(final double horizontalDensity, final double verticalDensity,
- final int unitLength) {
- this.horizontalDensity = horizontalDensity;
- this.verticalDensity = verticalDensity;
- this.unitLength = unitLength;
- }
-
- public static PixelDensity createUnitless(final double x, final double y) {
- return new PixelDensity(x, y, PIXEL_NO_UNIT);
+ public static PixelDensity createFromPixelsPerCentimetre(final double x, final double y) {
+ return new PixelDensity(x, y, PIXEL_PER_CENTIMETRE);
}
-
public static PixelDensity createFromPixelsPerInch(final double x, final double y) {
return new PixelDensity(x, y, PIXEL_PER_INCH);
}
-
public static PixelDensity createFromPixelsPerMetre(final double x, final double y) {
return new PixelDensity(x, y, PIXEL_PER_METRE);
}
- public static PixelDensity createFromPixelsPerCentimetre(final double x, final double y) {
- return new PixelDensity(x, y, PIXEL_PER_CENTIMETRE);
+ public static PixelDensity createUnitless(final double x, final double y) {
+ return new PixelDensity(x, y, PIXEL_NO_UNIT);
}
- public boolean isUnitless() {
- return unitLength == PIXEL_NO_UNIT;
- }
+ private final double horizontalDensity;
- public boolean isInInches() {
- return unitLength == PIXEL_PER_INCH;
- }
+ private final double verticalDensity;
- public boolean isInCentimetres() {
- return unitLength == PIXEL_PER_CENTIMETRE;
- }
+ // / One-tenth of a millimetre units.
+ private final int unitLength;
- public boolean isInMetres() {
- return unitLength == PIXEL_PER_METRE;
+ private PixelDensity(final double horizontalDensity, final double verticalDensity,
+ final int unitLength) {
+ this.horizontalDensity = horizontalDensity;
+ this.verticalDensity = verticalDensity;
+ this.unitLength = unitLength;
}
public double getRawHorizontalDensity() {
@@ -78,18 +62,18 @@ public final class PixelDensity {
return verticalDensity;
}
- public double horizontalDensityInches() {
- if (isInInches()) {
+ public double horizontalDensityCentimetres() {
+ if (isInCentimetres()) {
return horizontalDensity;
}
- return horizontalDensity * PIXEL_PER_INCH / unitLength;
+ return horizontalDensity * PIXEL_PER_CENTIMETRE / unitLength;
}
- public double verticalDensityInches() {
+ public double horizontalDensityInches() {
if (isInInches()) {
- return verticalDensity;
+ return horizontalDensity;
}
- return verticalDensity * PIXEL_PER_INCH / unitLength;
+ return horizontalDensity * PIXEL_PER_INCH / unitLength;
}
public double horizontalDensityMetres() {
@@ -99,18 +83,20 @@ public final class PixelDensity {
return horizontalDensity * PIXEL_PER_METRE / unitLength;
}
- public double verticalDensityMetres() {
- if (isInMetres()) {
- return verticalDensity;
- }
- return verticalDensity * PIXEL_PER_METRE / unitLength;
+ public boolean isInCentimetres() {
+ return unitLength == PIXEL_PER_CENTIMETRE;
}
- public double horizontalDensityCentimetres() {
- if (isInCentimetres()) {
- return horizontalDensity;
- }
- return horizontalDensity * PIXEL_PER_CENTIMETRE / unitLength;
+ public boolean isInInches() {
+ return unitLength == PIXEL_PER_INCH;
+ }
+
+ public boolean isInMetres() {
+ return unitLength == PIXEL_PER_METRE;
+ }
+
+ public boolean isUnitless() {
+ return unitLength == PIXEL_NO_UNIT;
}
public double verticalDensityCentimetres() {
@@ -119,4 +105,18 @@ public final class PixelDensity {
}
return verticalDensity * PIXEL_PER_CENTIMETRE / unitLength;
}
+
+ public double verticalDensityInches() {
+ if (isInInches()) {
+ return verticalDensity;
+ }
+ return verticalDensity * PIXEL_PER_INCH / unitLength;
+ }
+
+ public double verticalDensityMetres() {
+ if (isInMetres()) {
+ return verticalDensity;
+ }
+ return verticalDensity * PIXEL_PER_METRE / unitLength;
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorCieLab.java b/src/main/java/org/apache/commons/imaging/color/ColorCieLab.java
index 39e57b01..21f9e1e4 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorCieLab.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorCieLab.java
@@ -88,11 +88,6 @@ public final class ColorCieLab {
this.b = b;
}
- @Override
- public String toString() {
- return "{L: " + L + ", a: " + a + ", b: " + b + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -128,4 +123,9 @@ public final class ColorCieLab {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{L: " + L + ", a: " + a + ", b: " + b + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorCieLch.java b/src/main/java/org/apache/commons/imaging/color/ColorCieLch.java
index de54bb0b..924eb182 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorCieLch.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorCieLch.java
@@ -90,11 +90,6 @@ public final class ColorCieLch {
this.h = h;
}
- @Override
- public String toString() {
- return "{L: " + L + ", C: " + C + ", h: " + h + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -130,4 +125,9 @@ public final class ColorCieLch {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{L: " + L + ", C: " + C + ", h: " + h + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorCieLuv.java b/src/main/java/org/apache/commons/imaging/color/ColorCieLuv.java
index f24299b9..93196ac1 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorCieLuv.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorCieLuv.java
@@ -87,11 +87,6 @@ public final class ColorCieLuv {
this.v = v;
}
- @Override
- public String toString() {
- return "{L: " + L + ", u: " + u + ", v: " + v + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -127,4 +122,9 @@ public final class ColorCieLuv {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{L: " + L + ", u: " + u + ", v: " + v + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorCmy.java b/src/main/java/org/apache/commons/imaging/color/ColorCmy.java
index 4dfb7004..9efa0c8d 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorCmy.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorCmy.java
@@ -117,11 +117,6 @@ public final class ColorCmy {
this.Y = Y;
}
- @Override
- public String toString() {
- return "{C: " + C + ", M: " + M + ", Y: " + Y + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -157,4 +152,9 @@ public final class ColorCmy {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{C: " + C + ", M: " + M + ", Y: " + Y + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorCmyk.java b/src/main/java/org/apache/commons/imaging/color/ColorCmyk.java
index 41a9f91f..adde01f6 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorCmyk.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorCmyk.java
@@ -127,11 +127,6 @@ public final class ColorCmyk {
this.K = K;
}
- @Override
- public String toString() {
- return "{C: " + C + ", M: " + M + ", Y: " + Y + ", K: " + K + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -172,4 +167,9 @@ public final class ColorCmyk {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{C: " + C + ", M: " + M + ", Y: " + Y + ", K: " + K + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorConversions.java b/src/main/java/org/apache/commons/imaging/color/ColorConversions.java
index d9aa60ab..c0547762 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorConversions.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorConversions.java
@@ -35,29 +35,130 @@ public final class ColorConversions {
/** see: https://en.wikipedia.org/wiki/CIELAB_color_space#From_CIEXYZ_to_CIELAB[10] */
private static final double XYZ_t0 = 0.008856;
- private ColorConversions() {
+ public static int convertCIELabtoARGBTest(final int cieL, final int cieA, final int cieB) {
+ double X, Y, Z;
+ {
+
+ double var_Y = ((cieL * 100.0 / 255.0) + 16.0) / 116.0;
+ double var_X = cieA / 500.0 + var_Y;
+ double var_Z = var_Y - cieB / 200.0;
+
+ var_X = unPivotXYZ(var_X);
+ var_Y = unPivotXYZ(var_Y);
+ var_Z = unPivotXYZ(var_Z);
+
+ X = REF_X * var_X; // REF_X = 95.047 Observer= 2°, Illuminant= D65
+ Y = REF_Y * var_Y; // REF_Y = 100.000
+ Z = REF_Z * var_Z; // REF_Z = 108.883
+
+ }
+
+ double R, G, B;
+ {
+ final double var_X = X / 100; // X = From 0 to REF_X
+ final double var_Y = Y / 100; // Y = From 0 to REF_Y
+ final double var_Z = Z / 100; // Z = From 0 to REF_Y
+
+ double var_R = var_X * 3.2406 + var_Y * -1.5372 + var_Z * -0.4986;
+ double var_G = var_X * -0.9689 + var_Y * 1.8758 + var_Z * 0.0415;
+ double var_B = var_X * 0.0557 + var_Y * -0.2040 + var_Z * 1.0570;
+
+ var_R = pivotRGB(var_R);
+ var_G = pivotRGB(var_G);
+ var_B = pivotRGB(var_B);
+
+ R = (var_R * 255);
+ G = (var_G * 255);
+ B = (var_B * 255);
+ }
+
+ return convertRGBtoRGB(R, G, B);
}
- public static ColorCieLab convertXYZtoCIELab(final ColorXyz xyz) {
- return convertXYZtoCIELab(xyz.X, xyz.Y, xyz.Z);
+ public static ColorCieLch convertCIELabtoCIELCH(final ColorCieLab cielab) {
+ return convertCIELabtoCIELCH(cielab.L, cielab.a, cielab.b);
}
- public static ColorCieLab convertXYZtoCIELab(final double X, final double Y, final double Z) {
+ public static ColorCieLch convertCIELabtoCIELCH(final double L, final double a, final double b) {
+ // atan2(y,x) returns atan(y/x)
+ final double atanba = Math.atan2(b, a); // Quadrant by signs
- double var_X = X / REF_X; // REF_X = 95.047 Observer= 2°, Illuminant= D65
- double var_Y = Y / REF_Y; // REF_Y = 100.000
- double var_Z = Z / REF_Z; // REF_Z = 108.883
+ final double h = atanba > 0 //
+ ? Math.toDegrees(atanba) //
+ : Math.toDegrees(atanba) + 360;
- // Pivot XÝZ:
- var_X = pivotXYZ(var_X);
- var_Y = pivotXYZ(var_Y);
- var_Z = pivotXYZ(var_Z);
+ // L = L;
+ final double C = Math.sqrt(square(a) + square(b));
- // Math.max added from https://github.com/muak/ColorMinePortable/blob/master/ColorMinePortable/ColorSpaces/Conversions/LabConverter.cs
- final double L = Math.max(0, 116 * var_Y - 16);
- final double a = 500 * (var_X - var_Y);
- final double b = 200 * (var_Y - var_Z);
- return new ColorCieLab(L, a, b);
+ return new ColorCieLch(L, C, h);
+ }
+
+ public static ColorDin99Lab convertCIELabToDIN99bLab(final ColorCieLab cie) {
+ return convertCIELabToDIN99bLab(cie.L, cie.a, cie.b);
+ }
+
+ public static ColorDin99Lab convertCIELabToDIN99bLab(final double L, final double a, final double b) {
+ final double FAC_1 = 100.0 / Math.log(129.0 / 50.0); // = 105.51
+ final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
+ final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
+ final double ang = Math.toRadians(16.0);
+
+ final double L99 = kE * FAC_1 * Math.log(1. + 0.0158 * L);
+ double a99 = 0.0;
+ double b99 = 0.0;
+ if (a != 0.0 || b != 0.0) {
+ final double e = a * Math.cos(ang) + b * Math.sin(ang);
+ final double f = 0.7 * (b * Math.cos(ang) - a * Math.sin(ang));
+ final double G = Math.sqrt(e * e + f * f);
+ if (G != 0.) {
+ final double k = Math.log(1. + 0.045 * G) / (0.045 * kCH * kE * G);
+ a99 = k * e;
+ b99 = k * f;
+ }
+ }
+ return new ColorDin99Lab(L99, a99, b99);
+ }
+
+ /**
+ * DIN99o.
+ *
+ * @param cie CIE color.
+ * @return CIELab colors converted to DIN99oLab color space.
+ * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
+ */
+ public static ColorDin99Lab convertCIELabToDIN99oLab(final ColorCieLab cie) {
+ return convertCIELabToDIN99oLab(cie.L, cie.a, cie.b);
+ }
+
+ /**
+ * DIN99o.
+ *
+ * @param L lightness of color.
+ * @param a position between red and green.
+ * @param b position between yellow and blue.
+ * @return CIBELab colors converted to DIN99oLab color space.
+ * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
+ */
+ public static ColorDin99Lab convertCIELabToDIN99oLab(final double L, final double a, final double b) {
+ final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
+ final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
+ final double FAC_1 = 100.0 / Math.log(139.0 / 100.0); // L99 scaling factor = 303.67100547050995
+ final double ang = Math.toRadians(26.0);
+
+ final double L99o = FAC_1 / kE * Math.log(1 + 0.0039 * L); // Lightness correction kE
+ double a99o = 0.0;
+ double b99o = 0.0;
+ if (a != 0.0 || b != 0.0) {
+ final double eo = a * Math.cos(ang) + b * Math.sin(ang); // a stretching
+ final double fo = 0.83 * (b * Math.cos(ang) - a * Math.sin(ang)); // b rotation/stretching
+ final double Go = Math.sqrt(eo * eo + fo * fo); // chroma
+ final double C99o = Math.log(1.0 + 0.075 * Go) / (0.0435 * kCH * kE); // factor for chroma compression and viewing conditions
+ final double heofo = Math.atan2(fo, eo); // arctan in four quadrants
+ final double h99o = heofo + ang; // hue rotation
+ a99o = C99o * Math.cos(h99o);
+ b99o = C99o * Math.sin(h99o);
+ }
+ return new ColorDin99Lab(L99o, a99o, b99o);
}
public static ColorXyz convertCIELabtoXYZ(final ColorCieLab cielab) {
@@ -81,114 +182,104 @@ public final class ColorConversions {
return new ColorXyz(X, Y, Z);
}
- public static ColorHunterLab convertXYZtoHunterLab(final ColorXyz xyz) {
- return convertXYZtoHunterLab(xyz.X, xyz.Y, xyz.Z);
- }
- public static ColorHunterLab convertXYZtoHunterLab(final double X,
- final double Y, final double Z) {
- final double L = 10 * Math.sqrt(Y);
- final double a = Y == 0.0 ? 0.0 : 17.5 * (((1.02 * X) - Y) / Math.sqrt(Y));
- final double b = Y == 0.0 ? 0.0 : 7 * ((Y - (0.847 * Z)) / Math.sqrt(Y));
-
- return new ColorHunterLab(L, a, b);
- }
-
- public static ColorXyz convertHunterLabtoXYZ(final ColorHunterLab cielab) {
- return convertHunterLabtoXYZ(cielab.L, cielab.a, cielab.b);
+ public static ColorCieLab convertCIELCHtoCIELab(final ColorCieLch cielch) {
+ return convertCIELCHtoCIELab(cielch.L, cielch.C, cielch.h);
}
- public static ColorXyz convertHunterLabtoXYZ(final double L, final double a,
- final double b) {
- final double var_Y = L / 10;
- final double var_X = a / 17.5 * L / 10;
- final double var_Z = b / 7 * L / 10;
+ public static ColorCieLab convertCIELCHtoCIELab(final double L, final double C, final double H) {
+ // Where CIE-H° = 0 ÷ 360°
- final double Y = Math.pow(var_Y, 2);
- final double X = (var_X + Y) / 1.02;
- final double Z = -(var_Z - Y) / 0.847;
+ // CIE-L* = CIE-L;
+ final double a = Math.cos(degree_2_radian(H)) * C;
+ final double b = Math.sin(degree_2_radian(H)) * C;
- return new ColorXyz(X, Y, Z);
+ return new ColorCieLab(L, a, b);
}
-
- public static int convertXYZtoRGB(final ColorXyz xyz) {
- return convertXYZtoRGB(xyz.X, xyz.Y, xyz.Z);
+ public static ColorXyz convertCIELuvtoXYZ(final ColorCieLuv cielch) {
+ return convertCIELuvtoXYZ(cielch.L, cielch.u, cielch.v);
}
- public static int convertXYZtoRGB(final double X, final double Y, final double Z) {
- // Observer = 2°, Illuminant = D65
- final double var_X = X / 100.0; // Where X = 0 ÷ 95.047
- final double var_Y = Y / 100.0; // Where Y = 0 ÷ 100.000
- final double var_Z = Z / 100.0; // Where Z = 0 ÷ 108.883
+ public static ColorXyz convertCIELuvtoXYZ(final double L, final double u, final double v) {
+ // problems here with div by zero
- // see: https://github.com/StanfordHCI/c3/blob/master/java/src/edu/stanford/vis/color/LAB.java
- double var_R = var_X * 3.2404542 + var_Y * -1.5371385 + var_Z * -0.4985314;
- double var_G = var_X * -0.9692660 + var_Y * 1.8760108 + var_Z * 0.0415560;
- double var_B = var_X * 0.0556434 + var_Y * -0.2040259 + var_Z * 1.0572252;
+ double var_Y = (L + 16) / 116.0;
+ var_Y = unPivotXYZ(var_Y);
- // Attention: A lot of sources do list these values with less precision. But it makes a visual difference:
- // double var_R = var_X * 3.2406 + var_Y * -1.5372 + var_Z * -0.4986;
- // double var_G = var_X * -0.9689 + var_Y * 1.8758 + var_Z * 0.0415;
- // double var_B = var_X * 0.0557 + var_Y * -0.2040 + var_Z * 1.0570;
+ final double ref_U = (4 * REF_X) / (REF_X + (15 * REF_Y) + (3 * REF_Z));
+ final double ref_V = (9 * REF_Y) / (REF_X + (15 * REF_Y) + (3 * REF_Z));
+ final double var_U = u / (13 * L) + ref_U;
+ final double var_V = v / (13 * L) + ref_V;
- var_R = pivotRGB(var_R);
- var_G = pivotRGB(var_G);
- var_B = pivotRGB(var_B);
+ final double Y = var_Y * 100;
+ final double X = -(9 * Y * var_U) / ((var_U - 4) * var_V - var_U * var_V);
+ final double Z = (9 * Y - (15 * var_V * Y) - (var_V * X)) / (3 * var_V);
- final double R = (var_R * 255);
- final double G = (var_G * 255);
- final double B = (var_B * 255);
- return convertRGBtoRGB(R, G, B);
+ return new ColorXyz(X, Y, Z);
}
- // See also c# implementation:
- // https://github.com/muak/ColorMinePortable/blob/master/ColorMinePortable/ColorSpaces/Conversions/XyzConverter.cs
- public static ColorXyz convertRGBtoXYZ(final int rgb) {
- final int r = 0xff & (rgb >> 16);
- final int g = 0xff & (rgb >> 8);
- final int b = 0xff & (rgb >> 0);
+ public static ColorCmy convertCMYKtoCMY(final ColorCmyk cmyk) {
+ return convertCMYKtoCMY(cmyk.C, cmyk.M, cmyk.Y, cmyk.K);
+ }
- double var_R = r / 255.0; // Where R = 0 ÷ 255
- double var_G = g / 255.0; // Where G = 0 ÷ 255
- double var_B = b / 255.0; // Where B = 0 ÷ 255
+ public static ColorCmy convertCMYKtoCMY(double C, double M, double Y,
+ final double K) {
+ // Where CMYK and CMY values = 0 ÷ 1
- // Pivot RGB:
- var_R = unPivotRGB(var_R);
- var_G = unPivotRGB(var_G);
- var_B = unPivotRGB(var_B);
+ C = (C * (1 - K) + K);
+ M = (M * (1 - K) + K);
+ Y = (Y * (1 - K) + K);
- var_R *= 100;
- var_G *= 100;
- var_B *= 100;
+ return new ColorCmy(C, M, Y);
+ }
- // Observer. = 2°, Illuminant = D65
- // see: https://github.com/StanfordHCI/c3/blob/master/java/src/edu/stanford/vis/color/LAB.java
- final double X = var_R * 0.4124564 + var_G * 0.3575761 + var_B * 0.1804375;
- final double Y = var_R * 0.2126729 + var_G * 0.7151522 + var_B * 0.0721750;
- final double Z = var_R * 0.0193339 + var_G * 0.1191920 + var_B * 0.9503041;
+ public static int convertCMYKtoRGB(final int c, final int m, final int y, final int k) {
+ final double C = c / 255.0;
+ final double M = m / 255.0;
+ final double Y = y / 255.0;
+ final double K = k / 255.0;
- // Attention: A lot of sources do list these values with less precision. But it makes a visual difference:
- // final double X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805;
- // final double Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722;
- // final double Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505;
+ return convertCMYtoRGB(convertCMYKtoCMY(C, M, Y, K));
+ }
- return new ColorXyz(X, Y, Z);
+ public static int convertCMYKtoRGB_Adobe(final int sc, final int sm, final int sy,
+ final int sk) {
+ final int red = 255 - (sc + sk);
+ final int green = 255 - (sm + sk);
+ final int blue = 255 - (sy + sk);
+
+ return convertRGBtoRGB(red, green, blue);
}
- public static ColorCmy convertRGBtoCMY(final int rgb) {
- final int R = 0xff & (rgb >> 16);
- final int G = 0xff & (rgb >> 8);
- final int B = 0xff & (rgb >> 0);
+ public static ColorCmyk convertCMYtoCMYK(final ColorCmy cmy) {
+ // Where CMYK and CMY values = 0 ÷ 1
- // RGB values = 0 ÷ 255
- // CMY values = 0 ÷ 1
+ double C = cmy.C;
+ double M = cmy.M;
+ double Y = cmy.Y;
- final double C = 1 - (R / 255.0);
- final double M = 1 - (G / 255.0);
- final double Y = 1 - (B / 255.0);
+ double var_K = 1.0;
- return new ColorCmy(C, M, Y);
+ if (C < var_K) {
+ var_K = C;
+ }
+ if (M < var_K) {
+ var_K = M;
+ }
+ if (Y < var_K) {
+ var_K = Y;
+ }
+ if (var_K == 1) { // Black
+ C = 0;
+ M = 0;
+ Y = 0;
+ } else {
+ C = (C - var_K) / (1 - var_K);
+ M = (M - var_K) / (1 - var_K);
+ Y = (Y - var_K) / (1 - var_K);
+ }
+ return new ColorCmyk(C, M, Y, var_K);
}
public static int convertCMYtoRGB(final ColorCmy cmy) {
@@ -201,65 +292,216 @@ public final class ColorConversions {
// CMY values = 0 ÷ 1
// RGB values = 0 ÷ 255
- final double R = (1 - cmy.C) * 255.0;
- final double G = (1 - cmy.M) * 255.0;
- final double B = (1 - cmy.Y) * 255.0;
+ final double R = (1 - cmy.C) * 255.0;
+ final double G = (1 - cmy.M) * 255.0;
+ final double B = (1 - cmy.Y) * 255.0;
+
+ return convertRGBtoRGB(R, G, B);
+ }
+
+ public static ColorCieLab convertDIN99bLabToCIELab(final ColorDin99Lab dinb) {
+ return convertDIN99bLabToCIELab(dinb.L99, dinb.a99, dinb.b99);
+ }
+
+ public static ColorCieLab convertDIN99bLabToCIELab(final double L99b, final double a99b, final double b99b) {
+ final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
+ final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
+ final double FAC_1 = 100.0 / Math.log(129.0 / 50.0); // L99 scaling factor = 105.50867113783109
+ final double ang = Math.toRadians(16.0);
+
+ final double hef = Math.atan2(b99b, a99b);
+ final double C = Math.sqrt(a99b * a99b + b99b * b99b);
+ final double G = (Math.exp(0.045 * C * kCH * kE) - 1.0) / 0.045;
+ final double e = G * Math.cos(hef);
+ final double f = G * Math.sin(hef) / 0.7;
+
+ final double L = (Math.exp(L99b * kE / FAC_1) - 1.) / 0.0158;
+ final double a = e * Math.cos(ang) - f * Math.sin(ang);
+ final double b = e * Math.sin(ang) + f * Math.cos(ang);
+ return new ColorCieLab(L, a, b);
+ }
+
+ /**
+ * DIN99o.
+ *
+ * @param dino color in the DIN99 color space.
+ * @return DIN99o colors converted to CIELab color space.
+ * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
+ */
+ public static ColorCieLab convertDIN99oLabToCIELab(final ColorDin99Lab dino) {
+ return convertDIN99oLabToCIELab(dino.L99, dino.a99, dino.b99);
+ }
+
+ /**
+ * DIN99o.
+ *
+ * @param L99o lightness of color.
+ * @param a99o position between red and green.
+ * @param b99o position between yellow and blue.
+ * @return DIN99o colors converted to CIELab color space.
+ * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
+ */
+ public static ColorCieLab convertDIN99oLabToCIELab(final double L99o, final double a99o, final double b99o) {
+ final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
+ final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
+ final double FAC_1 = 100.0 / Math.log(139.0 / 100.0); // L99 scaling factor = 303.67100547050995
+ final double ang = Math.toRadians(26.0);
+
+ final double L = (Math.exp(L99o * kE / FAC_1) - 1.0) / 0.0039;
+
+ final double h99ef = Math.atan2(b99o, a99o); // arctan in four quadrants
+
+ final double heofo = h99ef - ang; // backwards hue rotation
+
+ final double C99 = Math.sqrt(a99o * a99o + b99o * b99o); // DIN99 chroma
+ final double G = (Math.exp(0.0435 * kE * kCH * C99) - 1.0) / 0.075; // factor for chroma decompression and viewing conditions
+ final double e = G * Math.cos(heofo);
+ final double f = G * Math.sin(heofo);
+
+ final double a = e * Math.cos(ang) - f / 0.83 * Math.sin(ang); // rotation by 26 degrees
+ final double b = e * Math.sin(ang) + f / 0.83 * Math.cos(ang); // rotation by 26 degrees
+
+ return new ColorCieLab(L, a, b);
+ }
+
+ public static int convertHSLtoRGB(final ColorHsl hsl) {
+ return convertHSLtoRGB(hsl.H, hsl.S, hsl.L);
+ }
+
+ public static int convertHSLtoRGB(final double H, final double S, final double L) {
+ double R, G, B;
+
+ if (S == 0) {
+ // HSL values = 0 ÷ 1
+ R = L * 255; // RGB results = 0 ÷ 255
+ G = L * 255;
+ B = L * 255;
+ } else {
+ double var_2;
+
+ if (L < 0.5) {
+ var_2 = L * (1 + S);
+ } else {
+ var_2 = (L + S) - (S * L);
+ }
+
+ final double var_1 = 2 * L - var_2;
+
+ R = 255 * convertHuetoRGB(var_1, var_2, H + (1 / 3.0));
+ G = 255 * convertHuetoRGB(var_1, var_2, H);
+ B = 255 * convertHuetoRGB(var_1, var_2, H - (1 / 3.0));
+ }
+
+ return convertRGBtoRGB(R, G, B);
+ }
+
+ public static int convertHSVtoRGB(final ColorHsv HSV) {
+ return convertHSVtoRGB(HSV.H, HSV.S, HSV.V);
+ }
+
+ public static int convertHSVtoRGB(final double H, final double S, final double V) {
+ double R, G, B;
+
+ if (S == 0) {
+ // HSV values = 0 ÷ 1
+ R = V * 255;
+ G = V * 255;
+ B = V * 255;
+ } else {
+ double var_h = H * 6;
+ if (var_h == 6) {
+ var_h = 0; // H must be < 1
+ }
+ final double var_i = Math.floor(var_h); // Or ... var_i = floor( var_h )
+ final double var_1 = V * (1 - S);
+ final double var_2 = V * (1 - S * (var_h - var_i));
+ final double var_3 = V * (1 - S * (1 - (var_h - var_i)));
+
+ double var_r, var_g, var_b;
+
+ if (var_i == 0) {
+ var_r = V;
+ var_g = var_3;
+ var_b = var_1;
+ } else if (var_i == 1) {
+ var_r = var_2;
+ var_g = V;
+ var_b = var_1;
+ } else if (var_i == 2) {
+ var_r = var_1;
+ var_g = V;
+ var_b = var_3;
+ } else if (var_i == 3) {
+ var_r = var_1;
+ var_g = var_2;
+ var_b = V;
+ } else if (var_i == 4) {
+ var_r = var_3;
+ var_g = var_1;
+ var_b = V;
+ } else {
+ var_r = V;
+ var_g = var_1;
+ var_b = var_2;
+ }
+
+ R = var_r * 255; // RGB results = 0 ÷ 255
+ G = var_g * 255;
+ B = var_b * 255;
+ }
return convertRGBtoRGB(R, G, B);
}
- public static ColorCmyk convertCMYtoCMYK(final ColorCmy cmy) {
- // Where CMYK and CMY values = 0 ÷ 1
-
- double C = cmy.C;
- double M = cmy.M;
- double Y = cmy.Y;
-
- double var_K = 1.0;
-
- if (C < var_K) {
- var_K = C;
+ private static double convertHuetoRGB(final double v1, final double v2, double vH) {
+ if (vH < 0) {
+ vH += 1;
}
- if (M < var_K) {
- var_K = M;
+ if (vH > 1) {
+ vH -= 1;
}
- if (Y < var_K) {
- var_K = Y;
+ if ((6 * vH) < 1) {
+ return (v1 + (v2 - v1) * 6 * vH);
}
- if (var_K == 1) { // Black
- C = 0;
- M = 0;
- Y = 0;
- } else {
- C = (C - var_K) / (1 - var_K);
- M = (M - var_K) / (1 - var_K);
- Y = (Y - var_K) / (1 - var_K);
+ if ((2 * vH) < 1) {
+ return (v2);
}
- return new ColorCmyk(C, M, Y, var_K);
+ if ((3 * vH) < 2) {
+ return (v1 + (v2 - v1) * ((2 / 3.0) - vH) * 6);
+ }
+ return (v1);
}
- public static ColorCmy convertCMYKtoCMY(final ColorCmyk cmyk) {
- return convertCMYKtoCMY(cmyk.C, cmyk.M, cmyk.Y, cmyk.K);
+ public static ColorXyz convertHunterLabtoXYZ(final ColorHunterLab cielab) {
+ return convertHunterLabtoXYZ(cielab.L, cielab.a, cielab.b);
}
- public static ColorCmy convertCMYKtoCMY(double C, double M, double Y,
- final double K) {
- // Where CMYK and CMY values = 0 ÷ 1
+ public static ColorXyz convertHunterLabtoXYZ(final double L, final double a,
+ final double b) {
+ final double var_Y = L / 10;
+ final double var_X = a / 17.5 * L / 10;
+ final double var_Z = b / 7 * L / 10;
- C = (C * (1 - K) + K);
- M = (M * (1 - K) + K);
- Y = (Y * (1 - K) + K);
+ final double Y = Math.pow(var_Y, 2);
+ final double X = (var_X + Y) / 1.02;
+ final double Z = -(var_Z - Y) / 0.847;
- return new ColorCmy(C, M, Y);
+ return new ColorXyz(X, Y, Z);
}
- public static int convertCMYKtoRGB(final int c, final int m, final int y, final int k) {
- final double C = c / 255.0;
- final double M = m / 255.0;
- final double Y = y / 255.0;
- final double K = k / 255.0;
+ public static ColorCmy convertRGBtoCMY(final int rgb) {
+ final int R = 0xff & (rgb >> 16);
+ final int G = 0xff & (rgb >> 8);
+ final int B = 0xff & (rgb >> 0);
- return convertCMYtoRGB(convertCMYKtoCMY(C, M, Y, K));
+ // RGB values = 0 ÷ 255
+ // CMY values = 0 ÷ 1
+
+ final double C = 1 - (R / 255.0);
+ final double M = 1 - (G / 255.0);
+ final double Y = 1 - (B / 255.0);
+
+ return new ColorCmy(C, M, Y);
}
public static ColorHsl convertRGBtoHSL(final int rgb) {
@@ -337,56 +579,6 @@ public final class ColorConversions {
return new ColorHsl(H, S, L);
}
- public static int convertHSLtoRGB(final ColorHsl hsl) {
- return convertHSLtoRGB(hsl.H, hsl.S, hsl.L);
- }
-
- public static int convertHSLtoRGB(final double H, final double S, final double L) {
- double R, G, B;
-
- if (S == 0) {
- // HSL values = 0 ÷ 1
- R = L * 255; // RGB results = 0 ÷ 255
- G = L * 255;
- B = L * 255;
- } else {
- double var_2;
-
- if (L < 0.5) {
- var_2 = L * (1 + S);
- } else {
- var_2 = (L + S) - (S * L);
- }
-
- final double var_1 = 2 * L - var_2;
-
- R = 255 * convertHuetoRGB(var_1, var_2, H + (1 / 3.0));
- G = 255 * convertHuetoRGB(var_1, var_2, H);
- B = 255 * convertHuetoRGB(var_1, var_2, H - (1 / 3.0));
- }
-
- return convertRGBtoRGB(R, G, B);
- }
-
- private static double convertHuetoRGB(final double v1, final double v2, double vH) {
- if (vH < 0) {
- vH += 1;
- }
- if (vH > 1) {
- vH -= 1;
- }
- if ((6 * vH) < 1) {
- return (v1 + (v2 - v1) * 6 * vH);
- }
- if ((2 * vH) < 1) {
- return (v2);
- }
- if ((3 * vH) < 2) {
- return (v1 + (v2 - v1) * ((2 / 3.0) - vH) * 6);
- }
- return (v1);
- }
-
public static ColorHsv convertRGBtoHSV(final int rgb) {
final int R = 0xff & (rgb >> 16);
final int G = 0xff & (rgb >> 8);
@@ -446,117 +638,6 @@ public final class ColorConversions {
return new ColorHsv(H, S, V);
}
- public static int convertHSVtoRGB(final ColorHsv HSV) {
- return convertHSVtoRGB(HSV.H, HSV.S, HSV.V);
- }
-
- public static int convertHSVtoRGB(final double H, final double S, final double V) {
- double R, G, B;
-
- if (S == 0) {
- // HSV values = 0 ÷ 1
- R = V * 255;
- G = V * 255;
- B = V * 255;
- } else {
- double var_h = H * 6;
- if (var_h == 6) {
- var_h = 0; // H must be < 1
- }
- final double var_i = Math.floor(var_h); // Or ... var_i = floor( var_h )
- final double var_1 = V * (1 - S);
- final double var_2 = V * (1 - S * (var_h - var_i));
- final double var_3 = V * (1 - S * (1 - (var_h - var_i)));
-
- double var_r, var_g, var_b;
-
- if (var_i == 0) {
- var_r = V;
- var_g = var_3;
- var_b = var_1;
- } else if (var_i == 1) {
- var_r = var_2;
- var_g = V;
- var_b = var_1;
- } else if (var_i == 2) {
- var_r = var_1;
- var_g = V;
- var_b = var_3;
- } else if (var_i == 3) {
- var_r = var_1;
- var_g = var_2;
- var_b = V;
- } else if (var_i == 4) {
- var_r = var_3;
- var_g = var_1;
- var_b = V;
- } else {
- var_r = V;
- var_g = var_1;
- var_b = var_2;
- }
-
- R = var_r * 255; // RGB results = 0 ÷ 255
- G = var_g * 255;
- B = var_b * 255;
- }
-
- return convertRGBtoRGB(R, G, B);
- }
-
- public static int convertCMYKtoRGB_Adobe(final int sc, final int sm, final int sy,
- final int sk) {
- final int red = 255 - (sc + sk);
- final int green = 255 - (sm + sk);
- final int blue = 255 - (sy + sk);
-
- return convertRGBtoRGB(red, green, blue);
- }
-
- private static double square(final double f) {
- return f * f;
- }
-
- public static int convertCIELabtoARGBTest(final int cieL, final int cieA, final int cieB) {
- double X, Y, Z;
- {
-
- double var_Y = ((cieL * 100.0 / 255.0) + 16.0) / 116.0;
- double var_X = cieA / 500.0 + var_Y;
- double var_Z = var_Y - cieB / 200.0;
-
- var_X = unPivotXYZ(var_X);
- var_Y = unPivotXYZ(var_Y);
- var_Z = unPivotXYZ(var_Z);
-
- X = REF_X * var_X; // REF_X = 95.047 Observer= 2°, Illuminant= D65
- Y = REF_Y * var_Y; // REF_Y = 100.000
- Z = REF_Z * var_Z; // REF_Z = 108.883
-
- }
-
- double R, G, B;
- {
- final double var_X = X / 100; // X = From 0 to REF_X
- final double var_Y = Y / 100; // Y = From 0 to REF_Y
- final double var_Z = Z / 100; // Z = From 0 to REF_Y
-
- double var_R = var_X * 3.2406 + var_Y * -1.5372 + var_Z * -0.4986;
- double var_G = var_X * -0.9689 + var_Y * 1.8758 + var_Z * 0.0415;
- double var_B = var_X * 0.0557 + var_Y * -0.2040 + var_Z * 1.0570;
-
- var_R = pivotRGB(var_R);
- var_G = pivotRGB(var_G);
- var_B = pivotRGB(var_B);
-
- R = (var_R * 255);
- G = (var_G * 255);
- B = (var_B * 255);
- }
-
- return convertRGBtoRGB(R, G, B);
- }
-
private static int convertRGBtoRGB(final double R, final double G, final double B) {
int red = (int) Math.round(R);
int green = (int) Math.round(G);
@@ -581,44 +662,60 @@ public final class ColorConversions {
return (alpha << 24) | (red << 16) | (green << 8) | (blue << 0);
}
- public static ColorCieLch convertCIELabtoCIELCH(final ColorCieLab cielab) {
- return convertCIELabtoCIELCH(cielab.L, cielab.a, cielab.b);
- }
+ // See also c# implementation:
+ // https://github.com/muak/ColorMinePortable/blob/master/ColorMinePortable/ColorSpaces/Conversions/XyzConverter.cs
+ public static ColorXyz convertRGBtoXYZ(final int rgb) {
+ final int r = 0xff & (rgb >> 16);
+ final int g = 0xff & (rgb >> 8);
+ final int b = 0xff & (rgb >> 0);
+
+ double var_R = r / 255.0; // Where R = 0 ÷ 255
+ double var_G = g / 255.0; // Where G = 0 ÷ 255
+ double var_B = b / 255.0; // Where B = 0 ÷ 255
- public static ColorCieLch convertCIELabtoCIELCH(final double L, final double a, final double b) {
- // atan2(y,x) returns atan(y/x)
- final double atanba = Math.atan2(b, a); // Quadrant by signs
+ // Pivot RGB:
+ var_R = unPivotRGB(var_R);
+ var_G = unPivotRGB(var_G);
+ var_B = unPivotRGB(var_B);
- final double h = atanba > 0 //
- ? Math.toDegrees(atanba) //
- : Math.toDegrees(atanba) + 360;
+ var_R *= 100;
+ var_G *= 100;
+ var_B *= 100;
- // L = L;
- final double C = Math.sqrt(square(a) + square(b));
+ // Observer. = 2°, Illuminant = D65
+ // see: https://github.com/StanfordHCI/c3/blob/master/java/src/edu/stanford/vis/color/LAB.java
+ final double X = var_R * 0.4124564 + var_G * 0.3575761 + var_B * 0.1804375;
+ final double Y = var_R * 0.2126729 + var_G * 0.7151522 + var_B * 0.0721750;
+ final double Z = var_R * 0.0193339 + var_G * 0.1191920 + var_B * 0.9503041;
- return new ColorCieLch(L, C, h);
- }
+ // Attention: A lot of sources do list these values with less precision. But it makes a visual difference:
+ // final double X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805;
+ // final double Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722;
+ // final double Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505;
- public static ColorCieLab convertCIELCHtoCIELab(final ColorCieLch cielch) {
- return convertCIELCHtoCIELab(cielch.L, cielch.C, cielch.h);
+ return new ColorXyz(X, Y, Z);
}
- public static ColorCieLab convertCIELCHtoCIELab(final double L, final double C, final double H) {
- // Where CIE-H° = 0 ÷ 360°
+ public static ColorCieLab convertXYZtoCIELab(final ColorXyz xyz) {
+ return convertXYZtoCIELab(xyz.X, xyz.Y, xyz.Z);
+ }
- // CIE-L* = CIE-L;
- final double a = Math.cos(degree_2_radian(H)) * C;
- final double b = Math.sin(degree_2_radian(H)) * C;
+ public static ColorCieLab convertXYZtoCIELab(final double X, final double Y, final double Z) {
- return new ColorCieLab(L, a, b);
- }
+ double var_X = X / REF_X; // REF_X = 95.047 Observer= 2°, Illuminant= D65
+ double var_Y = Y / REF_Y; // REF_Y = 100.000
+ double var_Z = Z / REF_Z; // REF_Z = 108.883
- public static double degree_2_radian(final double degree) {
- return degree * Math.PI / 180.0;
- }
+ // Pivot XÝZ:
+ var_X = pivotXYZ(var_X);
+ var_Y = pivotXYZ(var_Y);
+ var_Z = pivotXYZ(var_Z);
- public static double radian_2_degree(final double radian) {
- return radian * 180.0 / Math.PI;
+ // Math.max added from https://github.com/muak/ColorMinePortable/blob/master/ColorMinePortable/ColorSpaces/Conversions/LabConverter.cs
+ final double L = Math.max(0, 116 * var_Y - 16);
+ final double a = 500 * (var_X - var_Y);
+ final double b = 200 * (var_Y - var_Z);
+ return new ColorCieLab(L, a, b);
}
public static ColorCieLuv convertXYZtoCIELuv(final ColorXyz xyz) {
@@ -654,159 +751,51 @@ public final class ColorConversions {
return new ColorCieLuv(L, u, v);
}
- public static ColorXyz convertCIELuvtoXYZ(final ColorCieLuv cielch) {
- return convertCIELuvtoXYZ(cielch.L, cielch.u, cielch.v);
- }
-
- public static ColorXyz convertCIELuvtoXYZ(final double L, final double u, final double v) {
- // problems here with div by zero
-
- double var_Y = (L + 16) / 116.0;
- var_Y = unPivotXYZ(var_Y);
-
- final double ref_U = (4 * REF_X) / (REF_X + (15 * REF_Y) + (3 * REF_Z));
- final double ref_V = (9 * REF_Y) / (REF_X + (15 * REF_Y) + (3 * REF_Z));
- final double var_U = u / (13 * L) + ref_U;
- final double var_V = v / (13 * L) + ref_V;
-
- final double Y = var_Y * 100;
- final double X = -(9 * Y * var_U) / ((var_U - 4) * var_V - var_U * var_V);
- final double Z = (9 * Y - (15 * var_V * Y) - (var_V * X)) / (3 * var_V);
-
- return new ColorXyz(X, Y, Z);
- }
-
- public static ColorDin99Lab convertCIELabToDIN99bLab(final ColorCieLab cie) {
- return convertCIELabToDIN99bLab(cie.L, cie.a, cie.b);
+ public static ColorHunterLab convertXYZtoHunterLab(final ColorXyz xyz) {
+ return convertXYZtoHunterLab(xyz.X, xyz.Y, xyz.Z);
}
- public static ColorDin99Lab convertCIELabToDIN99bLab(final double L, final double a, final double b) {
- final double FAC_1 = 100.0 / Math.log(129.0 / 50.0); // = 105.51
- final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
- final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
- final double ang = Math.toRadians(16.0);
+ public static ColorHunterLab convertXYZtoHunterLab(final double X,
+ final double Y, final double Z) {
+ final double L = 10 * Math.sqrt(Y);
+ final double a = Y == 0.0 ? 0.0 : 17.5 * (((1.02 * X) - Y) / Math.sqrt(Y));
+ final double b = Y == 0.0 ? 0.0 : 7 * ((Y - (0.847 * Z)) / Math.sqrt(Y));
- final double L99 = kE * FAC_1 * Math.log(1. + 0.0158 * L);
- double a99 = 0.0;
- double b99 = 0.0;
- if (a != 0.0 || b != 0.0) {
- final double e = a * Math.cos(ang) + b * Math.sin(ang);
- final double f = 0.7 * (b * Math.cos(ang) - a * Math.sin(ang));
- final double G = Math.sqrt(e * e + f * f);
- if (G != 0.) {
- final double k = Math.log(1. + 0.045 * G) / (0.045 * kCH * kE * G);
- a99 = k * e;
- b99 = k * f;
- }
- }
- return new ColorDin99Lab(L99, a99, b99);
+ return new ColorHunterLab(L, a, b);
}
- public static ColorCieLab convertDIN99bLabToCIELab(final ColorDin99Lab dinb) {
- return convertDIN99bLabToCIELab(dinb.L99, dinb.a99, dinb.b99);
+ public static int convertXYZtoRGB(final ColorXyz xyz) {
+ return convertXYZtoRGB(xyz.X, xyz.Y, xyz.Z);
}
- public static ColorCieLab convertDIN99bLabToCIELab(final double L99b, final double a99b, final double b99b) {
- final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
- final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
- final double FAC_1 = 100.0 / Math.log(129.0 / 50.0); // L99 scaling factor = 105.50867113783109
- final double ang = Math.toRadians(16.0);
-
- final double hef = Math.atan2(b99b, a99b);
- final double C = Math.sqrt(a99b * a99b + b99b * b99b);
- final double G = (Math.exp(0.045 * C * kCH * kE) - 1.0) / 0.045;
- final double e = G * Math.cos(hef);
- final double f = G * Math.sin(hef) / 0.7;
-
- final double L = (Math.exp(L99b * kE / FAC_1) - 1.) / 0.0158;
- final double a = e * Math.cos(ang) - f * Math.sin(ang);
- final double b = e * Math.sin(ang) + f * Math.cos(ang);
- return new ColorCieLab(L, a, b);
- }
+ public static int convertXYZtoRGB(final double X, final double Y, final double Z) {
+ // Observer = 2°, Illuminant = D65
+ final double var_X = X / 100.0; // Where X = 0 ÷ 95.047
+ final double var_Y = Y / 100.0; // Where Y = 0 ÷ 100.000
+ final double var_Z = Z / 100.0; // Where Z = 0 ÷ 108.883
- /**
- * DIN99o.
- *
- * @param cie CIE color.
- * @return CIELab colors converted to DIN99oLab color space.
- * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
- */
- public static ColorDin99Lab convertCIELabToDIN99oLab(final ColorCieLab cie) {
- return convertCIELabToDIN99oLab(cie.L, cie.a, cie.b);
- }
+ // see: https://github.com/StanfordHCI/c3/blob/master/java/src/edu/stanford/vis/color/LAB.java
+ double var_R = var_X * 3.2404542 + var_Y * -1.5371385 + var_Z * -0.4985314;
+ double var_G = var_X * -0.9692660 + var_Y * 1.8760108 + var_Z * 0.0415560;
+ double var_B = var_X * 0.0556434 + var_Y * -0.2040259 + var_Z * 1.0572252;
- /**
- * DIN99o.
- *
- * @param L lightness of color.
- * @param a position between red and green.
- * @param b position between yellow and blue.
- * @return CIBELab colors converted to DIN99oLab color space.
- * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
- */
- public static ColorDin99Lab convertCIELabToDIN99oLab(final double L, final double a, final double b) {
- final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
- final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
- final double FAC_1 = 100.0 / Math.log(139.0 / 100.0); // L99 scaling factor = 303.67100547050995
- final double ang = Math.toRadians(26.0);
+ // Attention: A lot of sources do list these values with less precision. But it makes a visual difference:
+ // double var_R = var_X * 3.2406 + var_Y * -1.5372 + var_Z * -0.4986;
+ // double var_G = var_X * -0.9689 + var_Y * 1.8758 + var_Z * 0.0415;
+ // double var_B = var_X * 0.0557 + var_Y * -0.2040 + var_Z * 1.0570;
- final double L99o = FAC_1 / kE * Math.log(1 + 0.0039 * L); // Lightness correction kE
- double a99o = 0.0;
- double b99o = 0.0;
- if (a != 0.0 || b != 0.0) {
- final double eo = a * Math.cos(ang) + b * Math.sin(ang); // a stretching
- final double fo = 0.83 * (b * Math.cos(ang) - a * Math.sin(ang)); // b rotation/stretching
- final double Go = Math.sqrt(eo * eo + fo * fo); // chroma
- final double C99o = Math.log(1.0 + 0.075 * Go) / (0.0435 * kCH * kE); // factor for chroma compression and viewing conditions
- final double heofo = Math.atan2(fo, eo); // arctan in four quadrants
- final double h99o = heofo + ang; // hue rotation
- a99o = C99o * Math.cos(h99o);
- b99o = C99o * Math.sin(h99o);
- }
- return new ColorDin99Lab(L99o, a99o, b99o);
- }
+ var_R = pivotRGB(var_R);
+ var_G = pivotRGB(var_G);
+ var_B = pivotRGB(var_B);
- /**
- * DIN99o.
- *
- * @param dino color in the DIN99 color space.
- * @return DIN99o colors converted to CIELab color space.
- * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
- */
- public static ColorCieLab convertDIN99oLabToCIELab(final ColorDin99Lab dino) {
- return convertDIN99oLabToCIELab(dino.L99, dino.a99, dino.b99);
+ final double R = (var_R * 255);
+ final double G = (var_G * 255);
+ final double B = (var_B * 255);
+ return convertRGBtoRGB(R, G, B);
}
- /**
- * DIN99o.
- *
- * @param L99o lightness of color.
- * @param a99o position between red and green.
- * @param b99o position between yellow and blue.
- * @return DIN99o colors converted to CIELab color space.
- * @see <a href="https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum">https://de.wikipedia.org/w/index.php?title=Diskussion:DIN99-Farbraum</a>
- */
- public static ColorCieLab convertDIN99oLabToCIELab(final double L99o, final double a99o, final double b99o) {
- final double kE = 1.0; // brightness factor, 1.0 for CIE reference conditions
- final double kCH = 1.0; // chroma and hue factor, 1.0 for CIE reference conditions
- final double FAC_1 = 100.0 / Math.log(139.0 / 100.0); // L99 scaling factor = 303.67100547050995
- final double ang = Math.toRadians(26.0);
-
- final double L = (Math.exp(L99o * kE / FAC_1) - 1.0) / 0.0039;
-
- final double h99ef = Math.atan2(b99o, a99o); // arctan in four quadrants
-
- final double heofo = h99ef - ang; // backwards hue rotation
-
- final double C99 = Math.sqrt(a99o * a99o + b99o * b99o); // DIN99 chroma
- final double G = (Math.exp(0.0435 * kE * kCH * C99) - 1.0) / 0.075; // factor for chroma decompression and viewing conditions
- final double e = G * Math.cos(heofo);
- final double f = G * Math.sin(heofo);
-
- final double a = e * Math.cos(ang) - f / 0.83 * Math.sin(ang); // rotation by 26 degrees
- final double b = e * Math.sin(ang) + f / 0.83 * Math.cos(ang); // rotation by 26 degrees
-
- return new ColorCieLab(L, a, b);
+ public static double degree_2_radian(final double degree) {
+ return degree * Math.PI / 180.0;
}
private static double pivotRGB(double n) {
@@ -818,20 +807,28 @@ public final class ColorConversions {
return n;
}
- private static double unPivotRGB(double n) {
- if (n > 0.04045) {
- n = Math.pow((n + 0.055) / 1.055, 2.4);
+ private static double pivotXYZ(double n) {
+ if (n > XYZ_t0) {
+ n = Math.pow(n, 1 / 3.0);
} else {
- n = n / 12.92;
+ n = XYZ_m * n + 16 / 116.0;
}
return n;
}
- private static double pivotXYZ(double n) {
- if (n > XYZ_t0) {
- n = Math.pow(n, 1 / 3.0);
+ public static double radian_2_degree(final double radian) {
+ return radian * 180.0 / Math.PI;
+ }
+
+ private static double square(final double f) {
+ return f * f;
+ }
+
+ private static double unPivotRGB(double n) {
+ if (n > 0.04045) {
+ n = Math.pow((n + 0.055) / 1.055, 2.4);
} else {
- n = XYZ_m * n + 16 / 116.0;
+ n = n / 12.92;
}
return n;
}
@@ -846,4 +843,7 @@ public final class ColorConversions {
return n;
}
+ private ColorConversions() {
+ }
+
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorDin99Lab.java b/src/main/java/org/apache/commons/imaging/color/ColorDin99Lab.java
index 496bdad7..c9d6eccd 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorDin99Lab.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorDin99Lab.java
@@ -39,11 +39,6 @@ public final class ColorDin99Lab {
this.b99 = b99;
}
- @Override
- public String toString() {
- return "{L: " + L99 + ", a: " + a99 + ", b: " + b99 + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -79,4 +74,9 @@ public final class ColorDin99Lab {
result = 31 * result + (int) (temp ^ temp >>> 32);
return result;
}
+
+ @Override
+ public String toString() {
+ return "{L: " + L99 + ", a: " + a99 + ", b: " + b99 + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorHsl.java b/src/main/java/org/apache/commons/imaging/color/ColorHsl.java
index 46ba6bbc..447dd42b 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorHsl.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorHsl.java
@@ -87,11 +87,6 @@ public final class ColorHsl {
this.L = L;
}
- @Override
- public String toString() {
- return "{H: " + H + ", S: " + S + ", L: " + L + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -127,4 +122,9 @@ public final class ColorHsl {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{H: " + H + ", S: " + S + ", L: " + L + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorHsv.java b/src/main/java/org/apache/commons/imaging/color/ColorHsv.java
index 7bb8981b..1650dbc1 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorHsv.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorHsv.java
@@ -87,11 +87,6 @@ public final class ColorHsv {
this.V = V;
}
- @Override
- public String toString() {
- return "{H: " + H + ", S: " + S + ", V: " + V + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -127,4 +122,9 @@ public final class ColorHsv {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{H: " + H + ", S: " + S + ", V: " + V + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorHunterLab.java b/src/main/java/org/apache/commons/imaging/color/ColorHunterLab.java
index 12ceea00..758846d7 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorHunterLab.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorHunterLab.java
@@ -87,11 +87,6 @@ public final class ColorHunterLab {
this.b = b;
}
- @Override
- public String toString() {
- return "{L: " + L + ", a: " + a + ", b: " + b + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -127,4 +122,9 @@ public final class ColorHunterLab {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{L: " + L + ", a: " + a + ", b: " + b + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/color/ColorXyz.java b/src/main/java/org/apache/commons/imaging/color/ColorXyz.java
index ec26acd1..8a5a209d 100644
--- a/src/main/java/org/apache/commons/imaging/color/ColorXyz.java
+++ b/src/main/java/org/apache/commons/imaging/color/ColorXyz.java
@@ -88,11 +88,6 @@ public final class ColorXyz {
this.Z = Z;
}
- @Override
- public String toString() {
- return "{X: " + X + ", Y: " + Y + ", Z: " + Z + "}";
- }
-
@Override
public boolean equals(final Object o) {
if (this == o) {
@@ -128,4 +123,9 @@ public final class ColorXyz {
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
+
+ @Override
+ public String toString() {
+ return "{X: " + X + ", Y: " + Y + ", Z: " + Z + "}";
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/BasicCParser.java b/src/main/java/org/apache/commons/imaging/common/BasicCParser.java
index 38aaf7e2..78a30806 100644
--- a/src/main/java/org/apache/commons/imaging/common/BasicCParser.java
+++ b/src/main/java/org/apache/commons/imaging/common/BasicCParser.java
@@ -32,77 +32,134 @@ import org.apache.commons.imaging.ImageReadException;
* FIXME replace this by a parser generated via ANTLR (if we really need it?!)
*/
public class BasicCParser {
- private final PushbackInputStream is;
-
- public BasicCParser(final ByteArrayInputStream is) {
- this.is = new PushbackInputStream(is);
+ /**
+ * Parses the hexadecimal-base escape-sequence found at index {@code i} of {@code string}.
+ *
+ * <p>Helper-function for {@code unescapeString()}.</p>
+ *
+ * @param i the index of the escape-sequence in the string
+ * @param stringBuilder the stringBuilder to append the escape-char to
+ * @param string the string whose chars are parsed
+ * @return the new index i
+ * @since 1.0-alpha3
+ */
+ private static int appendHex(int i, final StringBuilder stringBuilder, final String string)
+ throws ImageReadException {
+ if (i + 2 >= string.length()) {
+ throw new ImageReadException(
+ "Parsing XPM file failed, "
+ + "hex constant in string too short");
+ }
+ final char hex1 = string.charAt(i + 1);
+ final char hex2 = string.charAt(i + 2);
+ i += 2;
+ int constant;
+ try {
+ constant = Integer.parseInt(hex1 + Character.toString(hex2), 16);
+ } catch (final NumberFormatException nfe) {
+ throw new ImageReadException(
+ "Parsing XPM file failed, "
+ + "hex constant invalid", nfe);
+ }
+ stringBuilder.append((char) constant);
+ return i;
}
- public String nextToken() throws IOException, ImageReadException {
- // I don't know how complete the C parsing in an XPM file
- // is meant to be, this is just the very basics...
-
- boolean inString = false;
- boolean inIdentifier = false;
- boolean hadBackSlash = false;
- final StringBuilder token = new StringBuilder();
- for (int c = is.read(); c != -1; c = is.read()) {
- if (inString) {
- switch (c) {
- case '\\':
- token.append('\\');
- hadBackSlash = !hadBackSlash;
- break;
- case '"':
- token.append('"');
- if (!hadBackSlash) {
- return token.toString();
- }
- hadBackSlash = false;
- break;
- case '\r':
- case '\n':
- throw new ImageReadException(
- "Unterminated string in XPM file");
- default:
- token.append((char) c);
- hadBackSlash = false;
- break;
- }
- } else if (inIdentifier) {
- if (!Character.isLetterOrDigit(c) && (c != '_')) {
- is.unread(c);
- return token.toString();
- }
- token.append((char) c);
- } else {
- if (c == '"') {
- token.append('"');
- inString = true;
- } else if (Character.isLetterOrDigit(c) || c == '_') {
- token.append((char) c);
- inIdentifier = true;
- } else if (c == '{' || c == '}' || c == '[' || c == ']'
- || c == '*' || c == ';' || c == '=' || c == ',') {
- token.append((char) c);
- return token.toString();
- } else if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
- // ignore
- } else {
- throw new ImageReadException(
- "Unhandled/invalid character '" + ((char) c)
- + "' found in XPM file");
- }
- }
+ /**
+ * Parses the octal-base escape-sequence found at index {@code i} of {@code string}.
+ *
+ * <p>Helper-function for {@code unescapeString()}.</p>
+ *
+ * @param i the index of the escape-sequence in the string
+ * @param stringBuilder the stringBuilder to append the escape-char to
+ * @param string the string whose chars are parsed
+ * @return the new index i
+ * @since 1.0-alpha3
+ */
+ private static int appendOct(int i, final StringBuilder stringBuilder, final String string) {
+ int length = 1;
+ if (i + 1 < string.length() && '0' <= string.charAt(i + 1)
+ && string.charAt(i + 1) <= '7') {
+ ++length;
}
-
- if (inIdentifier) {
- return token.toString();
+ if (i + 2 < string.length() && '0' <= string.charAt(i + 2)
+ && string.charAt(i + 2) <= '7') {
+ ++length;
}
- if (inString) {
- throw new ImageReadException("Unterminated string ends XMP file");
+ int constant = 0;
+ for (int j = 0; j < length; j++) {
+ constant *= 8;
+ constant += (string.charAt(i + j) - '0');
}
- return null;
+ i += length - 1;
+ stringBuilder.append((char) constant);
+ return i;
+ }
+
+ /**
+ * Parses the {@code i:th} escape-char in the input {@code string} and appends it to {@code stringBuilder}.
+ *
+ * <p>Helper-function for {@code unescapeString()}.</p>
+ *
+ * @param i the index of the escape-char in the string
+ * @param stringBuilder the stringBuilder to append the escape-char to
+ * @param string the string whose chars are parsed
+ * @return the new index i
+ * @since 1.0-alpha3
+ */
+ private static int parseEscape(int i, final StringBuilder stringBuilder, final String string)
+ throws ImageReadException {
+ final char c = string.charAt(i);
+ switch (c) {
+ case '\\':
+ stringBuilder.append('\\');
+ break;
+ case '"':
+ stringBuilder.append('"');
+ break;
+ case '\'':
+ stringBuilder.append('\'');
+ break;
+ case 'x':
+ i = appendHex(i, stringBuilder, string);
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ i = appendOct(i, stringBuilder, string);
+ break;
+ case 'a':
+ stringBuilder.append((char) 0x07);
+ break;
+ case 'b':
+ stringBuilder.append((char) 0x08);
+ break;
+ case 'f':
+ stringBuilder.append((char) 0x0c);
+ break;
+ case 'n':
+ stringBuilder.append((char) 0x0a);
+ break;
+ case 'r':
+ stringBuilder.append((char) 0x0d);
+ break;
+ case 't':
+ stringBuilder.append((char) 0x09);
+ break;
+ case 'v':
+ stringBuilder.append((char) 0x0b);
+ break;
+ default:
+ throw new ImageReadException("Parsing XPM file failed, "
+ + "invalid escape sequence");
+ }
+ return i;
+
}
public static ByteArrayOutputStream preprocess(final InputStream is,
@@ -342,135 +399,78 @@ public class BasicCParser {
}
}
- /**
- * Parses the hexadecimal-base escape-sequence found at index {@code i} of {@code string}.
- *
- * <p>Helper-function for {@code unescapeString()}.</p>
- *
- * @param i the index of the escape-sequence in the string
- * @param stringBuilder the stringBuilder to append the escape-char to
- * @param string the string whose chars are parsed
- * @return the new index i
- * @since 1.0-alpha3
- */
- private static int appendHex(int i, final StringBuilder stringBuilder, final String string)
- throws ImageReadException {
- if (i + 2 >= string.length()) {
- throw new ImageReadException(
- "Parsing XPM file failed, "
- + "hex constant in string too short");
- }
- final char hex1 = string.charAt(i + 1);
- final char hex2 = string.charAt(i + 2);
- i += 2;
- int constant;
- try {
- constant = Integer.parseInt(hex1 + Character.toString(hex2), 16);
- } catch (final NumberFormatException nfe) {
- throw new ImageReadException(
- "Parsing XPM file failed, "
- + "hex constant invalid", nfe);
- }
- stringBuilder.append((char) constant);
- return i;
- }
+ private final PushbackInputStream is;
- /**
- * Parses the octal-base escape-sequence found at index {@code i} of {@code string}.
- *
- * <p>Helper-function for {@code unescapeString()}.</p>
- *
- * @param i the index of the escape-sequence in the string
- * @param stringBuilder the stringBuilder to append the escape-char to
- * @param string the string whose chars are parsed
- * @return the new index i
- * @since 1.0-alpha3
- */
- private static int appendOct(int i, final StringBuilder stringBuilder, final String string) {
- int length = 1;
- if (i + 1 < string.length() && '0' <= string.charAt(i + 1)
- && string.charAt(i + 1) <= '7') {
- ++length;
- }
- if (i + 2 < string.length() && '0' <= string.charAt(i + 2)
- && string.charAt(i + 2) <= '7') {
- ++length;
- }
- int constant = 0;
- for (int j = 0; j < length; j++) {
- constant *= 8;
- constant += (string.charAt(i + j) - '0');
- }
- i += length - 1;
- stringBuilder.append((char) constant);
- return i;
+ public BasicCParser(final ByteArrayInputStream is) {
+ this.is = new PushbackInputStream(is);
}
- /**
- * Parses the {@code i:th} escape-char in the input {@code string} and appends it to {@code stringBuilder}.
- *
- * <p>Helper-function for {@code unescapeString()}.</p>
- *
- * @param i the index of the escape-char in the string
- * @param stringBuilder the stringBuilder to append the escape-char to
- * @param string the string whose chars are parsed
- * @return the new index i
- * @since 1.0-alpha3
- */
- private static int parseEscape(int i, final StringBuilder stringBuilder, final String string)
- throws ImageReadException {
- final char c = string.charAt(i);
- switch (c) {
- case '\\':
- stringBuilder.append('\\');
- break;
- case '"':
- stringBuilder.append('"');
- break;
- case '\'':
- stringBuilder.append('\'');
- break;
- case 'x':
- i = appendHex(i, stringBuilder, string);
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- i = appendOct(i, stringBuilder, string);
- break;
- case 'a':
- stringBuilder.append((char) 0x07);
- break;
- case 'b':
- stringBuilder.append((char) 0x08);
- break;
- case 'f':
- stringBuilder.append((char) 0x0c);
- break;
- case 'n':
- stringBuilder.append((char) 0x0a);
- break;
- case 'r':
- stringBuilder.append((char) 0x0d);
- break;
- case 't':
- stringBuilder.append((char) 0x09);
- break;
- case 'v':
- stringBuilder.append((char) 0x0b);
- break;
- default:
- throw new ImageReadException("Parsing XPM file failed, "
- + "invalid escape sequence");
+ public String nextToken() throws IOException, ImageReadException {
+ // I don't know how complete the C parsing in an XPM file
+ // is meant to be, this is just the very basics...
+
+ boolean inString = false;
+ boolean inIdentifier = false;
+ boolean hadBackSlash = false;
+ final StringBuilder token = new StringBuilder();
+ for (int c = is.read(); c != -1; c = is.read()) {
+ if (inString) {
+ switch (c) {
+ case '\\':
+ token.append('\\');
+ hadBackSlash = !hadBackSlash;
+ break;
+ case '"':
+ token.append('"');
+ if (!hadBackSlash) {
+ return token.toString();
+ }
+ hadBackSlash = false;
+ break;
+ case '\r':
+ case '\n':
+ throw new ImageReadException(
+ "Unterminated string in XPM file");
+ default:
+ token.append((char) c);
+ hadBackSlash = false;
+ break;
+ }
+ } else if (inIdentifier) {
+ if (!Character.isLetterOrDigit(c) && (c != '_')) {
+ is.unread(c);
+ return token.toString();
+ }
+ token.append((char) c);
+ } else {
+ if (c == '"') {
+ token.append('"');
+ inString = true;
+ } else if (Character.isLetterOrDigit(c) || c == '_') {
+ token.append((char) c);
+ inIdentifier = true;
+ } else if (c == '{' || c == '}' || c == '[' || c == ']'
+ || c == '*' || c == ';' || c == '=' || c == ',') {
+ token.append((char) c);
+ return token.toString();
+ } else if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
+ // ignore
+ } else {
+ throw new ImageReadException(
+ "Unhandled/invalid character '" + ((char) c)
+ + "' found in XPM file");
+ }
+ }
}
- return i;
+ if (inIdentifier) {
+ return token.toString();
+ }
+ if (inString) {
+ throw new ImageReadException("Unterminated string ends XMP file");
+ }
+ return null;
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/BinaryConstant.java b/src/main/java/org/apache/commons/imaging/common/BinaryConstant.java
index 7e299759..2b0e2532 100644
--- a/src/main/java/org/apache/commons/imaging/common/BinaryConstant.java
+++ b/src/main/java/org/apache/commons/imaging/common/BinaryConstant.java
@@ -27,18 +27,6 @@ public class BinaryConstant {
this.value = value.clone();
}
- @Override
- public boolean equals(final Object obj) {
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof BinaryConstant)) {
- return false;
- }
- final BinaryConstant other = (BinaryConstant) obj;
- return equals(other.value);
- }
-
public boolean equals(final byte[] bytes) {
return Arrays.equals(value, bytes);
}
@@ -56,14 +44,26 @@ public class BinaryConstant {
}
@Override
- public int hashCode() {
- return Arrays.hashCode(value);
+ public boolean equals(final Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (!(obj instanceof BinaryConstant)) {
+ return false;
+ }
+ final BinaryConstant other = (BinaryConstant) obj;
+ return equals(other.value);
}
public byte get(final int i) {
return value[i];
}
+ @Override
+ public int hashCode() {
+ return Arrays.hashCode(value);
+ }
+
public int size() {
return value.length;
}
diff --git a/src/main/java/org/apache/commons/imaging/common/BinaryFileParser.java b/src/main/java/org/apache/commons/imaging/common/BinaryFileParser.java
index 4ecbb78f..8db14425 100644
--- a/src/main/java/org/apache/commons/imaging/common/BinaryFileParser.java
+++ b/src/main/java/org/apache/commons/imaging/common/BinaryFileParser.java
@@ -30,10 +30,6 @@ public class BinaryFileParser {
// default byte order for Java, many file formats.
private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
- public BinaryFileParser(final ByteOrder byteOrder) {
- this.byteOrder = byteOrder;
- }
-
/**
* Constructs a BinaryFileParser with the default, big-endian, byte order.
*/
@@ -41,25 +37,10 @@ public class BinaryFileParser {
// as above
}
- protected void setByteOrder(final ByteOrder byteOrder) {
+ public BinaryFileParser(final ByteOrder byteOrder) {
this.byteOrder = byteOrder;
}
- public ByteOrder getByteOrder() {
- return byteOrder;
- }
-
- protected final void debugNumber(final String msg, final int data, final int bytes) {
- try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
- debugNumber(pw, msg, data, bytes);
- pw.flush();
- sw.flush();
- LOGGER.fine(sw.toString());
- } catch (final IOException e) {
- LOGGER.log(Level.SEVERE, e.getMessage(), e);
- }
- }
-
protected final void debugNumber(final PrintWriter pw, final String msg, final int data, final int bytes) {
pw.print(msg + ": " + data + " (");
int byteData = data;
@@ -74,4 +55,23 @@ public class BinaryFileParser {
pw.println(") [0x" + Integer.toHexString(data) + ", " + Integer.toBinaryString(data) + "]");
pw.flush();
}
+
+ protected final void debugNumber(final String msg, final int data, final int bytes) {
+ try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
+ debugNumber(pw, msg, data, bytes);
+ pw.flush();
+ sw.flush();
+ LOGGER.fine(sw.toString());
+ } catch (final IOException e) {
+ LOGGER.log(Level.SEVERE, e.getMessage(), e);
+ }
+ }
+
+ public ByteOrder getByteOrder() {
+ return byteOrder;
+ }
+
+ protected void setByteOrder(final ByteOrder byteOrder) {
+ this.byteOrder = byteOrder;
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/BinaryFunctions.java b/src/main/java/org/apache/commons/imaging/common/BinaryFunctions.java
index 9d2051f8..583d1723 100644
--- a/src/main/java/org/apache/commons/imaging/common/BinaryFunctions.java
+++ b/src/main/java/org/apache/commons/imaging/common/BinaryFunctions.java
@@ -34,22 +34,21 @@ public final class BinaryFunctions {
private static final Logger LOGGER = Logger.getLogger(BinaryFunctions.class.getName());
- private BinaryFunctions() {
+ public static int charsToQuad(final char c1, final char c2, final char c3, final char c4) {
+ return (((0xff & c1) << 24) | ((0xff & c2) << 16) | ((0xff & c3) << 8) | ((0xff & c4) << 0));
}
- public static boolean startsWith(final byte[] haystack, final byte[] needle) {
- if (needle == null) {
- return false;
- }
- if (haystack == null) {
+ public static boolean compareBytes(final byte[] a, final int aStart, final byte[] b,
+ final int bStart, final int length) {
+ if (a.length < (aStart + length)) {
return false;
}
- if (needle.length > haystack.length) {
+ if (b.length < (bStart + length)) {
return false;
}
- for (int i = 0; i < needle.length; i++) {
- if (needle[i] != haystack[i]) {
+ for (int i = 0; i < length; i++) {
+ if (a[aStart + i] != b[bStart + i]) {
return false;
}
}
@@ -57,156 +56,109 @@ public final class BinaryFunctions {
return true;
}
- public static boolean startsWith(final byte[] haystack, final BinaryConstant needle) {
- if ((haystack == null) || (haystack.length < needle.size())) {
- return false;
- }
-
- for (int i = 0; i < needle.size(); i++) {
- if (haystack[i] != needle.get(i)) {
- return false;
- }
+ public static void copyStreamToStream(final InputStream is, final OutputStream os)
+ throws IOException {
+ final byte[] buffer = new byte[1024];
+ int read;
+ while ((read = is.read(buffer)) > 0) {
+ os.write(buffer, 0, read);
}
-
- return true;
}
- public static byte readByte(final String name, final InputStream is, final String exception)
- throws IOException {
- final int result = is.read();
- if ((result < 0)) {
- throw new IOException(exception);
- }
- return (byte) (0xff & result);
+ public static int findNull(final byte[] src) {
+ return findNull(src, 0);
}
- public static byte[] readBytes(final String name, final InputStream is, final int length)
- throws IOException {
- final String exception = name + " could not be read.";
- return readBytes(name, is, length, exception);
+ public static int findNull(final byte[] src, final int start) {
+ for (int i = start; i < src.length; i++) {
+ if (src[i] == 0) {
+ return i;
+ }
+ }
+ return -1;
}
- public static byte[] readBytes(final String name, final InputStream is, final int length,
- final String exception) throws IOException {
+ public static byte[] getRAFBytes(final RandomAccessFile raf, final long pos,
+ final int length, final String exception) throws IOException {
if (length < 0) {
throw new IOException(String.format("%s, invalid length: %d", exception, length));
}
final byte[] result = new byte[length];
+
+ raf.seek(pos);
+
int read = 0;
while (read < length) {
- final int count = is.read(result, read, length - read);
+ final int count = raf.read(result, read, length - read);
if (count < 0) {
- throw new IOException(exception + " count: " + count
- + " read: " + read + " length: " + length);
+ throw new IOException(exception);
}
read += count;
}
return result;
- }
- public static byte[] readBytes(final InputStream is, final int count) throws IOException {
- return readBytes("", is, count, "Unexpected EOF");
- }
-
- public static void readAndVerifyBytes(final InputStream is, final byte[] expected,
- final String exception) throws ImageReadException, IOException {
- for (final byte element : expected) {
- final int data = is.read();
- final byte b = (byte) (0xff & data);
-
- if (data < 0) {
- throw new ImageReadException("Unexpected EOF.");
- }
-
- if (b != element) {
- throw new ImageReadException(exception);
- }
- }
}
- public static void readAndVerifyBytes(final InputStream is,
- final BinaryConstant expected, final String exception)
- throws ImageReadException, IOException {
- for (int i = 0; i < expected.size(); i++) {
- final int data = is.read();
- final byte b = (byte) (0xff & data);
-
- if (data < 0) {
- throw new ImageReadException("Unexpected EOF.");
- }
-
- if (b != expected.get(i)) {
- throw new ImageReadException(exception);
- }
- }
+ public static byte[] getStreamBytes(final InputStream is) throws IOException {
+ final ByteArrayOutputStream os = new ByteArrayOutputStream();
+ copyStreamToStream(is, os);
+ return os.toByteArray();
}
- public static void skipBytes(final InputStream is, final long length, final String exception)
- throws IOException {
- long total = 0;
- while (length != total) {
- final long skipped = is.skip(length - total);
- if (skipped < 1) {
- throw new IOException(exception + " (" + skipped + ")");
- }
- total += skipped;
+ public static byte[] head(final byte[] bytes, int count) {
+ if (count > bytes.length) {
+ count = bytes.length;
}
+ return slice(bytes, 0, count);
}
- public static byte[] remainingBytes(final String name, final byte[] bytes, final int count) {
- return slice(bytes, count, bytes.length - count);
+ public static void printByteBits(final String msg, final byte i) {
+ LOGGER.finest(msg + ": '" + Integer.toBinaryString(0xff & i));
}
- public static byte[] slice(final byte[] bytes, final int start, final int count) {
- final byte[] result = new byte[count];
- System.arraycopy(bytes, start, result, 0, count);
- return result;
- }
+ public static void printCharQuad(final PrintWriter pw, final String msg, final int i) {
+ pw.println(msg + ": '" + (char) (0xff & (i >> 24))
+ + (char) (0xff & (i >> 16)) + (char) (0xff & (i >> 8))
+ + (char) (0xff & (i >> 0)) + "'");
- public static byte[] head(final byte[] bytes, int count) {
- if (count > bytes.length) {
- count = bytes.length;
- }
- return slice(bytes, 0, count);
}
- public static boolean compareBytes(final byte[] a, final int aStart, final byte[] b,
- final int bStart, final int length) {
- if (a.length < (aStart + length)) {
- return false;
- }
- if (b.length < (bStart + length)) {
- return false;
- }
+ public static void printCharQuad(final String msg, final int i) {
+ LOGGER.finest(msg + ": '" + (char) (0xff & (i >> 24))
+ + (char) (0xff & (i >> 16)) + (char) (0xff & (i >> 8))
+ + (char) (0xff & (i >> 0)) + "'");
- for (int i = 0; i < length; i++) {
- if (a[aStart + i] != b[bStart + i]) {
- return false;
- }
- }
+ }
- return true;
+ /**
+ * Convert a quad into a byte array.
+ * @param quad quad
+ * @return a byte array
+ */
+ public static byte[] quadsToByteArray(final int quad) {
+ final byte[] arr = new byte[4];
+ arr[0] = (byte) (quad >> 24);
+ arr[1] = (byte) (quad >> 16);
+ arr[2] = (byte) (quad >> 8);
+ arr[3] = (byte) quad;
+ return arr;
}
- public static int read4Bytes(final String name, final InputStream is,
+ public static int read2Bytes(final String name, final InputStream is,
final String exception, final ByteOrder byteOrder) throws IOException {
final int byte0 = is.read();
final int byte1 = is.read();
- final int byte2 = is.read();
- final int byte3 = is.read();
- if ((byte0 | byte1 | byte2 | byte3) < 0) {
+ if ((byte0 | byte1) < 0) {
throw new IOException(exception);
}
final int result;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
- result = (byte0 << 24) | (byte1 << 16)
- | (byte2 << 8) | (byte3 << 0);
+ result = (byte0 << 8) | byte1;
} else {
- result = (byte3 << 24) | (byte2 << 16)
- | (byte1 << 8) | (byte0 << 0);
+ result = (byte1 << 8) | byte0;
}
return result;
@@ -233,58 +185,102 @@ public final class BinaryFunctions {
return result;
}
- public static int read2Bytes(final String name, final InputStream is,
+ public static int read4Bytes(final String name, final InputStream is,
final String exception, final ByteOrder byteOrder) throws IOException {
final int byte0 = is.read();
final int byte1 = is.read();
- if ((byte0 | byte1) < 0) {
+ final int byte2 = is.read();
+ final int byte3 = is.read();
+ if ((byte0 | byte1 | byte2 | byte3) < 0) {
throw new IOException(exception);
}
final int result;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
- result = (byte0 << 8) | byte1;
+ result = (byte0 << 24) | (byte1 << 16)
+ | (byte2 << 8) | (byte3 << 0);
} else {
- result = (byte1 << 8) | byte0;
+ result = (byte3 << 24) | (byte2 << 16)
+ | (byte1 << 8) | (byte0 << 0);
}
return result;
}
- public static void printCharQuad(final String msg, final int i) {
- LOGGER.finest(msg + ": '" + (char) (0xff & (i >> 24))
- + (char) (0xff & (i >> 16)) + (char) (0xff & (i >> 8))
- + (char) (0xff & (i >> 0)) + "'");
+ public static void readAndVerifyBytes(final InputStream is,
+ final BinaryConstant expected, final String exception)
+ throws ImageReadException, IOException {
+ for (int i = 0; i < expected.size(); i++) {
+ final int data = is.read();
+ final byte b = (byte) (0xff & data);
+ if (data < 0) {
+ throw new ImageReadException("Unexpected EOF.");
+ }
+
+ if (b != expected.get(i)) {
+ throw new ImageReadException(exception);
+ }
+ }
}
- public static void printCharQuad(final PrintWriter pw, final String msg, final int i) {
- pw.println(msg + ": '" + (char) (0xff & (i >> 24))
- + (char) (0xff & (i >> 16)) + (char) (0xff & (i >> 8))
- + (char) (0xff & (i >> 0)) + "'");
+ public static void readAndVerifyBytes(final InputStream is, final byte[] expected,
+ final String exception) throws ImageReadException, IOException {
+ for (final byte element : expected) {
+ final int data = is.read();
+ final byte b = (byte) (0xff & data);
+ if (data < 0) {
+ throw new ImageReadException("Unexpected EOF.");
+ }
+
+ if (b != element) {
+ throw new ImageReadException(exception);
+ }
+ }
}
- public static void printByteBits(final String msg, final byte i) {
- LOGGER.finest(msg + ": '" + Integer.toBinaryString(0xff & i));
+ public static byte readByte(final String name, final InputStream is, final String exception)
+ throws IOException {
+ final int result = is.read();
+ if ((result < 0)) {
+ throw new IOException(exception);
+ }
+ return (byte) (0xff & result);
}
- public static int charsToQuad(final char c1, final char c2, final char c3, final char c4) {
- return (((0xff & c1) << 24) | ((0xff & c2) << 16) | ((0xff & c3) << 8) | ((0xff & c4) << 0));
+ public static byte[] readBytes(final InputStream is, final int count) throws IOException {
+ return readBytes("", is, count, "Unexpected EOF");
}
- /**
- * Convert a quad into a byte array.
- * @param quad quad
- * @return a byte array
- */
- public static byte[] quadsToByteArray(final int quad) {
- final byte[] arr = new byte[4];
- arr[0] = (byte) (quad >> 24);
- arr[1] = (byte) (quad >> 16);
- arr[2] = (byte) (quad >> 8);
- arr[3] = (byte) quad;
- return arr;
+ public static byte[] readBytes(final String name, final InputStream is, final int length)
+ throws IOException {
+ final String exception = name + " could not be read.";
+ return readBytes(name, is, length, exception);
+ }
+
+ public static byte[] readBytes(final String name, final InputStream is, final int length,
+ final String exception) throws IOException {
+ if (length < 0) {
+ throw new IOException(String.format("%s, invalid length: %d", exception, length));
+ }
+ final byte[] result = new byte[length];
+ int read = 0;
+ while (read < length) {
+ final int count = is.read(result, read, length - read);
+ if (count < 0) {
+ throw new IOException(exception + " count: " + count
+ + " read: " + read + " length: " + length);
+ }
+
+ read += count;
+ }
+
+ return result;
+ }
+
+ public static byte[] remainingBytes(final String name, final byte[] bytes, final int count) {
+ return slice(bytes, count, bytes.length - count);
}
/**
@@ -315,58 +311,62 @@ public final class BinaryFunctions {
return false;
}
- public static int findNull(final byte[] src) {
- return findNull(src, 0);
+ public static void skipBytes(final InputStream is, final long length) throws IOException {
+ skipBytes(is, length, "Couldn't skip bytes");
}
- public static int findNull(final byte[] src, final int start) {
- for (int i = start; i < src.length; i++) {
- if (src[i] == 0) {
- return i;
+ public static void skipBytes(final InputStream is, final long length, final String exception)
+ throws IOException {
+ long total = 0;
+ while (length != total) {
+ final long skipped = is.skip(length - total);
+ if (skipped < 1) {
+ throw new IOException(exception + " (" + skipped + ")");
}
+ total += skipped;
}
- return -1;
}
- public static byte[] getRAFBytes(final RandomAccessFile raf, final long pos,
- final int length, final String exception) throws IOException {
- if (length < 0) {
- throw new IOException(String.format("%s, invalid length: %d", exception, length));
- }
- final byte[] result = new byte[length];
+ public static byte[] slice(final byte[] bytes, final int start, final int count) {
+ final byte[] result = new byte[count];
+ System.arraycopy(bytes, start, result, 0, count);
+ return result;
+ }
- raf.seek(pos);
+ public static boolean startsWith(final byte[] haystack, final BinaryConstant needle) {
+ if ((haystack == null) || (haystack.length < needle.size())) {
+ return false;
+ }
- int read = 0;
- while (read < length) {
- final int count = raf.read(result, read, length - read);
- if (count < 0) {
- throw new IOException(exception);
+ for (int i = 0; i < needle.size(); i++) {
+ if (haystack[i] != needle.get(i)) {
+ return false;
}
-
- read += count;
}
- return result;
-
+ return true;
}
- public static void skipBytes(final InputStream is, final long length) throws IOException {
- skipBytes(is, length, "Couldn't skip bytes");
- }
+ public static boolean startsWith(final byte[] haystack, final byte[] needle) {
+ if (needle == null) {
+ return false;
+ }
+ if (haystack == null) {
+ return false;
+ }
+ if (needle.length > haystack.length) {
+ return false;
+ }
- public static void copyStreamToStream(final InputStream is, final OutputStream os)
- throws IOException {
- final byte[] buffer = new byte[1024];
- int read;
- while ((read = is.read(buffer)) > 0) {
- os.write(buffer, 0, read);
+ for (int i = 0; i < needle.length; i++) {
+ if (needle[i] != haystack[i]) {
+ return false;
+ }
}
+
+ return true;
}
- public static byte[] getStreamBytes(final InputStream is) throws IOException {
- final ByteArrayOutputStream os = new ByteArrayOutputStream();
- copyStreamToStream(is, os);
- return os.toByteArray();
+ private BinaryFunctions() {
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/ByteConversions.java b/src/main/java/org/apache/commons/imaging/common/ByteConversions.java
index c2b07bb4..612fb01f 100644
--- a/src/main/java/org/apache/commons/imaging/common/ByteConversions.java
+++ b/src/main/java/org/apache/commons/imaging/common/ByteConversions.java
@@ -24,87 +24,54 @@ import java.util.Arrays;
* byte arrays.
*/
public final class ByteConversions {
- private ByteConversions() {
- }
-
- public static byte[] toBytes(final short value, final ByteOrder byteOrder) {
- final byte[] result = new byte[2];
+ public static byte[] toBytes(final double value, final ByteOrder byteOrder) {
+ final byte[] result = new byte[8];
toBytes(value, byteOrder, result, 0);
return result;
}
- public static byte[] toBytes(final short[] values, final ByteOrder byteOrder) {
- return toBytes(values, 0, values.length, byteOrder);
- }
-
- private static byte[] toBytes(final short[] values, final int offset, final int length, final ByteOrder byteOrder) {
- final byte[] result = new byte[length * 2];
- for (int i = 0; i < length; i++) {
- toBytes(values[offset + i], byteOrder, result, i * 2);
- }
- return result;
- }
-
- private static void toBytes(final short value, final ByteOrder byteOrder, final byte[] result, final int offset) {
- if (byteOrder == ByteOrder.BIG_ENDIAN) {
- result[offset + 0] = (byte) (value >> 8);
- result[offset + 1] = (byte) (value >> 0);
+ private static void toBytes(final double value, final ByteOrder byteOrder, final byte[] result, final int offset) {
+ final long bits = Double.doubleToRawLongBits(value);
+ if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
+ result[offset + 0] = (byte) (0xff & (bits >> 0));
+ result[offset + 1] = (byte) (0xff & (bits >> 8));
+ result[offset + 2] = (byte) (0xff & (bits >> 16));
+ result[offset + 3] = (byte) (0xff & (bits >> 24));
+ result[offset + 4] = (byte) (0xff & (bits >> 32));
+ result[offset + 5] = (byte) (0xff & (bits >> 40));
+ result[offset + 6] = (byte) (0xff & (bits >> 48));
+ result[offset + 7] = (byte) (0xff & (bits >> 56));
} else {
- result[offset + 1] = (byte) (value >> 8);
- result[offset + 0] = (byte) (value >> 0);
+ result[offset + 7] = (byte) (0xff & (bits >> 0));
+ result[offset + 6] = (byte) (0xff & (bits >> 8));
+ result[offset + 5] = (byte) (0xff & (bits >> 16));
+ result[offset + 4] = (byte) (0xff & (bits >> 24));
+ result[offset + 3] = (byte) (0xff & (bits >> 32));
+ result[offset + 2] = (byte) (0xff & (bits >> 40));
+ result[offset + 1] = (byte) (0xff & (bits >> 48));
+ result[offset + 0] = (byte) (0xff & (bits >> 56));
}
}
- public static byte[] toBytes(final int value, final ByteOrder byteOrder) {
- final byte[] result = new byte[4];
- toBytes(value, byteOrder, result, 0);
- return result;
- }
-
- public static byte[] toBytes(final int[] values, final ByteOrder byteOrder) {
+ public static byte[] toBytes(final double[] values, final ByteOrder byteOrder) {
return toBytes(values, 0, values.length, byteOrder);
}
- private static byte[] toBytes(final int[] values, final int offset, final int length, final ByteOrder byteOrder) {
- final byte[] result = new byte[length * 4];
+ private static byte[] toBytes(final double[] values, final int offset,
+ final int length, final ByteOrder byteOrder) {
+ final byte[] result = new byte[length * 8];
for (int i = 0; i < length; i++) {
- toBytes(values[offset + i], byteOrder, result, i * 4);
+ toBytes(values[offset + i], byteOrder, result, i * 8);
}
return result;
}
- private static void toBytes(final int value, final ByteOrder byteOrder, final byte[] result, final int offset) {
- if (byteOrder == ByteOrder.BIG_ENDIAN) {
- result[offset + 0] = (byte) (value >> 24);
- result[offset + 1] = (byte) (value >> 16);
- result[offset + 2] = (byte) (value >> 8);
- result[offset + 3] = (byte) (value >> 0);
- } else {
- result[offset + 3] = (byte) (value >> 24);
- result[offset + 2] = (byte) (value >> 16);
- result[offset + 1] = (byte) (value >> 8);
- result[offset + 0] = (byte) (value >> 0);
- }
- }
-
public static byte[] toBytes(final float value, final ByteOrder byteOrder) {
final byte[] result = new byte[4];
toBytes(value, byteOrder, result, 0);
return result;
}
- public static byte[] toBytes(final float[] values, final ByteOrder byteOrder) {
- return toBytes(values, 0, values.length, byteOrder);
- }
-
- private static byte[] toBytes(final float[] values, final int offset, final int length, final ByteOrder byteOrder) {
- final byte[] result = new byte[length * 4];
- for (int i = 0; i < length; i++) {
- toBytes(values[offset + i], byteOrder, result, i * 4);
- }
- return result;
- }
-
private static void toBytes(final float value, final ByteOrder byteOrder, final byte[] result, final int offset) {
final int bits = Float.floatToRawIntBits(value);
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
@@ -120,67 +87,56 @@ public final class ByteConversions {
}
}
- public static byte[] toBytes(final double value, final ByteOrder byteOrder) {
- final byte[] result = new byte[8];
- toBytes(value, byteOrder, result, 0);
- return result;
- }
-
- public static byte[] toBytes(final double[] values, final ByteOrder byteOrder) {
+ public static byte[] toBytes(final float[] values, final ByteOrder byteOrder) {
return toBytes(values, 0, values.length, byteOrder);
}
- private static byte[] toBytes(final double[] values, final int offset,
- final int length, final ByteOrder byteOrder) {
- final byte[] result = new byte[length * 8];
+ private static byte[] toBytes(final float[] values, final int offset, final int length, final ByteOrder byteOrder) {
+ final byte[] result = new byte[length * 4];
for (int i = 0; i < length; i++) {
- toBytes(values[offset + i], byteOrder, result, i * 8);
+ toBytes(values[offset + i], byteOrder, result, i * 4);
}
return result;
}
- private static void toBytes(final double value, final ByteOrder byteOrder, final byte[] result, final int offset) {
- final long bits = Double.doubleToRawLongBits(value);
- if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
- result[offset + 0] = (byte) (0xff & (bits >> 0));
- result[offset + 1] = (byte) (0xff & (bits >> 8));
- result[offset + 2] = (byte) (0xff & (bits >> 16));
- result[offset + 3] = (byte) (0xff & (bits >> 24));
- result[offset + 4] = (byte) (0xff & (bits >> 32));
- result[offset + 5] = (byte) (0xff & (bits >> 40));
- result[offset + 6] = (byte) (0xff & (bits >> 48));
- result[offset + 7] = (byte) (0xff & (bits >> 56));
- } else {
- result[offset + 7] = (byte) (0xff & (bits >> 0));
- result[offset + 6] = (byte) (0xff & (bits >> 8));
- result[offset + 5] = (byte) (0xff & (bits >> 16));
- result[offset + 4] = (byte) (0xff & (bits >> 24));
- result[offset + 3] = (byte) (0xff & (bits >> 32));
- result[offset + 2] = (byte) (0xff & (bits >> 40));
- result[offset + 1] = (byte) (0xff & (bits >> 48));
- result[offset + 0] = (byte) (0xff & (bits >> 56));
- }
- }
-
- public static byte[] toBytes(final RationalNumber value, final ByteOrder byteOrder) {
- final byte[] result = new byte[8];
+ public static byte[] toBytes(final int value, final ByteOrder byteOrder) {
+ final byte[] result = new byte[4];
toBytes(value, byteOrder, result, 0);
return result;
}
- public static byte[] toBytes(final RationalNumber[] values, final ByteOrder byteOrder) {
+ private static void toBytes(final int value, final ByteOrder byteOrder, final byte[] result, final int offset) {
+ if (byteOrder == ByteOrder.BIG_ENDIAN) {
+ result[offset + 0] = (byte) (value >> 24);
+ result[offset + 1] = (byte) (value >> 16);
+ result[offset + 2] = (byte) (value >> 8);
+ result[offset + 3] = (byte) (value >> 0);
+ } else {
+ result[offset + 3] = (byte) (value >> 24);
+ result[offset + 2] = (byte) (value >> 16);
+ result[offset + 1] = (byte) (value >> 8);
+ result[offset + 0] = (byte) (value >> 0);
+ }
+ }
+
+ public static byte[] toBytes(final int[] values, final ByteOrder byteOrder) {
return toBytes(values, 0, values.length, byteOrder);
}
- private static byte[] toBytes(final RationalNumber[] values, final int offset,
- final int length, final ByteOrder byteOrder) {
- final byte[] result = new byte[length * 8];
+ private static byte[] toBytes(final int[] values, final int offset, final int length, final ByteOrder byteOrder) {
+ final byte[] result = new byte[length * 4];
for (int i = 0; i < length; i++) {
- toBytes(values[offset + i], byteOrder, result, i * 8);
+ toBytes(values[offset + i], byteOrder, result, i * 4);
}
return result;
}
+ public static byte[] toBytes(final RationalNumber value, final ByteOrder byteOrder) {
+ final byte[] result = new byte[8];
+ toBytes(value, byteOrder, result, 0);
+ return result;
+ }
+
private static void toBytes(final RationalNumber value, final ByteOrder byteOrder,
final byte[] result, final int offset) {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
@@ -204,74 +160,81 @@ public final class ByteConversions {
}
}
- public static short toShort(final byte[] bytes, final ByteOrder byteOrder) {
- return toShort(bytes, 0, byteOrder);
- }
-
- private static short toShort(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
- return (short) toUInt16(bytes, offset, byteOrder);
- }
-
- public static short[] toShorts(final byte[] bytes, final ByteOrder byteOrder) {
- return toShorts(bytes, 0, bytes.length, byteOrder);
+ public static byte[] toBytes(final RationalNumber[] values, final ByteOrder byteOrder) {
+ return toBytes(values, 0, values.length, byteOrder);
}
- private static short[] toShorts(final byte[] bytes, final int offset,
+ private static byte[] toBytes(final RationalNumber[] values, final int offset,
final int length, final ByteOrder byteOrder) {
- final short[] result = new short[length / 2];
- for (int i = 0; i < result.length; i++) {
- result[i] = toShort(bytes, offset + 2 * i, byteOrder);
+ final byte[] result = new byte[length * 8];
+ for (int i = 0; i < length; i++) {
+ toBytes(values[offset + i], byteOrder, result, i * 8);
}
return result;
}
- public static int toUInt16(final byte[] bytes, final ByteOrder byteOrder) {
- return toUInt16(bytes, 0, byteOrder);
+ public static byte[] toBytes(final short value, final ByteOrder byteOrder) {
+ final byte[] result = new byte[2];
+ toBytes(value, byteOrder, result, 0);
+ return result;
}
- public static int toUInt16(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
- final int byte0 = 0xff & bytes[offset + 0];
- final int byte1 = 0xff & bytes[offset + 1];
+ private static void toBytes(final short value, final ByteOrder byteOrder, final byte[] result, final int offset) {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
- return ((byte0 << 8) | byte1);
+ result[offset + 0] = (byte) (value >> 8);
+ result[offset + 1] = (byte) (value >> 0);
+ } else {
+ result[offset + 1] = (byte) (value >> 8);
+ result[offset + 0] = (byte) (value >> 0);
}
- return ((byte1 << 8) | byte0);
}
- public static int[] toUInt16s(final byte[] bytes, final ByteOrder byteOrder) {
- return toUInt16s(bytes, 0, bytes.length, byteOrder);
+ public static byte[] toBytes(final short[] values, final ByteOrder byteOrder) {
+ return toBytes(values, 0, values.length, byteOrder);
}
- private static int[] toUInt16s(final byte[] bytes, final int offset, final int length,
- final ByteOrder byteOrder) {
- final int[] result = new int[length / 2];
- Arrays.setAll(result, i -> toUInt16(bytes, offset + 2 * i, byteOrder));
+ private static byte[] toBytes(final short[] values, final int offset, final int length, final ByteOrder byteOrder) {
+ final byte[] result = new byte[length * 2];
+ for (int i = 0; i < length; i++) {
+ toBytes(values[offset + i], byteOrder, result, i * 2);
+ }
return result;
}
- public static int toInt(final byte[] bytes, final ByteOrder byteOrder) {
- return toInt(bytes, 0, byteOrder);
+ public static double toDouble(final byte[] bytes, final ByteOrder byteOrder) {
+ return toDouble(bytes, 0, byteOrder);
}
- public static int toInt(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
- final int byte0 = 0xff & bytes[offset + 0];
- final int byte1 = 0xff & bytes[offset + 1];
- final int byte2 = 0xff & bytes[offset + 2];
- final int byte3 = 0xff & bytes[offset + 3];
+ private static double toDouble(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
+ final long byte0 = 0xffL & bytes[offset + 0];
+ final long byte1 = 0xffL & bytes[offset + 1];
+ final long byte2 = 0xffL & bytes[offset + 2];
+ final long byte3 = 0xffL & bytes[offset + 3];
+ final long byte4 = 0xffL & bytes[offset + 4];
+ final long byte5 = 0xffL & bytes[offset + 5];
+ final long byte6 = 0xffL & bytes[offset + 6];
+ final long byte7 = 0xffL & bytes[offset + 7];
+ final long bits;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
- return (byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3;
+ bits = (byte0 << 56) | (byte1 << 48) | (byte2 << 40)
+ | (byte3 << 32) | (byte4 << 24) | (byte5 << 16)
+ | (byte6 << 8) | (byte7 << 0);
+ } else {
+ bits = (byte7 << 56) | (byte6 << 48) | (byte5 << 40)
+ | (byte4 << 32) | (byte3 << 24) | (byte2 << 16)
+ | (byte1 << 8) | (byte0 << 0);
}
- return (byte3 << 24) | (byte2 << 16) | (byte1 << 8) | byte0;
+ return Double.longBitsToDouble(bits);
}
- public static int[] toInts(final byte[] bytes, final ByteOrder byteOrder) {
- return toInts(bytes, 0, bytes.length, byteOrder);
+ public static double[] toDoubles(final byte[] bytes, final ByteOrder byteOrder) {
+ return toDoubles(bytes, 0, bytes.length, byteOrder);
}
- private static int[] toInts(final byte[] bytes, final int offset, final int length,
- final ByteOrder byteOrder) {
- final int[] result = new int[length / 4];
- Arrays.setAll(result, i -> toInt(bytes, offset + 4 * i, byteOrder));
+ private static double[] toDoubles(final byte[] bytes, final int offset,
+ final int length, final ByteOrder byteOrder) {
+ final double[] result = new double[length / 8];
+ Arrays.setAll(result, i -> toDouble(bytes, offset + 8 * i, byteOrder));
return result;
}
@@ -306,40 +269,29 @@ public final class ByteConversions {
return result;
}
- public static double toDouble(final byte[] bytes, final ByteOrder byteOrder) {
- return toDouble(bytes, 0, byteOrder);
+ public static int toInt(final byte[] bytes, final ByteOrder byteOrder) {
+ return toInt(bytes, 0, byteOrder);
}
- private static double toDouble(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
- final long byte0 = 0xffL & bytes[offset + 0];
- final long byte1 = 0xffL & bytes[offset + 1];
- final long byte2 = 0xffL & bytes[offset + 2];
- final long byte3 = 0xffL & bytes[offset + 3];
- final long byte4 = 0xffL & bytes[offset + 4];
- final long byte5 = 0xffL & bytes[offset + 5];
- final long byte6 = 0xffL & bytes[offset + 6];
- final long byte7 = 0xffL & bytes[offset + 7];
- final long bits;
+ public static int toInt(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
+ final int byte0 = 0xff & bytes[offset + 0];
+ final int byte1 = 0xff & bytes[offset + 1];
+ final int byte2 = 0xff & bytes[offset + 2];
+ final int byte3 = 0xff & bytes[offset + 3];
if (byteOrder == ByteOrder.BIG_ENDIAN) {
- bits = (byte0 << 56) | (byte1 << 48) | (byte2 << 40)
- | (byte3 << 32) | (byte4 << 24) | (byte5 << 16)
- | (byte6 << 8) | (byte7 << 0);
- } else {
- bits = (byte7 << 56) | (byte6 << 48) | (byte5 << 40)
- | (byte4 << 32) | (byte3 << 24) | (byte2 << 16)
- | (byte1 << 8) | (byte0 << 0);
+ return (byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3;
}
- return Double.longBitsToDouble(bits);
+ return (byte3 << 24) | (byte2 << 16) | (byte1 << 8) | byte0;
}
- public static double[] toDoubles(final byte[] bytes, final ByteOrder byteOrder) {
- return toDoubles(bytes, 0, bytes.length, byteOrder);
+ public static int[] toInts(final byte[] bytes, final ByteOrder byteOrder) {
+ return toInts(bytes, 0, bytes.length, byteOrder);
}
- private static double[] toDoubles(final byte[] bytes, final int offset,
- final int length, final ByteOrder byteOrder) {
- final double[] result = new double[length / 8];
- Arrays.setAll(result, i -> toDouble(bytes, offset + 8 * i, byteOrder));
+ private static int[] toInts(final byte[] bytes, final int offset, final int length,
+ final ByteOrder byteOrder) {
+ final int[] result = new int[length / 4];
+ Arrays.setAll(result, i -> toInt(bytes, offset + 4 * i, byteOrder));
return result;
}
@@ -401,4 +353,52 @@ public final class ByteConversions {
Arrays.setAll(result, i -> toRational(bytes, offset + 8 * i, byteOrder, unsignedType));
return result;
}
+
+ public static short toShort(final byte[] bytes, final ByteOrder byteOrder) {
+ return toShort(bytes, 0, byteOrder);
+ }
+
+ private static short toShort(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
+ return (short) toUInt16(bytes, offset, byteOrder);
+ }
+
+ public static short[] toShorts(final byte[] bytes, final ByteOrder byteOrder) {
+ return toShorts(bytes, 0, bytes.length, byteOrder);
+ }
+
+ private static short[] toShorts(final byte[] bytes, final int offset,
+ final int length, final ByteOrder byteOrder) {
+ final short[] result = new short[length / 2];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toShort(bytes, offset + 2 * i, byteOrder);
+ }
+ return result;
+ }
+
+ public static int toUInt16(final byte[] bytes, final ByteOrder byteOrder) {
+ return toUInt16(bytes, 0, byteOrder);
+ }
+
+ public static int toUInt16(final byte[] bytes, final int offset, final ByteOrder byteOrder) {
+ final int byte0 = 0xff & bytes[offset + 0];
+ final int byte1 = 0xff & bytes[offset + 1];
+ if (byteOrder == ByteOrder.BIG_ENDIAN) {
+ return ((byte0 << 8) | byte1);
+ }
+ return ((byte1 << 8) | byte0);
+ }
+
+ public static int[] toUInt16s(final byte[] bytes, final ByteOrder byteOrder) {
+ return toUInt16s(bytes, 0, bytes.length, byteOrder);
+ }
+
+ private static int[] toUInt16s(final byte[] bytes, final int offset, final int length,
+ final ByteOrder byteOrder) {
+ final int[] result = new int[length / 2];
+ Arrays.setAll(result, i -> toUInt16(bytes, offset + 2 * i, byteOrder));
+ return result;
+ }
+
+ private ByteConversions() {
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/FastByteArrayOutputStream.java b/src/main/java/org/apache/commons/imaging/common/FastByteArrayOutputStream.java
index b140cd1e..b068eb6f 100644
--- a/src/main/java/org/apache/commons/imaging/common/FastByteArrayOutputStream.java
+++ b/src/main/java/org/apache/commons/imaging/common/FastByteArrayOutputStream.java
@@ -32,14 +32,8 @@ class FastByteArrayOutputStream extends OutputStream {
bytes = new byte[length];
}
- @Override
- public void write(final int value) throws IOException {
- if (count >= bytes.length) {
- throw new IOException("Write exceeded expected length (" + count + ", " + bytes.length + ")");
- }
-
- bytes[count] = (byte) value;
- count++;
+ public int getBytesWritten() {
+ return count;
}
public byte[] toByteArray() {
@@ -49,7 +43,13 @@ class FastByteArrayOutputStream extends OutputStream {
return bytes;
}
- public int getBytesWritten() {
- return count;
+ @Override
+ public void write(final int value) throws IOException {
+ if (count >= bytes.length) {
+ throw new IOException("Write exceeded expected length (" + count + ", " + bytes.length + ")");
+ }
+
+ bytes[count] = (byte) value;
+ count++;
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/GenericImageMetadata.java b/src/main/java/org/apache/commons/imaging/common/GenericImageMetadata.java
index dc47f74e..11d9def8 100644
--- a/src/main/java/org/apache/commons/imaging/common/GenericImageMetadata.java
+++ b/src/main/java/org/apache/commons/imaging/common/GenericImageMetadata.java
@@ -20,17 +20,49 @@ import java.util.ArrayList;
import java.util.List;
public class GenericImageMetadata implements ImageMetadata {
- private static final String NEWLINE = System.getProperty("line.separator");
- private final List<ImageMetadataItem> items = new ArrayList<>();
+ public static class GenericImageMetadataItem implements ImageMetadataItem {
+ private final String keyword;
+ private final String text;
- public void add(final String keyword, final String text) {
- add(new GenericImageMetadataItem(keyword, text));
+ public GenericImageMetadataItem(final String keyword, final String text) {
+ this.keyword = keyword;
+ this.text = text;
+ }
+
+ public String getKeyword() {
+ return keyword;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ @Override
+ public String toString() {
+ return toString(null);
+ }
+
+ @Override
+ public String toString(final String prefix) {
+ final String result = keyword + ": " + text;
+ if (null != prefix) {
+ return prefix + result;
+ }
+ return result;
+ }
}
+ private static final String NEWLINE = System.getProperty("line.separator");
+
+ private final List<ImageMetadataItem> items = new ArrayList<>();
public void add(final ImageMetadataItem item) {
items.add(item);
}
+ public void add(final String keyword, final String text) {
+ add(new GenericImageMetadataItem(keyword, text));
+ }
+
@Override
public List<? extends ImageMetadataItem> getItems() {
return new ArrayList<>(items);
@@ -65,36 +97,4 @@ public class GenericImageMetadata implements ImageMetadata {
return result.toString();
}
- public static class GenericImageMetadataItem implements ImageMetadataItem {
- private final String keyword;
- private final String text;
-
- public GenericImageMetadataItem(final String keyword, final String text) {
- this.keyword = keyword;
- this.text = text;
- }
-
- public String getKeyword() {
- return keyword;
- }
-
- public String getText() {
- return text;
- }
-
- @Override
- public String toString() {
- return toString(null);
- }
-
- @Override
- public String toString(final String prefix) {
- final String result = keyword + ": " + text;
- if (null != prefix) {
- return prefix + result;
- }
- return result;
- }
- }
-
}
diff --git a/src/main/java/org/apache/commons/imaging/common/ImageBuilder.java b/src/main/java/org/apache/commons/imaging/common/ImageBuilder.java
index 73b969bb..f695c3ba 100644
--- a/src/main/java/org/apache/commons/imaging/common/ImageBuilder.java
+++ b/src/main/java/org/apache/commons/imaging/common/ImageBuilder.java
@@ -102,6 +102,41 @@ public class ImageBuilder {
this.isAlphaPremultiplied = isAlphaPremultiplied;
}
+ /**
+ * Performs a check on the specified sub-region to verify
+ * that it is within the constraints of the ImageBuilder bounds.
+ *
+ * @param x the X coordinate of the upper-left corner of the
+ * specified rectangular region
+ * @param y the Y coordinate of the upper-left corner of the
+ * specified rectangular region
+ * @param w the width of the specified rectangular region
+ * @param h the height of the specified rectangular region
+ * @throws RasterFormatException if width or height are equal or less than zero, or if the subimage is outside raster (on x or y axis)
+ */
+ private void checkBounds(final int x, final int y, final int w, final int h) {
+ if (w <= 0) {
+ throw new RasterFormatException("negative or zero subimage width");
+ }
+ if (h <= 0) {
+ throw new RasterFormatException("negative or zero subimage height");
+ }
+ if (x < 0 || x >= width) {
+ throw new RasterFormatException("subimage x is outside raster");
+ }
+ if (x + w > width) {
+ throw new RasterFormatException(
+ "subimage (x+width) is outside raster");
+ }
+ if (y < 0 || y >= height) {
+ throw new RasterFormatException("subimage y is outside raster");
+ }
+ if (y + h > height) {
+ throw new RasterFormatException(
+ "subimage (y+height) is outside raster");
+ }
+ }
+
/**
* @param width image width (must be greater than zero)
* @param height image height (must be greater than zero)
@@ -118,11 +153,11 @@ public class ImageBuilder {
}
/**
- * Get the width of the ImageBuilder pixel field
- * @return a positive integer
+ * Create a BufferedImage using the data stored in the ImageBuilder.
+ * @return a valid BufferedImage.
*/
- public int getWidth() {
- return width;
+ public BufferedImage getBufferedImage() {
+ return makeBufferedImage(data, width, height, hasAlpha);
}
/**
@@ -147,62 +182,41 @@ public class ImageBuilder {
}
/**
- * Set the RGB or ARGB value for the pixel at position (x,y)
- * within the image builder pixel field. For performance reasons,
- * no bounds checking is applied.
- * @param x the X coordinate of the pixel to be set
- * @param y the Y coordinate of the pixel to be set
- * @param argb the RGB or ARGB value to be stored.
- */
- public void setRGB(final int x, final int y, final int argb) {
- final int rowOffset = y * width;
- data[rowOffset + x] = argb;
- }
-
- /**
- * Create a BufferedImage using the data stored in the ImageBuilder.
- * @return a valid BufferedImage.
- */
- public BufferedImage getBufferedImage() {
- return makeBufferedImage(data, width, height, hasAlpha);
- }
-
- /**
- * Performs a check on the specified sub-region to verify
- * that it is within the constraints of the ImageBuilder bounds.
- *
+ * Gets a subimage from the ImageBuilder using the specified parameters.
+ * If the parameters specify a rectangular region that is not entirely
+ * contained within the bounds defined by the ImageBuilder, this method will
+ * throw a RasterFormatException. This runtime-exception behavior
+ * is consistent with the behavior of the getSubimage method
+ * provided by BufferedImage.
* @param x the X coordinate of the upper-left corner of the
- * specified rectangular region
+ * specified rectangular region
* @param y the Y coordinate of the upper-left corner of the
- * specified rectangular region
+ * specified rectangular region
* @param w the width of the specified rectangular region
* @param h the height of the specified rectangular region
- * @throws RasterFormatException if width or height are equal or less than zero, or if the subimage is outside raster (on x or y axis)
+ * @return a BufferedImage that constructed from the data within the
+ * specified rectangular region
+ * @throws RasterFormatException f the specified area is not contained
+ * within this ImageBuilder
*/
- private void checkBounds(final int x, final int y, final int w, final int h) {
- if (w <= 0) {
- throw new RasterFormatException("negative or zero subimage width");
- }
- if (h <= 0) {
- throw new RasterFormatException("negative or zero subimage height");
- }
- if (x < 0 || x >= width) {
- throw new RasterFormatException("subimage x is outside raster");
- }
- if (x + w > width) {
- throw new RasterFormatException(
- "subimage (x+width) is outside raster");
- }
- if (y < 0 || y >= height) {
- throw new RasterFormatException("subimage y is outside raster");
- }
- if (y + h > height) {
- throw new RasterFormatException(
- "subimage (y+height) is outside raster");
+ public BufferedImage getSubimage(final int x, final int y, final int w, final int h) {
+ checkBounds(x, y, w, h);
+
+ // Transcribe the data to an output image array
+ final int[] argb = new int[w * h];
+ int k = 0;
+ for (int iRow = 0; iRow < h; iRow++) {
+ final int dIndex = (iRow + y) * width + x;
+ System.arraycopy(this.data, dIndex, argb, k, w);
+ k += w;
+
}
+
+ return makeBufferedImage(argb, w, h, hasAlpha);
+
}
- /**
+ /**
* Gets a subset of the ImageBuilder content using the specified parameters
* to indicate an area of interest. If the parameters specify a rectangular
* region that is not entirely contained within the bounds defined
@@ -230,42 +244,15 @@ public class ImageBuilder {
return b;
}
-
- /**
- * Gets a subimage from the ImageBuilder using the specified parameters.
- * If the parameters specify a rectangular region that is not entirely
- * contained within the bounds defined by the ImageBuilder, this method will
- * throw a RasterFormatException. This runtime-exception behavior
- * is consistent with the behavior of the getSubimage method
- * provided by BufferedImage.
- * @param x the X coordinate of the upper-left corner of the
- * specified rectangular region
- * @param y the Y coordinate of the upper-left corner of the
- * specified rectangular region
- * @param w the width of the specified rectangular region
- * @param h the height of the specified rectangular region
- * @return a BufferedImage that constructed from the data within the
- * specified rectangular region
- * @throws RasterFormatException f the specified area is not contained
- * within this ImageBuilder
+ /**
+ * Get the width of the ImageBuilder pixel field
+ * @return a positive integer
*/
- public BufferedImage getSubimage(final int x, final int y, final int w, final int h) {
- checkBounds(x, y, w, h);
-
- // Transcribe the data to an output image array
- final int[] argb = new int[w * h];
- int k = 0;
- for (int iRow = 0; iRow < h; iRow++) {
- final int dIndex = (iRow + y) * width + x;
- System.arraycopy(this.data, dIndex, argb, k, w);
- k += w;
-
- }
-
- return makeBufferedImage(argb, w, h, hasAlpha);
-
+ public int getWidth() {
+ return width;
}
+
private BufferedImage makeBufferedImage(
final int[] argb, final int w, final int h, final boolean useAlpha) {
ColorModel colorModel;
@@ -300,4 +287,17 @@ public class ImageBuilder {
return new BufferedImage(colorModel, raster,
colorModel.isAlphaPremultiplied(), new Properties());
}
+
+ /**
+ * Set the RGB or ARGB value for the pixel at position (x,y)
+ * within the image builder pixel field. For performance reasons,
+ * no bounds checking is applied.
+ * @param x the X coordinate of the pixel to be set
+ * @param y the Y coordinate of the pixel to be set
+ * @param argb the RGB or ARGB value to be stored.
+ */
+ public void setRGB(final int x, final int y, final int argb) {
+ final int rowOffset = y * width;
+ data[rowOffset + x] = argb;
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/ImageMetadata.java b/src/main/java/org/apache/commons/imaging/common/ImageMetadata.java
index f0da963c..72414ff9 100644
--- a/src/main/java/org/apache/commons/imaging/common/ImageMetadata.java
+++ b/src/main/java/org/apache/commons/imaging/common/ImageMetadata.java
@@ -19,14 +19,14 @@ package org.apache.commons.imaging.common;
import java.util.List;
public interface ImageMetadata {
- String toString(String prefix);
-
- List<? extends ImageMetadataItem> getItems();
-
interface ImageMetadataItem {
- String toString(String prefix);
-
@Override
String toString();
+
+ String toString(String prefix);
}
+
+ List<? extends ImageMetadataItem> getItems();
+
+ String toString(String prefix);
}
diff --git a/src/main/java/org/apache/commons/imaging/common/PackBits.java b/src/main/java/org/apache/commons/imaging/common/PackBits.java
index 3869a48e..19efec6a 100644
--- a/src/main/java/org/apache/commons/imaging/common/PackBits.java
+++ b/src/main/java/org/apache/commons/imaging/common/PackBits.java
@@ -23,6 +23,54 @@ import org.apache.commons.imaging.ImageReadException;
public class PackBits {
+ public byte[] compress(final byte[] bytes) throws IOException {
+ // max length 1 extra byte for every 128
+ try (FastByteArrayOutputStream baos = new FastByteArrayOutputStream(bytes.length * 2)) {
+ int ptr = 0;
+ while (ptr < bytes.length) {
+ int dup = findNextDuplicate(bytes, ptr);
+
+ if (dup == ptr) {
+ // write run length
+ final int len = findRunLength(bytes, dup);
+ final int actualLen = Math.min(len, 128);
+ baos.write(-(actualLen - 1));
+ baos.write(bytes[ptr]);
+ ptr += actualLen;
+ } else {
+ // write literals
+ int len = dup - ptr;
+
+ if (dup > 0) {
+ final int runlen = findRunLength(bytes, dup);
+ if (runlen < 3) {
+ // may want to discard next run.
+ final int nextptr = ptr + len + runlen;
+ final int nextdup = findNextDuplicate(bytes, nextptr);
+ if (nextdup != nextptr) {
+ // discard 2-byte run
+ dup = nextdup;
+ len = dup - ptr;
+ }
+ }
+ }
+
+ if (dup < 0) {
+ len = bytes.length - ptr;
+ }
+ final int actualLen = Math.min(len, 128);
+
+ baos.write(actualLen - 1);
+ for (int i = 0; i < actualLen; i++) {
+ baos.write(bytes[ptr]);
+ ptr++;
+ }
+ }
+ }
+ return baos.toByteArray();
+ }
+ }
+
public byte[] decompress(final byte[] bytes, final int expected)
throws ImageReadException {
int total = 0;
@@ -103,52 +151,4 @@ public class PackBits {
return i - start;
}
-
- public byte[] compress(final byte[] bytes) throws IOException {
- // max length 1 extra byte for every 128
- try (FastByteArrayOutputStream baos = new FastByteArrayOutputStream(bytes.length * 2)) {
- int ptr = 0;
- while (ptr < bytes.length) {
- int dup = findNextDuplicate(bytes, ptr);
-
- if (dup == ptr) {
- // write run length
- final int len = findRunLength(bytes, dup);
- final int actualLen = Math.min(len, 128);
- baos.write(-(actualLen - 1));
- baos.write(bytes[ptr]);
- ptr += actualLen;
- } else {
- // write literals
- int len = dup - ptr;
-
- if (dup > 0) {
- final int runlen = findRunLength(bytes, dup);
- if (runlen < 3) {
- // may want to discard next run.
- final int nextptr = ptr + len + runlen;
- final int nextdup = findNextDuplicate(bytes, nextptr);
- if (nextdup != nextptr) {
- // discard 2-byte run
- dup = nextdup;
- len = dup - ptr;
- }
- }
- }
-
- if (dup < 0) {
- len = bytes.length - ptr;
- }
- final int actualLen = Math.min(len, 128);
-
- baos.write(actualLen - 1);
- for (int i = 0; i < actualLen; i++) {
- baos.write(bytes[ptr]);
- ptr++;
- }
- }
- }
- return baos.toByteArray();
- }
- }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/RationalNumber.java b/src/main/java/org/apache/commons/imaging/common/RationalNumber.java
index 0aa226f6..4e4eccf3 100644
--- a/src/main/java/org/apache/commons/imaging/common/RationalNumber.java
+++ b/src/main/java/org/apache/commons/imaging/common/RationalNumber.java
@@ -31,62 +31,29 @@ import java.text.NumberFormat;
*/
public class RationalNumber extends Number {
- private static final long serialVersionUID = -8412262656468158691L;
-
- // int-precision tolerance
- private static final double TOLERANCE = 1E-8;
+ private static final class Option {
+ public static Option factory(final RationalNumber rationalNumber, final double value) {
+ return new Option(rationalNumber, Math.abs(rationalNumber .doubleValue() - value));
+ }
+ public final RationalNumber rationalNumber;
- // The TIFF and EXIF specifications call for the use
- // of 32 bit unsigned integers. Since Java does not have an
- // unsigned type, this class widens the type to long in order
- // to avoid unintended negative numbers.
- public final long numerator;
- public final long divisor;
- public final boolean unsignedType;
+ public final double error;
- /**
- * Constructs an instance based on signed integers
- * @param numerator a 32-bit signed integer
- * @param divisor a non-zero 32-bit signed integer
- */
- public RationalNumber(final int numerator, final int divisor) {
- this.numerator = numerator;
- this.divisor = divisor;
- this.unsignedType = false;
- }
+ private Option(final RationalNumber rationalNumber, final double error) {
+ this.rationalNumber = rationalNumber;
+ this.error = error;
+ }
- /**
- * Constructs an instance supports either signed or unsigned integers.
- * @param numerator a numerator in the indicated form (signed or unsigned)
- * @param divisor a non-zero divisor in the indicated form (signed or unsigned)
- * @param unsignedType indicates whether the input values are to be treated
- * as unsigned.
- */
- public RationalNumber(final int numerator, final int divisor, final boolean unsignedType) {
- this.unsignedType = unsignedType;
- if (unsignedType) {
- this.numerator = numerator & 0xffffffffL;
- this.divisor = divisor & 0xffffffffL;
- } else {
- this.numerator = numerator;
- this.divisor = divisor;
+ @Override
+ public String toString() {
+ return rationalNumber.toString();
}
}
- /**
- * A private constructor for methods such as negate() that create instances
- * of this class using the content of the current instance.
- * @param numerator a valid numerator
- * @param divisor a valid denominator
- * @param unsignedType indicates how numerator and divisor values
- * are to be interpreted.
- */
- private RationalNumber(final long numerator, final long divisor, final boolean unsignedType){
- this.numerator = numerator;
- this.divisor = divisor;
- this.unsignedType = unsignedType;
- }
+ private static final long serialVersionUID = -8412262656468158691L;
+ // int-precision tolerance
+ private static final double TOLERANCE = 1E-8;
static RationalNumber factoryMethod(long n, long d) {
// safer than constructor - handles values outside min/max range.
// also does some simple finding of common denominators.
@@ -113,7 +80,6 @@ public class RationalNumber extends Number {
return new RationalNumber((int) n, (int) d);
}
-
/**
* Return the greatest common divisor
*/
@@ -124,113 +90,6 @@ public class RationalNumber extends Number {
return gcd(b, a % b);
}
- /**
- * Negates the value of the RationalNumber. If the numerator of this
- * instance has its high-order bit set, then its value is too large
- * to be treated as a Java 32-bit signed integer. In such a case, the
- * only way that a RationalNumber instance can be negated is to
- * divide both terms by a common divisor, if a non-zero common divisor exists.
- * However, if no such divisor exists, there is no numerically correct
- * way to perform the negation. When a negation cannot be performed correctly,
- * this method throws an unchecked exception.
- * @return a valid instance with a negated value.
- */
- public RationalNumber negate() {
- long n = numerator;
- long d = divisor;
- if (unsignedType) {
- // An instance of an unsigned type can be negated if and only if
- // its high-order bit (the sign bit) is clear. If the bit is set,
- // the value will be too large to convert to a signed type.
- // In such a case it is necessary to adjust the numerator and denominator
- // by their greatest common divisor (gcd), if one exists.
- // If no non-zero common divisor exists, an exception is thrown.
- if ((n >> 31) == 1) {
- // the unsigned value is so large that the high-order bit is set
- // it cannot be converted to a negative number. Check to see
- // whether there is an option to reduce its magnitude.
- final long g = gcd(numerator, divisor);
- if (g != 0) {
- n /= g;
- d /= g;
- }
- if ((n >> 31) == 1) {
- throw new NumberFormatException(
- "Unsigned numerator is too large to negate "
- + numerator);
- }
- }
- }
- return new RationalNumber(-n, d, false);
- }
-
- @Override
- public double doubleValue() {
- return (double) numerator / (double) divisor;
- }
-
- @Override
- public float floatValue() {
- // The computation uses double value in order to preserve
- // as much of the precision of the source numerator and denominator
- // as possible. Note that the expression
- // return (float)numerator/(float) denominator
- // could lose precision since a Java float only carries 24 bits
- // of precision while an integer carries 32.
- return (float) doubleValue();
- }
-
- @Override
- public int intValue() {
- return (int)(numerator / divisor);
- }
-
- @Override
- public long longValue() {
- return numerator / divisor;
- }
-
- @Override
- public String toString() {
- if (divisor == 0) {
- return "Invalid rational (" + numerator + "/" + divisor + ")";
- }
- final NumberFormat nf = NumberFormat.getInstance();
-
- if ((numerator % divisor) == 0) {
- return nf.format(numerator / divisor);
- }
- return numerator + "/" + divisor + " (" + nf.format((double) numerator / divisor) + ")";
- }
-
- public String toDisplayString() {
- if ((numerator % divisor) == 0) {
- return Long.toString(numerator / divisor);
- }
- final NumberFormat nf = NumberFormat.getInstance();
- nf.setMaximumFractionDigits(3);
- return nf.format((double) numerator / (double) divisor);
- }
-
- private static final class Option {
- public final RationalNumber rationalNumber;
- public final double error;
-
- private Option(final RationalNumber rationalNumber, final double error) {
- this.rationalNumber = rationalNumber;
- this.error = error;
- }
-
- public static Option factory(final RationalNumber rationalNumber, final double value) {
- return new Option(rationalNumber, Math.abs(rationalNumber .doubleValue() - value));
- }
-
- @Override
- public String toString() {
- return rationalNumber.toString();
- }
- }
-
/**
* Calculate rational number using successive approximations.
*
@@ -313,4 +172,145 @@ public class RationalNumber extends Number {
: bestOption.rationalNumber;
}
+ // The TIFF and EXIF specifications call for the use
+ // of 32 bit unsigned integers. Since Java does not have an
+ // unsigned type, this class widens the type to long in order
+ // to avoid unintended negative numbers.
+ public final long numerator;
+
+ public final long divisor;
+
+ public final boolean unsignedType;
+
+ /**
+ * Constructs an instance based on signed integers
+ * @param numerator a 32-bit signed integer
+ * @param divisor a non-zero 32-bit signed integer
+ */
+ public RationalNumber(final int numerator, final int divisor) {
+ this.numerator = numerator;
+ this.divisor = divisor;
+ this.unsignedType = false;
+ }
+
+ /**
+ * Constructs an instance supports either signed or unsigned integers.
+ * @param numerator a numerator in the indicated form (signed or unsigned)
+ * @param divisor a non-zero divisor in the indicated form (signed or unsigned)
+ * @param unsignedType indicates whether the input values are to be treated
+ * as unsigned.
+ */
+ public RationalNumber(final int numerator, final int divisor, final boolean unsignedType) {
+ this.unsignedType = unsignedType;
+ if (unsignedType) {
+ this.numerator = numerator & 0xffffffffL;
+ this.divisor = divisor & 0xffffffffL;
+ } else {
+ this.numerator = numerator;
+ this.divisor = divisor;
+ }
+ }
+
+ /**
+ * A private constructor for methods such as negate() that create instances
+ * of this class using the content of the current instance.
+ * @param numerator a valid numerator
+ * @param divisor a valid denominator
+ * @param unsignedType indicates how numerator and divisor values
+ * are to be interpreted.
+ */
+ private RationalNumber(final long numerator, final long divisor, final boolean unsignedType){
+ this.numerator = numerator;
+ this.divisor = divisor;
+ this.unsignedType = unsignedType;
+ }
+
+ @Override
+ public double doubleValue() {
+ return (double) numerator / (double) divisor;
+ }
+
+ @Override
+ public float floatValue() {
+ // The computation uses double value in order to preserve
+ // as much of the precision of the source numerator and denominator
+ // as possible. Note that the expression
+ // return (float)numerator/(float) denominator
+ // could lose precision since a Java float only carries 24 bits
+ // of precision while an integer carries 32.
+ return (float) doubleValue();
+ }
+
+ @Override
+ public int intValue() {
+ return (int)(numerator / divisor);
+ }
+
+ @Override
+ public long longValue() {
+ return numerator / divisor;
+ }
+
+ /**
+ * Negates the value of the RationalNumber. If the numerator of this
+ * instance has its high-order bit set, then its value is too large
+ * to be treated as a Java 32-bit signed integer. In such a case, the
+ * only way that a RationalNumber instance can be negated is to
+ * divide both terms by a common divisor, if a non-zero common divisor exists.
+ * However, if no such divisor exists, there is no numerically correct
+ * way to perform the negation. When a negation cannot be performed correctly,
+ * this method throws an unchecked exception.
+ * @return a valid instance with a negated value.
+ */
+ public RationalNumber negate() {
+ long n = numerator;
+ long d = divisor;
+ if (unsignedType) {
+ // An instance of an unsigned type can be negated if and only if
+ // its high-order bit (the sign bit) is clear. If the bit is set,
+ // the value will be too large to convert to a signed type.
+ // In such a case it is necessary to adjust the numerator and denominator
+ // by their greatest common divisor (gcd), if one exists.
+ // If no non-zero common divisor exists, an exception is thrown.
+ if ((n >> 31) == 1) {
+ // the unsigned value is so large that the high-order bit is set
+ // it cannot be converted to a negative number. Check to see
+ // whether there is an option to reduce its magnitude.
+ final long g = gcd(numerator, divisor);
+ if (g != 0) {
+ n /= g;
+ d /= g;
+ }
+ if ((n >> 31) == 1) {
+ throw new NumberFormatException(
+ "Unsigned numerator is too large to negate "
+ + numerator);
+ }
+ }
+ }
+ return new RationalNumber(-n, d, false);
+ }
+
+ public String toDisplayString() {
+ if ((numerator % divisor) == 0) {
+ return Long.toString(numerator / divisor);
+ }
+ final NumberFormat nf = NumberFormat.getInstance();
+ nf.setMaximumFractionDigits(3);
+ return nf.format((double) numerator / (double) divisor);
+ }
+
+ @Override
+ public String toString() {
+ if (divisor == 0) {
+ return "Invalid rational (" + numerator + "/" + divisor + ")";
+ }
+ final NumberFormat nf = NumberFormat.getInstance();
+
+ if ((numerator % divisor) == 0) {
+ return nf.format(numerator / divisor);
+ }
+ return numerator + "/" + divisor + " (" + nf.format((double) numerator / divisor) + ")";
+ }
+
}
diff --git a/src/main/java/org/apache/commons/imaging/common/ZlibDeflate.java b/src/main/java/org/apache/commons/imaging/common/ZlibDeflate.java
index cf676a83..4efddfd3 100644
--- a/src/main/java/org/apache/commons/imaging/common/ZlibDeflate.java
+++ b/src/main/java/org/apache/commons/imaging/common/ZlibDeflate.java
@@ -38,6 +38,25 @@ import org.apache.commons.imaging.ImageWriteException;
*/
public class ZlibDeflate {
+ /**
+ * Compress the byte[] using ZLIB deflate compression.
+ *
+ * @param bytes The bytes to compress
+ *
+ * @return The compressed bytes.
+ * @throws ImageWriteException if the bytes could not be compressed.
+ * @see DeflaterOutputStream
+ */
+ public static byte[] compress(final byte[] bytes) throws ImageWriteException {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream(bytes.length / 2);
+ try (DeflaterOutputStream compressOut = new DeflaterOutputStream(out)) {
+ compressOut.write(bytes);
+ } catch (final IOException e) {
+ throw new ImageWriteException("Unable to compress image", e);
+ }
+ return out.toByteArray();
+ }
+
/**
* Compress the byte[] using ZLIB deflate decompression.
*
@@ -60,23 +79,4 @@ public class ZlibDeflate {
}
}
- /**
- * Compress the byte[] using ZLIB deflate compression.
- *
- * @param bytes The bytes to compress
- *
- * @return The compressed bytes.
- * @throws ImageWriteException if the bytes could not be compressed.
- * @see DeflaterOutputStream
- */
- public static byte[] compress(final byte[] bytes) throws ImageWriteException {
- final ByteArrayOutputStream out = new ByteArrayOutputStream(bytes.length / 2);
- try (DeflaterOutputStream compressOut = new DeflaterOutputStream(out)) {
- compressOut.write(bytes);
- } catch (final IOException e) {
- throw new ImageWriteException("Unable to compress image", e);
- }
- return out.toByteArray();
- }
-
}
diff --git a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSource.java b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSource.java
index 8eb8b480..d25e5b28 100644
--- a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSource.java
+++ b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSource.java
@@ -28,6 +28,22 @@ public abstract class ByteSource {
this.fileName = fileName;
}
+ public abstract byte[] getAll() throws IOException;
+
+ public byte[] getBlock(final int start, final int length) throws IOException {
+ return getBlock(0xFFFFffffL & start, length);
+ }
+
+ public abstract byte[] getBlock(long start, int length) throws IOException;
+
+ public abstract String getDescription();
+
+ public final String getFileName() {
+ return fileName;
+ }
+
+ public abstract InputStream getInputStream() throws IOException;
+
public final InputStream getInputStream(final long start) throws IOException {
InputStream is = null;
boolean succeeded = false;
@@ -43,16 +59,6 @@ public abstract class ByteSource {
return is;
}
- public abstract InputStream getInputStream() throws IOException;
-
- public byte[] getBlock(final int start, final int length) throws IOException {
- return getBlock(0xFFFFffffL & start, length);
- }
-
- public abstract byte[] getBlock(long start, int length) throws IOException;
-
- public abstract byte[] getAll() throws IOException;
-
/**
* This operation can be VERY expensive; for inputstream byte sources, the
* entire stream must be drained to determine its length.
@@ -62,10 +68,4 @@ public abstract class ByteSource {
*/
public abstract long getLength() throws IOException;
- public abstract String getDescription();
-
- public final String getFileName() {
- return fileName;
- }
-
}
diff --git a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceArray.java b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceArray.java
index 621fdda2..ddbcbb13 100644
--- a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceArray.java
+++ b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceArray.java
@@ -24,18 +24,18 @@ import java.util.Arrays;
public class ByteSourceArray extends ByteSource {
private final byte[] bytes;
+ public ByteSourceArray(final byte[] bytes) {
+ this(null, bytes);
+ }
+
public ByteSourceArray(final String fileName, final byte[] bytes) {
super(fileName);
this.bytes = bytes;
}
- public ByteSourceArray(final byte[] bytes) {
- this(null, bytes);
- }
-
@Override
- public InputStream getInputStream() {
- return new ByteArrayInputStream(bytes);
+ public byte[] getAll() throws IOException {
+ return bytes;
}
@Override
@@ -53,18 +53,18 @@ public class ByteSourceArray extends ByteSource {
}
@Override
- public long getLength() {
- return bytes.length;
+ public String getDescription() {
+ return bytes.length + " byte array";
}
@Override
- public byte[] getAll() throws IOException {
- return bytes;
+ public InputStream getInputStream() {
+ return new ByteArrayInputStream(bytes);
}
@Override
- public String getDescription() {
- return bytes.length + " byte array";
+ public long getLength() {
+ return bytes.length;
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceFile.java b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceFile.java
index 30c745c1..e9b253d4 100644
--- a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceFile.java
+++ b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceFile.java
@@ -35,8 +35,17 @@ public class ByteSourceFile extends ByteSource {
}
@Override
- public InputStream getInputStream() throws IOException {
- return new BufferedInputStream(new FileInputStream(file));
+ public byte[] getAll() throws IOException {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ try (InputStream is = getInputStream()) {
+ final byte[] buffer = new byte[1024];
+ int read;
+ while ((read = is.read(buffer)) > 0) {
+ baos.write(buffer, 0, read);
+ }
+ return baos.toByteArray();
+ }
}
@Override
@@ -56,27 +65,18 @@ public class ByteSourceFile extends ByteSource {
}
@Override
- public long getLength() {
- return file.length();
+ public String getDescription() {
+ return "File: '" + file.getAbsolutePath() + "'";
}
@Override
- public byte[] getAll() throws IOException {
- final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- try (InputStream is = getInputStream()) {
- final byte[] buffer = new byte[1024];
- int read;
- while ((read = is.read(buffer)) > 0) {
- baos.write(buffer, 0, read);
- }
- return baos.toByteArray();
- }
+ public InputStream getInputStream() throws IOException {
+ return new BufferedInputStream(new FileInputStream(file));
}
@Override
- public String getDescription() {
- return "File: '" + file.getAbsolutePath() + "'";
+ public long getLength() {
+ return file.length();
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceInputStream.java b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceInputStream.java
index 3fa22038..d03f97ad 100644
--- a/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceInputStream.java
+++ b/src/main/java/org/apache/commons/imaging/common/bytesource/ByteSourceInputStream.java
@@ -26,18 +26,6 @@ import java.util.Objects;
import org.apache.commons.imaging.common.BinaryFunctions;
public class ByteSourceInputStream extends ByteSource {
- private static final int BLOCK_SIZE = 1024;
-
- private final InputStream is;
- private CacheBlock cacheHead;
- private byte[] readBuffer;
- private long streamLength = -1;
-
- public ByteSourceInputStream(final InputStream is, final String fileName) {
- super(fileName);
- this.is = new BufferedInputStream(is);
- }
-
private class CacheBlock {
public final byte[] bytes;
private CacheBlock next;
@@ -61,32 +49,6 @@ public class ByteSourceInputStream extends ByteSource {
}
- private CacheBlock readBlock() throws IOException {
- if (null == readBuffer) {
- readBuffer = new byte[BLOCK_SIZE];
- }
-
- final int read = is.read(readBuffer);
- if (read < 1) {
- return null;
- }
- if (read < BLOCK_SIZE) {
- // return a copy.
- return new CacheBlock(Arrays.copyOf(readBuffer, read));
- }
- // return current buffer.
- final byte[] result = readBuffer;
- readBuffer = null;
- return new CacheBlock(result);
- }
-
- private CacheBlock getFirstBlock() throws IOException {
- if (null == cacheHead) {
- cacheHead = readBlock();
- }
- return cacheHead;
- }
-
private class CacheReadingInputStream extends InputStream {
private CacheBlock block;
private boolean readFirst;
@@ -202,10 +164,29 @@ public class ByteSourceInputStream extends ByteSource {
}
}
+ private static final int BLOCK_SIZE = 1024;
+ private final InputStream is;
+ private CacheBlock cacheHead;
+
+ private byte[] readBuffer;
+
+ private long streamLength = -1;
+
+ public ByteSourceInputStream(final InputStream is, final String fileName) {
+ super(fileName);
+ this.is = new BufferedInputStream(is);
+ }
@Override
- public InputStream getInputStream() throws IOException {
- return new CacheReadingInputStream();
+ public byte[] getAll() throws IOException {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ CacheBlock block = getFirstBlock();
+ while (block != null) {
+ baos.write(block.bytes);
+ block = block.getNext();
+ }
+ return baos.toByteArray();
}
@Override
@@ -236,6 +217,23 @@ public class ByteSourceInputStream extends ByteSource {
}
}
+ @Override
+ public String getDescription() {
+ return "Inputstream: '" + getFileName() + "'";
+ }
+
+ private CacheBlock getFirstBlock() throws IOException {
+ if (null == cacheHead) {
+ cacheHead = readBlock();
+ }
+ return cacheHead;
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return new CacheReadingInputStream();
+ }
+
@Override
public long getLength() throws IOException {
if (streamLength >= 0) {
@@ -252,21 +250,23 @@ public class ByteSourceInputStream extends ByteSource {
return result;
}
- @Override
- public byte[] getAll() throws IOException {
- final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- CacheBlock block = getFirstBlock();
- while (block != null) {
- baos.write(block.bytes);
- block = block.getNext();
+ private CacheBlock readBlock() throws IOException {
+ if (null == readBuffer) {
+ readBuffer = new byte[BLOCK_SIZE];
}
- return baos.toByteArray();
- }
- @Override
- public String getDescription() {
- return "Inputstream: '" + getFileName() + "'";
+ final int read = is.read(readBuffer);
+ if (read < 1) {
+ return null;
+ }
+ if (read < BLOCK_SIZE) {
+ // return a copy.
+ return new CacheBlock(Arrays.copyOf(readBuffer, read));
+ }
+ // return current buffer.
+ final byte[] result = readBuffer;
+ readBuffer = null;
+ return new CacheBlock(result);
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/itu_t4/BitArrayOutputStream.java b/src/main/java/org/apache/commons/imaging/common/itu_t4/BitArrayOutputStream.java
index 6b513447..3eba5939 100644
--- a/src/main/java/org/apache/commons/imaging/common/itu_t4/BitArrayOutputStream.java
+++ b/src/main/java/org/apache/commons/imaging/common/itu_t4/BitArrayOutputStream.java
@@ -37,18 +37,6 @@ class BitArrayOutputStream extends OutputStream {
buffer = new byte[size];
}
- public int size() {
- return bytesWritten;
- }
-
- public byte[] toByteArray() {
- flush();
- if (bytesWritten == buffer.length) {
- return buffer;
- }
- return Arrays.copyOf(buffer, bytesWritten);
- }
-
@Override
public void close() {
flush();
@@ -63,6 +51,26 @@ class BitArrayOutputStream extends OutputStream {
}
}
+ public int getBitsAvailableInCurrentByte() {
+ int count = 0;
+ for (int mask = cacheMask; mask != 0; mask >>>= 1) {
+ ++count;
+ }
+ return count;
+ }
+
+ public int size() {
+ return bytesWritten;
+ }
+
+ public byte[] toByteArray() {
+ flush();
+ if (bytesWritten == buffer.length) {
+ return buffer;
+ }
+ return Arrays.copyOf(buffer, bytesWritten);
+ }
+
@Override
public void write(final int b) {
flush();
@@ -79,14 +87,6 @@ class BitArrayOutputStream extends OutputStream {
}
}
- public int getBitsAvailableInCurrentByte() {
- int count = 0;
- for (int mask = cacheMask; mask != 0; mask >>>= 1) {
- ++count;
- }
- return count;
- }
-
private void writeByte(final int b) {
if (bytesWritten >= buffer.length) {
final byte[] bigger = new byte[buffer.length * 2];
diff --git a/src/main/java/org/apache/commons/imaging/common/itu_t4/BitInputStreamFlexible.java b/src/main/java/org/apache/commons/imaging/common/itu_t4/BitInputStreamFlexible.java
index 6daf5ba6..452362d7 100644
--- a/src/main/java/org/apache/commons/imaging/common/itu_t4/BitInputStreamFlexible.java
+++ b/src/main/java/org/apache/commons/imaging/common/itu_t4/BitInputStreamFlexible.java
@@ -37,6 +37,14 @@ class BitInputStreamFlexible extends InputStream {
// super(is);
}
+ public void flushCache() {
+ cacheBitsRemaining = 0;
+ }
+
+ public long getBytesRead() {
+ return bytesRead;
+ }
+
@Override
public int read() throws IOException {
if (cacheBitsRemaining > 0) {
@@ -97,12 +105,4 @@ class BitInputStreamFlexible extends InputStream {
throw new IOException("BitInputStream: unknown error");
}
-
- public void flushCache() {
- cacheBitsRemaining = 0;
- }
-
- public long getBytesRead() {
- return bytesRead;
- }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/itu_t4/HuffmanTree.java b/src/main/java/org/apache/commons/imaging/common/itu_t4/HuffmanTree.java
index 061402ba..929ef1fe 100644
--- a/src/main/java/org/apache/commons/imaging/common/itu_t4/HuffmanTree.java
+++ b/src/main/java/org/apache/commons/imaging/common/itu_t4/HuffmanTree.java
@@ -24,42 +24,12 @@ import java.util.List;
* A Huffman tree implemented as 1 array for high locality of reference.
*/
class HuffmanTree<T> {
- private final List<Node<T>> nodes = new ArrayList<>();
-
private static final class Node<T> {
boolean empty = true;
T value;
}
- public final void insert(final String pattern, final T value) throws HuffmanTreeException {
- int position = 0;
- Node<T> node = growAndGetNode(position);
- if (node.value != null) {
- throw new HuffmanTreeException("Can't add child to a leaf");
- }
- for (int patternPosition = 0; patternPosition < pattern.length(); patternPosition++) {
- final char nextChar = pattern.charAt(patternPosition);
- if (nextChar == '0') {
- position = (position << 1) + 1;
- } else {
- position = (position + 1) << 1;
- }
- node = growAndGetNode(position);
- if (node.value != null) {
- throw new HuffmanTreeException("Can't add child to a leaf");
- }
- }
- node.value = value;
- }
-
- private Node<T> growAndGetNode(final int position) {
- while (position >= nodes.size()) {
- nodes.add(new Node<>());
- }
- final Node<T> node = nodes.get(position);
- node.empty = false;
- return node;
- }
+ private final List<Node<T>> nodes = new ArrayList<>();
public final T decode(final BitInputStreamFlexible bitStream) throws HuffmanTreeException {
int position = 0;
@@ -87,4 +57,34 @@ class HuffmanTree<T> {
}
return node.value;
}
+
+ private Node<T> growAndGetNode(final int position) {
+ while (position >= nodes.size()) {
+ nodes.add(new Node<>());
+ }
+ final Node<T> node = nodes.get(position);
+ node.empty = false;
+ return node;
+ }
+
+ public final void insert(final String pattern, final T value) throws HuffmanTreeException {
+ int position = 0;
+ Node<T> node = growAndGetNode(position);
+ if (node.value != null) {
+ throw new HuffmanTreeException("Can't add child to a leaf");
+ }
+ for (int patternPosition = 0; patternPosition < pattern.length(); patternPosition++) {
+ final char nextChar = pattern.charAt(patternPosition);
+ if (nextChar == '0') {
+ position = (position << 1) + 1;
+ } else {
+ position = (position + 1) << 1;
+ }
+ node = growAndGetNode(position);
+ if (node.value != null) {
+ throw new HuffmanTreeException("Can't add child to a leaf");
+ }
+ }
+ node.value = value;
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/itu_t4/T4AndT6Compression.java b/src/main/java/org/apache/commons/imaging/common/itu_t4/T4AndT6Compression.java
index d064df6d..34f23800 100644
--- a/src/main/java/org/apache/commons/imaging/common/itu_t4/T4AndT6Compression.java
+++ b/src/main/java/org/apache/commons/imaging/common/itu_t4/T4AndT6Compression.java
@@ -71,7 +71,11 @@ public final class T4AndT6Compression {
}
}
- private T4AndT6Compression() {
+ private static int changingElementAt(final int[] line, final int position) {
+ if (position < 0 || position >= line.length) {
+ return WHITE;
+ }
+ return line[position];
}
private static void compress1DLine(final BitInputStreamFlexible inputStream,
@@ -125,122 +129,6 @@ public final class T4AndT6Compression {
}
}
- /**
- * Decompresses the "Modified Huffman" encoding of section 10 in the TIFF6
- * specification. No EOLs, no RTC, rows are padded to end on a byte
- * boundary.
- *
- * @param compressed compressed byte data
- * @param width image width
- * @param height image height
- * @return the compressed data
- * @throws ImageReadException if it fails to read the compressed data
- */
- public static byte[] decompressModifiedHuffman(final byte[] compressed,
- final int width, final int height) throws ImageReadException {
- try (ByteArrayInputStream baos = new ByteArrayInputStream(compressed);
- BitInputStreamFlexible inputStream = new BitInputStreamFlexible(baos);
- BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
- for (int y = 0; y < height; y++) {
- int color = WHITE;
- int rowLength;
- for (rowLength = 0; rowLength < width;) {
- final int runLength = readTotalRunLength(inputStream, color);
- for (int i = 0; i < runLength; i++) {
- outputStream.writeBit(color);
- }
- color = 1 - color;
- rowLength += runLength;
- }
-
- if (rowLength == width) {
- inputStream.flushCache();
- outputStream.flush();
- } else if (rowLength > width) {
- throw new ImageReadException("Unrecoverable row length error in image row " + y);
- }
- }
- return outputStream.toByteArray();
- } catch (final IOException ioException) {
- throw new ImageReadException("Error reading image to decompress", ioException);
- }
- }
-
- public static byte[] compressT4_1D(final byte[] uncompressed, final int width,
- final int height, final boolean hasFill) throws ImageWriteException {
- final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(uncompressed));
- try (BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
- if (hasFill) {
- T4_T6_Tables.EOL16.writeBits(outputStream);
- } else {
- T4_T6_Tables.EOL.writeBits(outputStream);
- }
-
- for (int y = 0; y < height; y++) {
- compress1DLine(inputStream, outputStream, null, width);
- if (hasFill) {
- int bitsAvailable = outputStream.getBitsAvailableInCurrentByte();
- if (bitsAvailable < 4) {
- outputStream.flush();
- bitsAvailable = 8;
- }
- for (; bitsAvailable > 4; bitsAvailable--) {
- outputStream.writeBit(0);
- }
- }
- T4_T6_Tables.EOL.writeBits(outputStream);
- inputStream.flushCache();
- }
-
- return outputStream.toByteArray();
- }
- }
-
- /**
- * Decompresses T.4 1D encoded data. EOL at the beginning and after each
- * row, can be preceded by fill bits to fit on a byte boundary, no RTC.
- *
- * @param compressed compressed byte data
- * @param width image width
- * @param height image height
- * @param hasFill used to check the end of line
- * @return the decompressed data
- * @throws ImageReadException if it fails to read the compressed data
- */
- public static byte[] decompressT4_1D(final byte[] compressed, final int width,
- final int height, final boolean hasFill) throws ImageReadException {
- final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed));
- try (BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
- for (int y = 0; y < height; y++) {
- int rowLength;
- try {
- final T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream);
- if (!isEOL(entry, hasFill)) {
- throw new ImageReadException("Expected EOL not found");
- }
- int color = WHITE;
- for (rowLength = 0; rowLength < width;) {
- final int runLength = readTotalRunLength(inputStream, color);
- for (int i = 0; i < runLength; i++) {
- outputStream.writeBit(color);
- }
- color = 1 - color;
- rowLength += runLength;
- }
- } catch (final HuffmanTreeException huffmanException) {
- throw new ImageReadException("Decompression error", huffmanException);
- }
-
- if (rowLength == width) {
- outputStream.flush();
- } else if (rowLength > width) {
- throw new ImageReadException("Unrecoverable row length error in image row " + y);
- }
- }
- return outputStream.toByteArray();
- }
- }
-
private static int compressT(final int a0, final int a1, final int b1, final BitArrayOutputStream outputStream,final int codingA0Color, final int[] codingLine ){
final int a1b1 = a1 - b1;
if (-3 <= a1b1 && a1b1 <= 3) {
@@ -280,6 +168,37 @@ public final class T4AndT6Compression {
writeRunLength(outputStream, a1a2, 1 - codingA0Color);
return a2;
}
+
+ public static byte[] compressT4_1D(final byte[] uncompressed, final int width,
+ final int height, final boolean hasFill) throws ImageWriteException {
+ final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(uncompressed));
+ try (BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
+ if (hasFill) {
+ T4_T6_Tables.EOL16.writeBits(outputStream);
+ } else {
+ T4_T6_Tables.EOL.writeBits(outputStream);
+ }
+
+ for (int y = 0; y < height; y++) {
+ compress1DLine(inputStream, outputStream, null, width);
+ if (hasFill) {
+ int bitsAvailable = outputStream.getBitsAvailableInCurrentByte();
+ if (bitsAvailable < 4) {
+ outputStream.flush();
+ bitsAvailable = 8;
+ }
+ for (; bitsAvailable > 4; bitsAvailable--) {
+ outputStream.writeBit(0);
+ }
+ }
+ T4_T6_Tables.EOL.writeBits(outputStream);
+ inputStream.flushCache();
+ }
+
+ return outputStream.toByteArray();
+ }
+ }
+
public static byte[] compressT4_2D(final byte[] uncompressed, final int width,
final int height, final boolean hasFill, final int parameterK)
throws ImageWriteException {
@@ -359,6 +278,145 @@ public final class T4AndT6Compression {
return outputStream.toByteArray();
}
+ public static byte[] compressT6(final byte[] uncompressed, final int width, final int height)
+ throws ImageWriteException {
+ try (ByteArrayInputStream bais = new ByteArrayInputStream(uncompressed);
+ BitInputStreamFlexible inputStream = new BitInputStreamFlexible(bais)) {
+ final BitArrayOutputStream outputStream = new BitArrayOutputStream();
+ int[] referenceLine = new int[width];
+ int[] codingLine = new int[width];
+ for (int y = 0; y < height; y++) {
+ for (int i = 0; i < width; i++) {
+ try {
+ codingLine[i] = inputStream.readBits(1);
+ } catch (final IOException ioException) {
+ throw new ImageWriteException("Error reading image to compress", ioException);
+ }
+ }
+ int codingA0Color = WHITE;
+ int referenceA0Color = WHITE;
+ int a1 = nextChangingElement(codingLine, codingA0Color, 0);
+ int b1 = nextChangingElement(referenceLine, referenceA0Color, 0);
+ int b2 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1);
+ for (int a0 = 0; a0 < width;) {
+ if (b2 < a1) {
+ T4_T6_Tables.P.writeBits(outputStream);
+ a0 = b2;
+ } else {
+ a0 = compressT(a0, a1, b1, outputStream, codingA0Color, codingLine);
+ if (a0 == a1) {
+ codingA0Color = 1 - codingA0Color;
+ }
+ }
+ referenceA0Color = changingElementAt(referenceLine, a0);
+ a1 = nextChangingElement(codingLine, codingA0Color, a0 + 1);
+ if (codingA0Color == referenceA0Color) {
+ b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1);
+ } else {
+ b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1);
+ b1 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1);
+ }
+ b2 = nextChangingElement(referenceLine, 1 - codingA0Color, b1 + 1);
+ }
+ final int[] swap = referenceLine;
+ referenceLine = codingLine;
+ codingLine = swap;
+ inputStream.flushCache();
+ }
+ // EOFB
+ T4_T6_Tables.EOL.writeBits(outputStream);
+ T4_T6_Tables.EOL.writeBits(outputStream);
+ return outputStream.toByteArray();
+ } catch (final IOException ioException) {
+ throw new ImageWriteException("I/O error", ioException);
+ }
+ }
+ /**
+ * Decompresses the "Modified Huffman" encoding of section 10 in the TIFF6
+ * specification. No EOLs, no RTC, rows are padded to end on a byte
+ * boundary.
+ *
+ * @param compressed compressed byte data
+ * @param width image width
+ * @param height image height
+ * @return the compressed data
+ * @throws ImageReadException if it fails to read the compressed data
+ */
+ public static byte[] decompressModifiedHuffman(final byte[] compressed,
+ final int width, final int height) throws ImageReadException {
+ try (ByteArrayInputStream baos = new ByteArrayInputStream(compressed);
+ BitInputStreamFlexible inputStream = new BitInputStreamFlexible(baos);
+ BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
+ for (int y = 0; y < height; y++) {
+ int color = WHITE;
+ int rowLength;
+ for (rowLength = 0; rowLength < width;) {
+ final int runLength = readTotalRunLength(inputStream, color);
+ for (int i = 0; i < runLength; i++) {
+ outputStream.writeBit(color);
+ }
+ color = 1 - color;
+ rowLength += runLength;
+ }
+
+ if (rowLength == width) {
+ inputStream.flushCache();
+ outputStream.flush();
+ } else if (rowLength > width) {
+ throw new ImageReadException("Unrecoverable row length error in image row " + y);
+ }
+ }
+ return outputStream.toByteArray();
+ } catch (final IOException ioException) {
+ throw new ImageReadException("Error reading image to decompress", ioException);
+ }
+ }
+
+ /**
+ * Decompresses T.4 1D encoded data. EOL at the beginning and after each
+ * row, can be preceded by fill bits to fit on a byte boundary, no RTC.
+ *
+ * @param compressed compressed byte data
+ * @param width image width
+ * @param height image height
+ * @param hasFill used to check the end of line
+ * @return the decompressed data
+ * @throws ImageReadException if it fails to read the compressed data
+ */
+ public static byte[] decompressT4_1D(final byte[] compressed, final int width,
+ final int height, final boolean hasFill) throws ImageReadException {
+ final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed));
+ try (BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
+ for (int y = 0; y < height; y++) {
+ int rowLength;
+ try {
+ final T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream);
+ if (!isEOL(entry, hasFill)) {
+ throw new ImageReadException("Expected EOL not found");
+ }
+ int color = WHITE;
+ for (rowLength = 0; rowLength < width;) {
+ final int runLength = readTotalRunLength(inputStream, color);
+ for (int i = 0; i < runLength; i++) {
+ outputStream.writeBit(color);
+ }
+ color = 1 - color;
+ rowLength += runLength;
+ }
+ } catch (final HuffmanTreeException huffmanException) {
+ throw new ImageReadException("Decompression error", huffmanException);
+ }
+
+ if (rowLength == width) {
+ outputStream.flush();
+ } else if (rowLength > width) {
+ throw new ImageReadException("Unrecoverable row length error in image row " + y);
+ }
+ }
+ return outputStream.toByteArray();
+ }
+ }
+
/**
* Decompressed T.4 2D encoded data. EOL at the beginning and after each
* row, can be preceded by fill bits to fit on a byte boundary, and is
@@ -468,60 +526,6 @@ public final class T4AndT6Compression {
}
}
- public static byte[] compressT6(final byte[] uncompressed, final int width, final int height)
- throws ImageWriteException {
- try (ByteArrayInputStream bais = new ByteArrayInputStream(uncompressed);
- BitInputStreamFlexible inputStream = new BitInputStreamFlexible(bais)) {
- final BitArrayOutputStream outputStream = new BitArrayOutputStream();
- int[] referenceLine = new int[width];
- int[] codingLine = new int[width];
- for (int y = 0; y < height; y++) {
- for (int i = 0; i < width; i++) {
- try {
- codingLine[i] = inputStream.readBits(1);
- } catch (final IOException ioException) {
- throw new ImageWriteException("Error reading image to compress", ioException);
- }
- }
- int codingA0Color = WHITE;
- int referenceA0Color = WHITE;
- int a1 = nextChangingElement(codingLine, codingA0Color, 0);
- int b1 = nextChangingElement(referenceLine, referenceA0Color, 0);
- int b2 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1);
- for (int a0 = 0; a0 < width;) {
- if (b2 < a1) {
- T4_T6_Tables.P.writeBits(outputStream);
- a0 = b2;
- } else {
- a0 = compressT(a0, a1, b1, outputStream, codingA0Color, codingLine);
- if (a0 == a1) {
- codingA0Color = 1 - codingA0Color;
- }
- }
- referenceA0Color = changingElementAt(referenceLine, a0);
- a1 = nextChangingElement(codingLine, codingA0Color, a0 + 1);
- if (codingA0Color == referenceA0Color) {
- b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1);
- } else {
- b1 = nextChangingElement(referenceLine, referenceA0Color, a0 + 1);
- b1 = nextChangingElement(referenceLine, 1 - referenceA0Color, b1 + 1);
- }
- b2 = nextChangingElement(referenceLine, 1 - codingA0Color, b1 + 1);
- }
- final int[] swap = referenceLine;
- referenceLine = codingLine;
- codingLine = swap;
- inputStream.flushCache();
- }
- // EOFB
- T4_T6_Tables.EOL.writeBits(outputStream);
- T4_T6_Tables.EOL.writeBits(outputStream);
- return outputStream.toByteArray();
- } catch (final IOException ioException) {
- throw new ImageWriteException("I/O error", ioException);
- }
- }
-
/**
* Decompress T.6 encoded data. No EOLs, except for 2 consecutive ones at
* the end (the EOFB, end of fax block). No RTC. No fill bits anywhere. All
@@ -608,6 +612,14 @@ public final class T4AndT6Compression {
return outputStream.toByteArray();
}
+ private static void fillRange(final BitArrayOutputStream outputStream,
+ final int[] referenceRow, final int a0, final int end, final int color) {
+ for (int i = a0; i < end; i++) {
+ referenceRow[i] = color;
+ outputStream.writeBit(color);
+ }
+ }
+
private static boolean isEOL(final T4_T6_Tables.Entry entry, final boolean hasFill) {
if (entry == T4_T6_Tables.EOL) {
return true;
@@ -623,32 +635,6 @@ public final class T4AndT6Compression {
return false;
}
- private static void writeRunLength(final BitArrayOutputStream bitStream,
- int runLength, final int color) {
- final T4_T6_Tables.Entry[] makeUpCodes;
- final T4_T6_Tables.Entry[] terminatingCodes;
- if (color == WHITE) {
- makeUpCodes = T4_T6_Tables.WHITE_MAKE_UP_CODES;
- terminatingCodes = T4_T6_Tables.WHITE_TERMINATING_CODES;
- } else {
- makeUpCodes = T4_T6_Tables.BLACK_MAKE_UP_CODES;
- terminatingCodes = T4_T6_Tables.BLACK_TERMINATING_CODES;
- }
- while (runLength >= 1792) {
- final T4_T6_Tables.Entry entry = lowerBound(
- T4_T6_Tables.ADDITIONAL_MAKE_UP_CODES, runLength);
- entry.writeBits(bitStream);
- runLength -= entry.value;
- }
- while (runLength >= 64) {
- final T4_T6_Tables.Entry entry = lowerBound(makeUpCodes, runLength);
- entry.writeBits(bitStream);
- runLength -= entry.value;
- }
- final T4_T6_Tables.Entry terminatingEntry = terminatingCodes[runLength];
- terminatingEntry.writeBits(bitStream);
- }
-
private static T4_T6_Tables.Entry lowerBound(final T4_T6_Tables.Entry[] entries, final int value) {
int first = 0;
int last = entries.length - 1;
@@ -668,6 +654,16 @@ public final class T4AndT6Compression {
return entries[first];
}
+ private static int nextChangingElement(final int[] line, final int currentColour, final int start) {
+ int position;
+ for (position = start; position < line.length
+ && line[position] == currentColour; position++) {
+ // noop
+ }
+
+ return Math.min(position, line.length);
+ }
+
private static int readTotalRunLength(final BitInputStreamFlexible bitStream,
final int color) throws ImageReadException {
try {
@@ -687,28 +683,32 @@ public final class T4AndT6Compression {
}
}
- private static int changingElementAt(final int[] line, final int position) {
- if (position < 0 || position >= line.length) {
- return WHITE;
+ private static void writeRunLength(final BitArrayOutputStream bitStream,
+ int runLength, final int color) {
+ final T4_T6_Tables.Entry[] makeUpCodes;
+ final T4_T6_Tables.Entry[] terminatingCodes;
+ if (color == WHITE) {
+ makeUpCodes = T4_T6_Tables.WHITE_MAKE_UP_CODES;
+ terminatingCodes = T4_T6_Tables.WHITE_TERMINATING_CODES;
+ } else {
+ makeUpCodes = T4_T6_Tables.BLACK_MAKE_UP_CODES;
+ terminatingCodes = T4_T6_Tables.BLACK_TERMINATING_CODES;
}
- return line[position];
- }
-
- private static int nextChangingElement(final int[] line, final int currentColour, final int start) {
- int position;
- for (position = start; position < line.length
- && line[position] == currentColour; position++) {
- // noop
+ while (runLength >= 1792) {
+ final T4_T6_Tables.Entry entry = lowerBound(
+ T4_T6_Tables.ADDITIONAL_MAKE_UP_CODES, runLength);
+ entry.writeBits(bitStream);
+ runLength -= entry.value;
}
-
- return Math.min(position, line.length);
+ while (runLength >= 64) {
+ final T4_T6_Tables.Entry entry = lowerBound(makeUpCodes, runLength);
+ entry.writeBits(bitStream);
+ runLength -= entry.value;
+ }
+ final T4_T6_Tables.Entry terminatingEntry = terminatingCodes[runLength];
+ terminatingEntry.writeBits(bitStream);
}
- private static void fillRange(final BitArrayOutputStream outputStream,
- final int[] referenceRow, final int a0, final int end, final int color) {
- for (int i = a0; i < end; i++) {
- referenceRow[i] = color;
- outputStream.writeBit(color);
- }
+ private T4AndT6Compression() {
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/itu_t4/T4_T6_Tables.java b/src/main/java/org/apache/commons/imaging/common/itu_t4/T4_T6_Tables.java
index f18ad630..3036eaad 100644
--- a/src/main/java/org/apache/commons/imaging/common/itu_t4/T4_T6_Tables.java
+++ b/src/main/java/org/apache/commons/imaging/common/itu_t4/T4_T6_Tables.java
@@ -17,6 +17,26 @@
package org.apache.commons.imaging.common.itu_t4;
class T4_T6_Tables {
+ public static class Entry {
+ final String bitString;
+ final Integer value;
+
+ Entry(final String bitString, final int value) {
+ this.bitString = bitString;
+ this.value = value;
+ }
+
+ public void writeBits(final BitArrayOutputStream outputStream) {
+ for (int i = 0; i < bitString.length(); i++) {
+ if (bitString.charAt(i) == '0') {
+ outputStream.writeBit(0);
+ } else {
+ outputStream.writeBit(1);
+ }
+ }
+ }
+ }
+
public static final Entry[] WHITE_TERMINATING_CODES = {
new Entry("00110101", 0),
new Entry("000111", 1),
@@ -221,7 +241,6 @@ class T4_T6_Tables {
new Entry("000000011101", 2432),
new Entry("000000011110", 2496),
new Entry("000000011111", 2560), };
-
public static final Entry EOL = new Entry("000000000001", 0);
public static final Entry EOL13 = new Entry("0000000000001", 0);
public static final Entry EOL14 = new Entry("00000000000001", 0);
@@ -238,25 +257,6 @@ class T4_T6_Tables {
public static final Entry VR3 = new Entry("0000011", 0);
public static final Entry VL1 = new Entry("010", 0);
public static final Entry VL2 = new Entry("000010", 0);
- public static final Entry VL3 = new Entry("0000010", 0);
-
- public static class Entry {
- final String bitString;
- final Integer value;
- Entry(final String bitString, final int value) {
- this.bitString = bitString;
- this.value = value;
- }
-
- public void writeBits(final BitArrayOutputStream outputStream) {
- for (int i = 0; i < bitString.length(); i++) {
- if (bitString.charAt(i) == '0') {
- outputStream.writeBit(0);
- } else {
- outputStream.writeBit(1);
- }
- }
- }
- }
+ public static final Entry VL3 = new Entry("0000010", 0);
}
diff --git a/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitInputStream.java b/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitInputStream.java
index 721934af..443b0fc6 100644
--- a/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitInputStream.java
+++ b/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitInputStream.java
@@ -33,15 +33,20 @@ public class MyBitInputStream extends InputStream {
this.is = is;
}
+ public void flushCache() {
+ bitsInCache = 0;
+ bitCache = 0;
+ }
+
+ public long getBytesRead() {
+ return bytesRead;
+ }
+
@Override
public int read() throws IOException {
return readBits(8);
}
- public void setTiffLZWMode() {
- tiffLZWMode = true;
- }
-
public int readBits(final int sampleBits) throws IOException {
while (bitsInCache < sampleBits) {
final int next = is.read();
@@ -85,13 +90,8 @@ public class MyBitInputStream extends InputStream {
return result;
}
- public void flushCache() {
- bitsInCache = 0;
- bitCache = 0;
- }
-
- public long getBytesRead() {
- return bytesRead;
+ public void setTiffLZWMode() {
+ tiffLZWMode = true;
}
}
diff --git a/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitOutputStream.java b/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitOutputStream.java
index 02e3e57c..4316c6e4 100644
--- a/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitOutputStream.java
+++ b/src/main/java/org/apache/commons/imaging/common/mylzw/MyBitOutputStream.java
@@ -32,6 +32,34 @@ public class MyBitOutputStream extends OutputStream {
this.os = os;
}
+ private void actualWrite(final int value) throws IOException {
+ os.write(value);
+ bytesWritten++;
+ }
+
+ public void flushCache() throws IOException {
+ if (bitsInCache > 0) {
+ final int bitMask = (1 << bitsInCache) - 1;
+ int b = bitMask & bitCache;
+
+ if (byteOrder == ByteOrder.BIG_ENDIAN) {
+ // MSB, so write from left
+ b <<= 8 - bitsInCache; // left align fragment.
+ os.write(b);
+ } else {
+ // LSB, so write from right
+ os.write(b);
+ }
+ }
+
+ bitsInCache = 0;
+ bitCache = 0;
+ }
+
+ public int getBytesWritten() {
+ return bytesWritten + ((bitsInCache > 0) ? 1 : 0);
+ }
+
@Override
public void write(final int value) throws IOException {
writeBits(value, 8);
@@ -73,32 +101,4 @@ public class MyBitOutputStream extends OutputStream {
}
- private void actualWrite(final int value) throws IOException {
- os.write(value);
- bytesWritten++;
- }
-
- public void flushCache() throws IOException {
- if (bitsInCache > 0) {
- final int bitMask = (1 << bitsInCache) - 1;
- int b = bitMask & bitCache;
-
- if (byteOrder == ByteOrder.BIG_ENDIAN) {
- // MSB, so write from left
- b <<= 8 - bitsInCache; // left align fragment.
- os.write(b);
- } else {
- // LSB, so write from right
- os.write(b);
- }
- }
-
- bitsInCache = 0;
- bitCache = 0;
- }
-
- public int getBytesWritten() {
- return bytesWritten + ((bitsInCache > 0) ? 1 : 0);
- }
-
}
diff --git a/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwCompressor.java b/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwCompressor.java
index a46e1e31..c0edebfa 100644
--- a/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwCompressor.java
+++ b/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwCompressor.java
@@ -23,70 +23,6 @@ import java.util.HashMap;
import java.util.Map;
public class MyLzwCompressor {
- private int codeSize;
- private final int initialCodeSize;
- private int codes = -1;
-
- private final ByteOrder byteOrder;
- private final boolean earlyLimit;
- private final int clearCode;
- private final int eoiCode;
- private final Listener listener;
- private final Map<ByteArray, Integer> map = new HashMap<>();
-
- public MyLzwCompressor(final int initialCodeSize, final ByteOrder byteOrder,
- final boolean earlyLimit) {
- this(initialCodeSize, byteOrder, earlyLimit, null);
- }
-
- public MyLzwCompressor(final int initialCodeSize, final ByteOrder byteOrder,
- final boolean earlyLimit, final Listener listener) {
- this.listener = listener;
- this.byteOrder = byteOrder;
- this.earlyLimit = earlyLimit;
-
- this.initialCodeSize = initialCodeSize;
-
- clearCode = 1 << initialCodeSize;
- eoiCode = clearCode + 1;
-
- if (null != listener) {
- listener.init(clearCode, eoiCode);
- }
-
- initializeStringTable();
- }
-
- private void initializeStringTable() {
- codeSize = initialCodeSize;
-
- final int initialEntriesCount = (1 << codeSize) + 2;
-
- map.clear();
- for (codes = 0; codes < initialEntriesCount; codes++) {
- if ((codes != clearCode) && (codes != eoiCode)) {
- final ByteArray key = arrayToKey((byte) codes);
-
- map.put(key, codes);
- }
- }
- }
-
- private void clearTable() {
- initializeStringTable();
- incrementCodeSize();
- }
-
- private void incrementCodeSize() {
- if (codeSize != 12) {
- codeSize++;
- }
- }
-
- private ByteArray arrayToKey(final byte b) {
- return arrayToKey(new byte[] { b, }, 0, 1);
- }
-
private static final class ByteArray {
private final byte[] bytes;
private final int start;
@@ -108,11 +44,6 @@ public class MyLzwCompressor {
hash = tempHash;
}
- @Override
- public int hashCode() {
- return hash;
- }
-
@Override
public boolean equals(final Object o) {
if (o instanceof ByteArray) {
@@ -134,53 +65,55 @@ public class MyLzwCompressor {
}
return false;
}
- }
- private ByteArray arrayToKey(final byte[] bytes, final int start, final int length) {
- return new ByteArray(bytes, start, length);
- }
-
- private void writeDataCode(final MyBitOutputStream bos, final int code)
- throws IOException {
- if (null != listener) {
- listener.dataCode(code);
+ @Override
+ public int hashCode() {
+ return hash;
}
- writeCode(bos, code);
}
+ public interface Listener {
+ void clearCode(int code);
- private void writeClearCode(final MyBitOutputStream bos) throws IOException {
- if (null != listener) {
- listener.dataCode(clearCode);
- }
- writeCode(bos, clearCode);
- }
+ void dataCode(int code);
- private void writeEoiCode(final MyBitOutputStream bos) throws IOException {
- if (null != listener) {
- listener.eoiCode(eoiCode);
- }
- writeCode(bos, eoiCode);
- }
+ void eoiCode(int code);
- private void writeCode(final MyBitOutputStream bos, final int code)
- throws IOException {
- bos.writeBits(code, codeSize);
+ void init(int clearCode, int eoiCode);
}
+ private int codeSize;
- private boolean isInTable(final byte[] bytes, final int start, final int length) {
- final ByteArray key = arrayToKey(bytes, start, length);
+ private final int initialCodeSize;
+ private int codes = -1;
+ private final ByteOrder byteOrder;
+ private final boolean earlyLimit;
+ private final int clearCode;
+ private final int eoiCode;
- return map.containsKey(key);
+ private final Listener listener;
+
+ private final Map<ByteArray, Integer> map = new HashMap<>();
+
+ public MyLzwCompressor(final int initialCodeSize, final ByteOrder byteOrder,
+ final boolean earlyLimit) {
+ this(initialCodeSize, byteOrder, earlyLimit, null);
}
- private int codeFromString(final byte[] bytes, final int start, final int length)
- throws IOException {
- final ByteArray key = arrayToKey(bytes, start, length);
- final Integer code = map.get(key);
- if (code == null) {
- throw new IOException("CodeFromString");
+ public MyLzwCompressor(final int initialCodeSize, final ByteOrder byteOrder,
+ final boolean earlyLimit, final Listener listener) {
+ this.listener = listener;
+ this.byteOrder = byteOrder;
+ this.earlyLimit = earlyLimit;
+
+ this.initialCodeSize = initialCodeSize;
+
+ clearCode = 1 << initialCodeSize;
+ eoiCode = clearCode + 1;
+
+ if (null != listener) {
+ listener.init(clearCode, eoiCode);
}
- return code;
+
+ initializeStringTable();
}
private boolean addTableEntry(final MyBitOutputStream bos, final byte[] bytes,
@@ -216,14 +149,27 @@ public class MyLzwCompressor {
return cleared;
}
- public interface Listener {
- void dataCode(int code);
+ private ByteArray arrayToKey(final byte b) {
+ return arrayToKey(new byte[] { b, }, 0, 1);
+ }
- void eoiCode(int code);
+ private ByteArray arrayToKey(final byte[] bytes, final int start, final int length) {
+ return new ByteArray(bytes, start, length);
+ }
- void clearCode(int code);
+ private void clearTable() {
+ initializeStringTable();
+ incrementCodeSize();
+ }
- void init(int clearCode, int eoiCode);
+ private int codeFromString(final byte[] bytes, final int start, final int length)
+ throws IOException {
+ final ByteArray key = arrayToKey(bytes, start, length);
+ final Integer code = map.get(key);
+ if (code == null) {
+ throw new IOException("CodeFromString");
+ }
+ return code;
}
public byte[] compress(final byte[] bytes) throws IOException {
@@ -259,4 +205,58 @@ public class MyLzwCompressor {
return baos.toByteArray();
}
+
+ private void incrementCodeSize() {
+ if (codeSize != 12) {
+ codeSize++;
+ }
+ }
+
+ private void initializeStringTable() {
+ codeSize = initialCodeSize;
+
+ final int initialEntriesCount = (1 << codeSize) + 2;
+
+ map.clear();
+ for (codes = 0; codes < initialEntriesCount; codes++) {
+ if ((codes != clearCode) && (codes != eoiCode)) {
+ final ByteArray key = arrayToKey((byte) codes);
+
+ map.put(key, codes);
+ }
+ }
+ }
+
+ private boolean isInTable(final byte[] bytes, final int start, final int length) {
+ final ByteArray key = arrayToKey(bytes, start, length);
+
+ return map.containsKey(key);
+ }
+
+ private void writeClearCode(final MyBitOutputStream bos) throws IOException {
+ if (null != listener) {
+ listener.dataCode(clearCode);
+ }
+ writeCode(bos, clearCode);
+ }
+
+ private void writeCode(final MyBitOutputStream bos, final int code)
+ throws IOException {
+ bos.writeBits(code, codeSize);
+ }
+
+ private void writeDataCode(final MyBitOutputStream bos, final int code)
+ throws IOException {
+ if (null != listener) {
+ listener.dataCode(code);
+ }
+ writeCode(bos, code);
+ }
+
+ private void writeEoiCode(final MyBitOutputStream bos) throws IOException {
+ if (null != listener) {
+ listener.eoiCode(eoiCode);
+ }
+ writeCode(bos, eoiCode);
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwDecompressor.java b/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwDecompressor.java
index 320bfaa3..1aa607ef 100644
--- a/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwDecompressor.java
+++ b/src/main/java/org/apache/commons/imaging/common/mylzw/MyLzwDecompressor.java
@@ -26,6 +26,11 @@ import java.util.Arrays;
import org.apache.commons.imaging.ImageReadException;
public final class MyLzwDecompressor {
+ public interface Listener {
+ void code(int code);
+
+ void init(int clearCode, int eoiCode);
+ }
private static final int MAX_TABLE_SIZE = 1 << 12;
private final byte[][] table;
private int codeSize;
@@ -36,13 +41,8 @@ public final class MyLzwDecompressor {
private final int clearCode;
private final int eoiCode;
private int written;
- private boolean tiffLZWMode;
-
- public interface Listener {
- void code(int code);
- void init(int clearCode, int eoiCode);
- }
+ private boolean tiffLZWMode;
public MyLzwDecompressor(final int initialCodeSize, final ByteOrder byteOrder) throws ImageReadException {
this(initialCodeSize, byteOrder, null);
@@ -66,51 +66,6 @@ public final class MyLzwDecompressor {
initializeTable();
}
- private void initializeTable() throws ImageReadException {
- codeSize = initialCodeSize;
-
- final int initialEntriesCount = 1 << codeSize + 2;
-
- if (initialEntriesCount > table.length) {
- throw new ImageReadException(String.format("Invalid Lzw table length [%d]; entries count is [%d]", table.length, initialEntriesCount));
- }
-
- for (int i = 0; i < initialEntriesCount; i++) {
- table[i] = new byte[] { (byte) i, };
- }
- }
-
- private void clearTable() {
- codes = (1 << initialCodeSize) + 2;
- codeSize = initialCodeSize;
- incrementCodeSize();
- }
-
- private int getNextCode(final MyBitInputStream is) throws IOException {
- final int code = is.readBits(codeSize);
-
- if (null != listener) {
- listener.code(code);
- }
- return code;
- }
-
- private byte[] stringFromCode(final int code) throws IOException {
- if ((code >= codes) || (code < 0)) {
- throw new IOException("Bad Code: " + code + " codes: " + codes
- + " code_size: " + codeSize + ", table: " + table.length);
- }
- return table[code];
- }
-
- private boolean isInTable(final int code) {
- return code < codes;
- }
-
- private byte firstChar(final byte[] bytes) {
- return bytes[0];
- }
-
private void addStringToTable(final byte[] bytes) {
if (codes < (1 << codeSize)) {
table[codes] = bytes;
@@ -128,14 +83,21 @@ public final class MyLzwDecompressor {
return result;
}
- private void writeToResult(final OutputStream os, final byte[] bytes)
- throws IOException {
- os.write(bytes);
- written += bytes.length;
+ private void checkCodeSize() {
+ int limit = (1 << codeSize);
+ if (tiffLZWMode) {
+ limit--;
+ }
+
+ if (codes == limit) {
+ incrementCodeSize();
+ }
}
- public void setTiffLZWMode() {
- tiffLZWMode = true;
+ private void clearTable() {
+ codes = (1 << initialCodeSize) + 2;
+ codeSize = initialCodeSize;
+ incrementCodeSize();
}
public byte[] decompress(final InputStream is, final int expectedLength) throws IOException {
@@ -186,15 +148,17 @@ public final class MyLzwDecompressor {
return baos.toByteArray();
}
- private void checkCodeSize() {
- int limit = (1 << codeSize);
- if (tiffLZWMode) {
- limit--;
- }
+ private byte firstChar(final byte[] bytes) {
+ return bytes[0];
+ }
- if (codes == limit) {
- incrementCodeSize();
+ private int getNextCode(final MyBitInputStream is) throws IOException {
+ final int code = is.readBits(codeSize);
+
+ if (null != listener) {
+ listener.code(code);
}
+ return code;
}
private void incrementCodeSize() {
@@ -202,4 +166,40 @@ public final class MyLzwDecompressor {
codeSize++;
}
}
+
+ private void initializeTable() throws ImageReadException {
+ codeSize = initialCodeSize;
+
+ final int initialEntriesCount = 1 << codeSize + 2;
+
+ if (initialEntriesCount > table.length) {
+ throw new ImageReadException(String.format("Invalid Lzw table length [%d]; entries count is [%d]", table.length, initialEntriesCount));
+ }
+
+ for (int i = 0; i < initialEntriesCount; i++) {
+ table[i] = new byte[] { (byte) i, };
+ }
+ }
+
+ private boolean isInTable(final int code) {
+ return code < codes;
+ }
+
+ public void setTiffLZWMode() {
+ tiffLZWMode = true;
+ }
+
+ private byte[] stringFromCode(final int code) throws IOException {
+ if ((code >= codes) || (code < 0)) {
+ throw new IOException("Bad Code: " + code + " codes: " + codes
+ + " code_size: " + codeSize + ", table: " + table.length);
+ }
+ return table[code];
+ }
+
+ private void writeToResult(final OutputStream os, final byte[] bytes)
+ throws IOException {
+ os.write(bytes);
+ written += bytes.length;
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpHeaderInfo.java b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpHeaderInfo.java
index 0106dbe6..7625f979 100644
--- a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpHeaderInfo.java
+++ b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpHeaderInfo.java
@@ -17,6 +17,17 @@
package org.apache.commons.imaging.formats.bmp;
class BmpHeaderInfo {
+ static class ColorSpace {
+ ColorSpaceCoordinate red;
+ ColorSpaceCoordinate green;
+ ColorSpaceCoordinate blue;
+ }
+ static class ColorSpaceCoordinate {
+ int x;
+ int y;
+ int z;
+ }
+
// BM - Windows 3.1x, 95, NT
// BA - OS/2 Bitmap Array
// CI - OS/2 Color Icon
@@ -25,11 +36,10 @@ class BmpHeaderInfo {
// PT - OS/2 Pointer
public final byte identifier1;
public final byte identifier2;
-
public final int fileSize;
+
public final int reserved;
public final int bitmapDataOffset;
-
public final int bitmapHeaderSize;
public final int width;
public final int height;
@@ -39,14 +49,14 @@ class BmpHeaderInfo {
public final int bitmapDataSize;
public final int hResolution;
public final int vResolution;
+
public final int colorsUsed;
public final int colorsImportant;
-
public final int redMask;
public final int greenMask;
+
public final int blueMask;
public final int alphaMask;
-
public final int colorSpaceType;
public final ColorSpace colorSpace;
public final int gammaRed;
@@ -54,20 +64,10 @@ class BmpHeaderInfo {
public final int gammaBlue;
public final int intent;
public final int profileData;
- public final int profileSize;
- public final int reservedV5;
- static class ColorSpaceCoordinate {
- int x;
- int y;
- int z;
- }
+ public final int profileSize;
- static class ColorSpace {
- ColorSpaceCoordinate red;
- ColorSpaceCoordinate green;
- ColorSpaceCoordinate blue;
- }
+ public final int reservedV5;
BmpHeaderInfo(final byte identifier1, final byte identifier2, final int fileSize,
final int reserved, final int bitmapDataOffset, final int bitmapHeaderSize,
diff --git a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpImageParser.java b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpImageParser.java
index 72ddeac1..b2df9253 100644
--- a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpImageParser.java
+++ b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpImageParser.java
@@ -68,13 +68,84 @@ public class BmpImageParser extends ImageParser<BmpImagingParameters> {
}
@Override
- public BmpImagingParameters getDefaultParameters() {
- return new BmpImagingParameters();
+ public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
+ throws ImageReadException, IOException {
+ pw.println("bmp.dumpImageFile");
+
+ final ImageInfo imageData = getImageInfo(byteSource, null);
+
+ imageData.toString(pw, "");
+
+ pw.println("");
+
+ return true;
}
@Override
- public String getName() {
- return "Bmp-Custom";
+ protected String[] getAcceptedExtensions() {
+ return ACCEPTED_EXTENSIONS;
+ }
+
+ @Override
+ protected ImageFormat[] getAcceptedTypes() {
+ return new ImageFormat[] { ImageFormats.BMP };
+ }
+
+ private String getBmpTypeDescription(final int identifier1, final int identifier2) {
+ if ((identifier1 == 'B') && (identifier2 == 'M')) {
+ return "Windows 3.1x, 95, NT,";
+ }
+ if ((identifier1 == 'B') && (identifier2 == 'A')) {
+ return "OS/2 Bitmap Array";
+ }
+ if ((identifier1 == 'C') && (identifier2 == 'I')) {
+ return "OS/2 Color Icon";
+ }
+ if ((identifier1 == 'C') && (identifier2 == 'P')) {
+ return "OS/2 Color Pointer";
+ }
+ if ((identifier1 == 'I') && (identifier2 == 'C')) {
+ return "OS/2 Icon";
+ }
+ if ((identifier1 == 'P') && (identifier2 == 'T')) {
+ return "OS/2 Pointer";
+ }
+
+ return "Unknown";
+ }
+
+ @Override
+ public BufferedImage getBufferedImage(final ByteSource byteSource, final BmpImagingParameters params)
+ throws ImageReadException, IOException {
+ try (InputStream is = byteSource.getInputStream()) {
+ return getBufferedImage(is, params);
+ }
+ }
+
+ public BufferedImage getBufferedImage(final InputStream inputStream, final BmpImagingParameters params)
+ throws ImageReadException, IOException {
+ final BmpImageContents ic = readImageContents(inputStream, FormatCompliance.getDefault());
+
+ final BmpHeaderInfo bhi = ic.bhi;
+ // byte colorTable[] = ic.colorTable;
+ // byte imageData[] = ic.imageData;
+
+ final int width = bhi.width;
+ final int height = bhi.height;
+
+ if (LOGGER.isLoggable(Level.FINE)) {
+ LOGGER.fine("width: " + width);
+ LOGGER.fine("height: " + height);
+ LOGGER.fine("width*height: " + width * height);
+ LOGGER.fine("width*height*4: " + width * height * 4);
+ }
+
+ final PixelParser pixelParser = ic.pixelParser;
+ final ImageBuilder imageBuilder = new ImageBuilder(width, height, true);
+ pixelParser.processImage(imageBuilder);
+
+ return imageBuilder.getBufferedImage();
+
}
@Override
@@ -83,13 +154,168 @@ public class BmpImageParser extends ImageParser<BmpImagingParameters> {
}
@Override
- protected String[] getAcceptedExtensions() {
- return ACCEPTED_EXTENSIONS;
+ public BmpImagingParameters getDefaultParameters() {
+ return new BmpImagingParameters();
}
@Override
- protected ImageFormat[] getAcceptedTypes() {
- return new ImageFormat[] { ImageFormats.BMP };
+ public FormatCompliance getFormatCompliance(final ByteSource byteSource)
+ throws ImageReadException, IOException {
+ final FormatCompliance result = new FormatCompliance(
+ byteSource.getDescription());
+
+ try (InputStream is = byteSource.getInputStream()) {
+ readImageContents(is, result);
+ }
+
+ return result;
+ }
+
+ @Override
+ public byte[] getICCProfileBytes(final ByteSource byteSource, final BmpImagingParameters params)
+ throws ImageReadException, IOException {
+ return null;
+ }
+
+ @Override
+ public ImageInfo getImageInfo(final ByteSource byteSource, final BmpImagingParameters params)
+ throws ImageReadException, IOException {
+ BmpImageContents ic = null;
+ try (InputStream is = byteSource.getInputStream()) {
+ ic = readImageContents(is, FormatCompliance.getDefault());
+ }
+
+ final BmpHeaderInfo bhi = ic.bhi;
+ final byte[] colorTable = ic.colorTable;
+
+ if (bhi == null) {
+ throw new ImageReadException("BMP: couldn't read header");
+ }
+
+ final int height = bhi.height;
+ final int width = bhi.width;
+
+ final List<String> comments = new ArrayList<>();
+ // TODO: comments...
+
+ final int bitsPerPixel = bhi.bitsPerPixel;
+ final ImageFormat format = ImageFormats.BMP;
+ final String name = "BMP Windows Bitmap";
+ final String mimeType = "image/x-ms-bmp";
+ // we ought to count images, but don't yet.
+ final int numberOfImages = -1;
+ // not accurate ... only reflects first
+ final boolean progressive = false;
+ // boolean progressive = (fPNGChunkIHDR.InterlaceMethod != 0);
+ //
+ // pixels per meter
+ final int physicalWidthDpi = (int) Math.round(bhi.hResolution * .0254);
+ final float physicalWidthInch = (float) ((double) width / (double) physicalWidthDpi);
+ // int physicalHeightDpi = 72;
+ final int physicalHeightDpi = (int) Math.round(bhi.vResolution * .0254);
+ final float physicalHeightInch = (float) ((double) height / (double) physicalHeightDpi);
+
+ final String formatDetails = "Bmp (" + (char) bhi.identifier1
+ + (char) bhi.identifier2 + ": "
+ + getBmpTypeDescription(bhi.identifier1, bhi.identifier2) + ")";
+
+ final boolean transparent = false;
+
+ final boolean usesPalette = colorTable != null;
+ final ImageInfo.ColorType colorType = ImageInfo.ColorType.RGB;
+ final ImageInfo.CompressionAlgorithm compressionAlgorithm = ImageInfo.CompressionAlgorithm.RLE;
+
+ return new ImageInfo(formatDetails, bitsPerPixel, comments,
+ format, name, height, mimeType, numberOfImages,
+ physicalHeightDpi, physicalHeightInch, physicalWidthDpi,
+ physicalWidthInch, width, progressive, transparent,
+ usesPalette, colorType, compressionAlgorithm);
+ }
+
+ @Override
+ public Dimension getImageSize(final ByteSource byteSource, final BmpImagingParameters params)
+ throws ImageReadException, IOException {
+ final BmpHeaderInfo bhi = readBmpHeaderInfo(byteSource);
+
+ return new Dimension(bhi.width, bhi.height);
+
+ }
+
+ @Override
+ public ImageMetadata getMetadata(final ByteSource byteSource, final BmpImagingParameters params)
+ throws ImageReadException, IOException {
+ // TODO this should throw UnsupportedOperationException, but RoundtripTest has to be refactored completely before this can be changed
+ return null;
+ }
+
+ @Override
+ public String getName() {
+ return "Bmp-Custom";
+ }
+
+ private byte[] getRLEBytes(final InputStream is, final int rleSamplesPerByte) throws IOException {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ // this.setDebug(true);
+
+ boolean done = false;
+ while (!done) {
+ final int a = 0xff & readByte("RLE a", is, "BMP: Bad RLE");
+ baos.write(a);
+ final int b = 0xff & readByte("RLE b", is, "BMP: Bad RLE");
+ baos.write(b);
+
+ if (a == 0) {
+ switch (b) {
+ case 0: // EOL
+ break;
+ case 1: // EOF
+ // System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+ // );
+ done = true;
+ break;
+ case 2: {
+ // System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+ // );
+ final int c = 0xff & readByte("RLE c", is, "BMP: Bad RLE");
+ baos.write(c);
+ final int d = 0xff & readByte("RLE d", is, "BMP: Bad RLE");
+ baos.write(d);
+
+ }
+ break;
+ default: {
+ int size = b / rleSamplesPerByte;
+ if ((b % rleSamplesPerByte) > 0) {
+ size++;
+ }
+ if ((size % 2) != 0) {
+ size++;
+ }
+
+ // System.out.println("b: " + b);
+ // System.out.println("size: " + size);
+ // System.out.println("RLESamplesPerByte: " +
+ // RLESamplesPerByte);
+ // System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
+ // );
+ final byte[] bytes = readBytes("bytes", is, size,
+ "RLE: Absolute Mode");
+ baos.write(bytes);
+ }
+ break;
+ }
+ }
+ }
+
+ return baos.toByteArray();
+ }
+
+ private BmpHeaderInfo readBmpHeaderInfo(final ByteSource byteSource) throws ImageReadException, IOException {
+ try (InputStream is = byteSource.getInputStream()) {
+ // readSignature(is);
+ return readBmpHeaderInfo(is, null);
+ }
}
private BmpHeaderInfo readBmpHeaderInfo(final InputStream is,
@@ -243,64 +469,6 @@ public class BmpImageParser extends ImageParser<BmpImagingParameters> {
profileSize, reservedV5);
}
- private byte[] getRLEBytes(final InputStream is, final int rleSamplesPerByte) throws IOException {
- final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- // this.setDebug(true);
-
- boolean done = false;
- while (!done) {
- final int a = 0xff & readByte("RLE a", is, "BMP: Bad RLE");
- baos.write(a);
- final int b = 0xff & readByte("RLE b", is, "BMP: Bad RLE");
- baos.write(b);
-
- if (a == 0) {
- switch (b) {
- case 0: // EOL
- break;
- case 1: // EOF
- // System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
- // );
- done = true;
- break;
- case 2: {
- // System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
- // );
- final int c = 0xff & readByte("RLE c", is, "BMP: Bad RLE");
- baos.write(c);
- final int d = 0xff & readByte("RLE d", is, "BMP: Bad RLE");
- baos.write(d);
-
- }
- break;
- default: {
- int size = b / rleSamplesPerByte;
- if ((b % rleSamplesPerByte) > 0) {
- size++;
- }
- if ((size % 2) != 0) {
- size++;
- }
-
- // System.out.println("b: " + b);
- // System.out.println("size: " + size);
- // System.out.println("RLESamplesPerByte: " +
- // RLESamplesPerByte);
- // System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
- // );
- final byte[] bytes = readBytes("bytes", is, size,
- "RLE: Absolute Mode");
- baos.write(bytes);
- }
- break;
- }
- }
- }
-
- return baos.toByteArray();
- }
-
private BmpImageContents readImageContents(final InputStream is,
final FormatCompliance formatCompliance)
throws ImageReadException, IOException {
@@ -480,174 +648,6 @@ public class BmpImageParser extends ImageParser<BmpImagingParameters> {
return new BmpImageContents(bhi, colorTable, imageData, pixelParser);
}
- private BmpHeaderInfo readBmpHeaderInfo(final ByteSource byteSource) throws ImageReadException, IOException {
- try (InputStream is = byteSource.getInputStream()) {
- // readSignature(is);
- return readBmpHeaderInfo(is, null);
- }
- }
-
- @Override
- public byte[] getICCProfileBytes(final ByteSource byteSource, final BmpImagingParameters params)
- throws ImageReadException, IOException {
- return null;
- }
-
- @Override
- public Dimension getImageSize(final ByteSource byteSource, final BmpImagingParameters params)
- throws ImageReadException, IOException {
- final BmpHeaderInfo bhi = readBmpHeaderInfo(byteSource);
-
- return new Dimension(bhi.width, bhi.height);
-
- }
-
- @Override
- public ImageMetadata getMetadata(final ByteSource byteSource, final BmpImagingParameters params)
- throws ImageReadException, IOException {
- // TODO this should throw UnsupportedOperationException, but RoundtripTest has to be refactored completely before this can be changed
- return null;
- }
-
- private String getBmpTypeDescription(final int identifier1, final int identifier2) {
- if ((identifier1 == 'B') && (identifier2 == 'M')) {
- return "Windows 3.1x, 95, NT,";
- }
- if ((identifier1 == 'B') && (identifier2 == 'A')) {
- return "OS/2 Bitmap Array";
- }
- if ((identifier1 == 'C') && (identifier2 == 'I')) {
- return "OS/2 Color Icon";
- }
- if ((identifier1 == 'C') && (identifier2 == 'P')) {
- return "OS/2 Color Pointer";
- }
- if ((identifier1 == 'I') && (identifier2 == 'C')) {
- return "OS/2 Icon";
- }
- if ((identifier1 == 'P') && (identifier2 == 'T')) {
- return "OS/2 Pointer";
- }
-
- return "Unknown";
- }
-
- @Override
- public ImageInfo getImageInfo(final ByteSource byteSource, final BmpImagingParameters params)
- throws ImageReadException, IOException {
- BmpImageContents ic = null;
- try (InputStream is = byteSource.getInputStream()) {
- ic = readImageContents(is, FormatCompliance.getDefault());
- }
-
- final BmpHeaderInfo bhi = ic.bhi;
- final byte[] colorTable = ic.colorTable;
-
- if (bhi == null) {
- throw new ImageReadException("BMP: couldn't read header");
- }
-
- final int height = bhi.height;
- final int width = bhi.width;
-
- final List<String> comments = new ArrayList<>();
- // TODO: comments...
-
- final int bitsPerPixel = bhi.bitsPerPixel;
- final ImageFormat format = ImageFormats.BMP;
- final String name = "BMP Windows Bitmap";
- final String mimeType = "image/x-ms-bmp";
- // we ought to count images, but don't yet.
- final int numberOfImages = -1;
- // not accurate ... only reflects first
- final boolean progressive = false;
- // boolean progressive = (fPNGChunkIHDR.InterlaceMethod != 0);
- //
- // pixels per meter
- final int physicalWidthDpi = (int) Math.round(bhi.hResolution * .0254);
- final float physicalWidthInch = (float) ((double) width / (double) physicalWidthDpi);
- // int physicalHeightDpi = 72;
- final int physicalHeightDpi = (int) Math.round(bhi.vResolution * .0254);
- final float physicalHeightInch = (float) ((double) height / (double) physicalHeightDpi);
-
- final String formatDetails = "Bmp (" + (char) bhi.identifier1
- + (char) bhi.identifier2 + ": "
- + getBmpTypeDescription(bhi.identifier1, bhi.identifier2) + ")";
-
- final boolean transparent = false;
-
- final boolean usesPalette = colorTable != null;
- final ImageInfo.ColorType colorType = ImageInfo.ColorType.RGB;
- final ImageInfo.CompressionAlgorithm compressionAlgorithm = ImageInfo.CompressionAlgorithm.RLE;
-
- return new ImageInfo(formatDetails, bitsPerPixel, comments,
- format, name, height, mimeType, numberOfImages,
- physicalHeightDpi, physicalHeightInch, physicalWidthDpi,
- physicalWidthInch, width, progressive, transparent,
- usesPalette, colorType, compressionAlgorithm);
- }
-
- @Override
- public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
- throws ImageReadException, IOException {
- pw.println("bmp.dumpImageFile");
-
- final ImageInfo imageData = getImageInfo(byteSource, null);
-
- imageData.toString(pw, "");
-
- pw.println("");
-
- return true;
- }
-
- @Override
- public FormatCompliance getFormatCompliance(final ByteSource byteSource)
- throws ImageReadException, IOException {
- final FormatCompliance result = new FormatCompliance(
- byteSource.getDescription());
-
- try (InputStream is = byteSource.getInputStream()) {
- readImageContents(is, result);
- }
-
- return result;
- }
-
- @Override
- public BufferedImage getBufferedImage(final ByteSource byteSource, final BmpImagingParameters params)
- throws ImageReadException, IOException {
- try (InputStream is = byteSource.getInputStream()) {
- return getBufferedImage(is, params);
- }
- }
-
- public BufferedImage getBufferedImage(final InputStream inputStream, final BmpImagingParameters params)
- throws ImageReadException, IOException {
- final BmpImageContents ic = readImageContents(inputStream, FormatCompliance.getDefault());
-
- final BmpHeaderInfo bhi = ic.bhi;
- // byte colorTable[] = ic.colorTable;
- // byte imageData[] = ic.imageData;
-
- final int width = bhi.width;
- final int height = bhi.height;
-
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.fine("width: " + width);
- LOGGER.fine("height: " + height);
- LOGGER.fine("width*height: " + width * height);
- LOGGER.fine("width*height*4: " + width * height * 4);
- }
-
- final PixelParser pixelParser = ic.pixelParser;
- final ImageBuilder imageBuilder = new ImageBuilder(width, height, true);
- pixelParser.processImage(imageBuilder);
-
- return imageBuilder.getBufferedImage();
-
- }
-
@Override
public void writeImage(final BufferedImage src, final OutputStream os, BmpImagingParameters params) throws ImageWriteException, IOException {
if (params == null) {
diff --git a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriter.java b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriter.java
index 9943e988..e95ce7c3 100644
--- a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriter.java
+++ b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriter.java
@@ -23,11 +23,11 @@ import org.apache.commons.imaging.common.BinaryOutputStream;
interface BmpWriter {
- int getPaletteSize();
-
int getBitsPerPixel();
- void writePalette(BinaryOutputStream bos) throws IOException;
-
byte[] getImageData(BufferedImage src);
+
+ int getPaletteSize();
+
+ void writePalette(BinaryOutputStream bos) throws IOException;
}
diff --git a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterPalette.java b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterPalette.java
index 04aa86dc..2ef606bb 100644
--- a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterPalette.java
+++ b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterPalette.java
@@ -40,32 +40,11 @@ class BmpWriterPalette implements BmpWriter {
}
}
- @Override
- public int getPaletteSize() {
- return palette.length();
- }
-
@Override
public int getBitsPerPixel() {
return bitsPerSample;
}
- @Override
- public void writePalette(final BinaryOutputStream bos) throws IOException {
- for (int i = 0; i < palette.length(); i++) {
- final int rgb = palette.getEntry(i);
-
- final int red = 0xff & (rgb >> 16);
- final int green = 0xff & (rgb >> 8);
- final int blue = 0xff & (rgb >> 0);
-
- bos.write(blue);
- bos.write(green);
- bos.write(red);
- bos.write(0);
- }
- }
-
@Override
public byte[] getImageData(final BufferedImage src) {
final int width = src.getWidth();
@@ -117,4 +96,25 @@ class BmpWriterPalette implements BmpWriter {
return baos.toByteArray();
}
+
+ @Override
+ public int getPaletteSize() {
+ return palette.length();
+ }
+
+ @Override
+ public void writePalette(final BinaryOutputStream bos) throws IOException {
+ for (int i = 0; i < palette.length(); i++) {
+ final int rgb = palette.getEntry(i);
+
+ final int red = 0xff & (rgb >> 16);
+ final int green = 0xff & (rgb >> 8);
+ final int blue = 0xff & (rgb >> 0);
+
+ bos.write(blue);
+ bos.write(green);
+ bos.write(red);
+ bos.write(0);
+ }
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterRgb.java b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterRgb.java
index ebd36bd6..cc87d7d9 100644
--- a/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterRgb.java
+++ b/src/main/java/org/apache/commons/imaging/formats/bmp/BmpWriterRgb.java
@@ -30,22 +30,12 @@ class BmpWriterRgb implements BmpWriter {
// this.alpha = alpha;
// }
- @Override
- public int getPaletteSize() {
- return 0;
- }
-
@Override
public int getBitsPerPixel() {
// return alpha ? 32 : 24;
return 24;
}
- @Override
- public void writePalette(final BinaryOutputStream bos) throws IOException {
- // no palette
- }
-
@Override
public byte[] getImageData(final BufferedImage src) {
final int width = src.getWidth();
@@ -79,4 +69,14 @@ class BmpWriterRgb implements BmpWriter {
return baos.toByteArray();
}
+
+ @Override
+ public int getPaletteSize() {
+ return 0;
+ }
+
+ @Override
+ public void writePalette(final BinaryOutputStream bos) throws IOException {
+ // no palette
+ }
}
diff --git a/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParser.java b/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParser.java
index 0692b74d..1a858b7f 100644
--- a/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParser.java
+++ b/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParser.java
@@ -39,8 +39,6 @@ abstract class PixelParser {
is = new ByteArrayInputStream(imageData);
}
- public abstract void processImage(ImageBuilder imageBuilder) throws ImageReadException, IOException;
-
int getColorTableRGB(int index) {
index *= 4;
final int blue = 0xff & colorTable[index + 0];
@@ -54,4 +52,6 @@ abstract class PixelParser {
| (blue << 0);
}
+ public abstract void processImage(ImageBuilder imageBuilder) throws ImageReadException, IOException;
+
}
diff --git a/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParserRle.java b/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParserRle.java
index ba30102f..00837586 100644
--- a/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParserRle.java
+++ b/src/main/java/org/apache/commons/imaging/formats/bmp/PixelParserRle.java
@@ -31,17 +31,6 @@ class PixelParserRle extends PixelParser {
super(bhi, colorTable, imageData);
}
- private int getSamplesPerByte() throws ImageReadException {
- if (bhi.bitsPerPixel == 8) {
- return 1;
- }
- if (bhi.bitsPerPixel == 4) {
- return 2;
- }
- throw new ImageReadException("BMP RLE: bad BitsPerPixel: "
- + bhi.bitsPerPixel);
- }
-
private int[] convertDataToSamples(final int data) throws ImageReadException {
int[] rgbs;
if (bhi.bitsPerPixel == 8) {
@@ -63,6 +52,17 @@ class PixelParserRle extends PixelParser {
return rgbs;
}
+ private int getSamplesPerByte() throws ImageReadException {
+ if (bhi.bitsPerPixel == 8) {
+ return 1;
+ }
+ if (bhi.bitsPerPixel == 4) {
+ return 2;
+ }
+ throw new ImageReadException("BMP RLE: bad BitsPerPixel: "
+ + bhi.bitsPerPixel);
+ }
+
private int processByteOfData(final int[] rgbs, final int repeat, int x, final int y,
final int width, final int height, final ImageBuilder imageBuilder) {
// int rbg
diff --git a/src/main/java/org/apache/commons/imaging/formats/dcx/DcxImageParser.java b/src/main/java/org/apache/commons/imaging/formats/dcx/DcxImageParser.java
index 96dce6fd..630b6dac 100644
--- a/src/main/java/org/apache/commons/imaging/formats/dcx/DcxImageParser.java
+++ b/src/main/java/org/apache/commons/imaging/formats/dcx/DcxImageParser.java
@@ -42,8 +42,27 @@ import org.apache.commons.imaging.formats.pcx.PcxImageParser;
import org.apache.commons.imaging.formats.pcx.PcxImagingParameters;
public class DcxImageParser extends ImageParser<PcxImagingParameters> {
+ private static class DcxHeader {
+
+ public static final int DCX_ID = 0x3ADE68B1;
+ public final int id;
+ public final long[] pageTable;
+
+ DcxHeader(final int id, final long[] pageTable) {
+ this.id = id;
+ this.pageTable = pageTable;
+ }
+
+ public void dump(final PrintWriter pw) {
+ pw.println("DcxHeader");
+ pw.println("Id: 0x" + Integer.toHexString(id));
+ pw.println("Pages: " + pageTable.length);
+ pw.println();
+ }
+ }
// See http://www.fileformat.fine/format/pcx/egff.htm for documentation
private static final String DEFAULT_EXTENSION = ImageFormats.DCX.getDefaultExtension();
+
private static final String[] ACCEPTED_EXTENSIONS = ImageFormats.DCX.getExtensions();
public DcxImageParser() {
@@ -51,33 +70,60 @@ public class DcxImageParser extends ImageParser<PcxImagingParameters> {
}
@Override
- public PcxImagingParameters getDefaultParameters() {
- return new PcxImagingParameters();
+ public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
+ throws ImageReadException, IOException {
+ readDcxHeader(byteSource).dump(pw);
+ return true;
}
@Override
- public String getName() {
- return "Dcx-Custom";
+ protected String[] getAcceptedExtensions() {
+ return ACCEPTED_EXTENSIONS;
}
@Override
- public String getDefaultExtension() {
- return DEFAULT_EXTENSION;
+ protected ImageFormat[] getAcceptedTypes() {
+ return new ImageFormat[] { ImageFormats.DCX };
}
@Override
- protected String[] getAcceptedExtensions() {
- return ACCEPTED_EXTENSIONS;
+ public List<BufferedImage> getAllBufferedImages(final ByteSource byteSource)
+ throws ImageReadException, IOException {
+ final DcxHeader dcxHeader = readDcxHeader(byteSource);
+ final List<BufferedImage> images = new ArrayList<>();
+ final PcxImageParser pcxImageParser = new PcxImageParser();
+ for (final long element : dcxHeader.pageTable) {
+ try (InputStream stream = byteSource.getInputStream(element)) {
+ final ByteSourceInputStream pcxSource = new ByteSourceInputStream(
+ stream, null);
+ final BufferedImage image = pcxImageParser.getBufferedImage(
+ pcxSource, new PcxImagingParameters());
+ images.add(image);
+ }
+ }
+ return images;
}
@Override
- protected ImageFormat[] getAcceptedTypes() {
- return new ImageFormat[] { ImageFormats.DCX };
+ public final BufferedImage getBufferedImage(final ByteSource byteSource,
+ final PcxImagingParameters params) throws ImageReadException, IOException {
+ final List<BufferedImage> list = getAllBufferedImages(byteSource);
+ return list.isEmpty() ? null : list.get(0);
+ }
+
+ @Override
+ public String getDefaultExtension() {
+ return DEFAULT_EXTENSION;
+ }
+
+ @Override
+ public PcxImagingParameters getDefaultParameters() {
+ return new PcxImagingParameters();
}
// FIXME should throw UOE
@Override
- public ImageMetadata getMetadata(final ByteSource byteSource, final PcxImagingParameters params)
+ public byte[] getICCProfileBytes(final ByteSource byteSource, final PcxImagingParameters params)
throws ImageReadException, IOException {
return null;
}
@@ -98,28 +144,14 @@ public class DcxImageParser extends ImageParser<PcxImagingParameters> {
// FIXME should throw UOE
@Override
- public byte[] getICCProfileBytes(final ByteSource byteSource, final PcxImagingParameters params)
+ public ImageMetadata getMetadata(final ByteSource byteSource, final PcxImagingParameters params)
throws ImageReadException, IOException {
return null;
}
- private static class DcxHeader {
-
- public static final int DCX_ID = 0x3ADE68B1;
- public final int id;
- public final long[] pageTable;
-
- DcxHeader(final int id, final long[] pageTable) {
- this.id = id;
- this.pageTable = pageTable;
- }
-
- public void dump(final PrintWriter pw) {
- pw.println("DcxHeader");
- pw.println("Id: 0x" + Integer.toHexString(id));
- pw.println("Pages: " + pageTable.length);
- pw.println();
- }
+ @Override
+ public String getName() {
+ return "Dcx-Custom";
}
private DcxHeader readDcxHeader(final ByteSource byteSource)
@@ -147,38 +179,6 @@ public class DcxImageParser extends ImageParser<PcxImagingParameters> {
}
}
- @Override
- public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
- throws ImageReadException, IOException {
- readDcxHeader(byteSource).dump(pw);
- return true;
- }
-
- @Override
- public final BufferedImage getBufferedImage(final ByteSource byteSource,
- final PcxImagingParameters params) throws ImageReadException, IOException {
- final List<BufferedImage> list = getAllBufferedImages(byteSource);
- return list.isEmpty() ? null : list.get(0);
- }
-
- @Override
- public List<BufferedImage> getAllBufferedImages(final ByteSource byteSource)
- throws ImageReadException, IOException {
- final DcxHeader dcxHeader = readDcxHeader(byteSource);
- final List<BufferedImage> images = new ArrayList<>();
- final PcxImageParser pcxImageParser = new PcxImageParser();
- for (final long element : dcxHeader.pageTable) {
- try (InputStream stream = byteSource.getInputStream(element)) {
- final ByteSourceInputStream pcxSource = new ByteSourceInputStream(
- stream, null);
- final BufferedImage image = pcxImageParser.getBufferedImage(
- pcxSource, new PcxImagingParameters());
- images.add(image);
- }
- }
- return images;
- }
-
@Override
public void writeImage(final BufferedImage src, final OutputStream os, final PcxImagingParameters params)
throws ImageWriteException, IOException {
diff --git a/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadata.java b/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadata.java
index f6e5d08c..e3ed1203 100644
--- a/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadata.java
+++ b/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadata.java
@@ -34,6 +34,19 @@ public class GifImageMetadata implements ImageMetadata {
this.items = Collections.unmodifiableList(new ArrayList<>(items));
}
+ public int getHeight() {
+ return height;
+ }
+
+ @Override
+ public List<GifImageMetadataItem> getItems() {
+ return Collections.unmodifiableList(items);
+ }
+
+ public int getWidth() {
+ return width;
+ }
+
@Override
public String toString(String prefix) {
prefix = prefix == null ? "" : prefix;
@@ -49,17 +62,4 @@ public class GifImageMetadata implements ImageMetadata {
}
return result.toString();
}
-
- public int getWidth() {
- return width;
- }
-
- public int getHeight() {
- return height;
- }
-
- @Override
- public List<GifImageMetadataItem> getItems() {
- return Collections.unmodifiableList(items);
- }
}
diff --git a/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadataItem.java b/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadataItem.java
index 1a894ac8..d5d1e937 100644
--- a/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadataItem.java
+++ b/src/main/java/org/apache/commons/imaging/formats/gif/GifImageMetadataItem.java
@@ -36,6 +36,10 @@ public class GifImageMetadataItem implements ImageMetadata.ImageMetadataItem {
return delay;
}
+ public DisposalMethod getDisposalMethod() {
+ return disposalMethod;
+ }
+
public int getLeftPosition() {
return leftPosition;
}
@@ -44,10 +48,6 @@ public class GifImageMetadataItem implements ImageMetadata.ImageMetadataItem {
return topPosition;
}
- public DisposalMethod getDisposalMethod() {
- return disposalMethod;
- }
-
@Override
public String toString(String prefix) {
prefix = prefix == null ? "" : prefix;
diff --git a/src/main/java/org/apache/commons/imaging/formats/gif/GifImageParser.java b/src/main/java/org/apache/commons/imaging/formats/gif/GifImageParser.java
index acef3872..ba86a721 100644
--- a/src/main/java/org/apache/commons/imaging/formats/gif/GifImageParser.java
+++ b/src/main/java/org/apache/commons/imaging/formats/gif/GifImageParser.java
@@ -89,398 +89,377 @@ public class GifImageParser extends ImageParser<GifImagingParameters> implements
0x50, // P
};
+ // Made internal for testability.
+ static DisposalMethod createDisposalMethodFromIntValue(final int value) throws ImageReadException {
+ switch (value) {
+ case 0:
+ return DisposalMethod.UNSPECIFIED;
+ case 1:
+ return DisposalMethod.DO_NOT_DISPOSE;
+ case 2:
+ return DisposalMethod.RESTORE_TO_BACKGROUND;
+ case 3:
+ return DisposalMethod.RESTORE_TO_PREVIOUS;
+ case 4:
+ return DisposalMethod.TO_BE_DEFINED_1;
+ case 5:
+ return DisposalMethod.TO_BE_DEFINED_2;
+ case 6:
+ return DisposalMethod.TO_BE_DEFINED_3;
+ case 7:
+ return DisposalMethod.TO_BE_DEFINED_4;
+ default:
+ throw new ImageReadException("GIF: Invalid parsing of disposal method");
+ }
+ }
+
public GifImageParser() {
super.setByteOrder(ByteOrder.LITTLE_ENDIAN);
}
- @Override
- public GifImagingParameters getDefaultParameters() {
- return new GifImagingParameters();
+ private int convertColorTableSize(final int tableSize) {
+ return 3 * simplePow(2, tableSize + 1);
}
@Override
- public String getName() {
- return "Graphics Interchange Format";
- }
+ public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
+ throws ImageReadException, IOException {
+ pw.println("gif.dumpImageFile");
- @Override
- public String getDefaultExtension() {
- return DEFAULT_EXTENSION;
- }
+ final ImageInfo imageData = getImageInfo(byteSource);
+ if (imageData == null) {
+ return false;
+ }
- @Override
- protected String[] getAcceptedExtensions() {
- return ACCEPTED_EXTENSIONS;
- }
+ imageData.toString(pw, "");
- @Override
- protected ImageFormat[] getAcceptedTypes() {
- return new ImageFormat[] { ImageFormats.GIF, //
- };
- }
+ final GifImageContents blocks = readFile(byteSource, false);
- private GifHeaderInfo readHeader(final InputStream is,
- final FormatCompliance formatCompliance) throws ImageReadException,
- IOException {
- final byte identifier1 = readByte("identifier1", is, "Not a Valid GIF File");
- final byte identifier2 = readByte("identifier2", is, "Not a Valid GIF File");
- final byte identifier3 = readByte("identifier3", is, "Not a Valid GIF File");
+ pw.println("gif.blocks: " + blocks.blocks.size());
+ for (int i = 0; i < blocks.blocks.size(); i++) {
+ final GifBlock gifBlock = blocks.blocks.get(i);
+ this.debugNumber(pw, "\t" + i + " ("
+ + gifBlock.getClass().getName() + ")",
+ gifBlock.blockCode, 4);
+ }
- final byte version1 = readByte("version1", is, "Not a Valid GIF File");
- final byte version2 = readByte("version2", is, "Not a Valid GIF File");
- final byte version3 = readByte("version3", is, "Not a Valid GIF File");
+ pw.println("");
- if (formatCompliance != null) {
- formatCompliance.compareBytes("Signature", GIF_HEADER_SIGNATURE,
- new byte[]{identifier1, identifier2, identifier3,});
- formatCompliance.compare("version", 56, version1);
- formatCompliance.compare("version", new int[] { 55, 57, }, version2);
- formatCompliance.compare("version", 97, version3);
- }
+ return true;
+ }
- if (LOGGER.isLoggable(Level.FINEST)) {
- printCharQuad("identifier: ", ((identifier1 << 16)
- | (identifier2 << 8) | (identifier3 << 0)));
- printCharQuad("version: ",
- ((version1 << 16) | (version2 << 8) | (version3 << 0)));
+ /**
+ * See {@link GifImageParser#readBlocks} for reference how the blocks are created. They should match
+ * the code we are giving here, returning the correct class type. Internal only.
+ */
+ @SuppressWarnings("unchecked")
+ private <T extends GifBlock> List<T> findAllBlocks(final List<GifBlock> blocks, final int code) {
+ final List<T> filteredBlocks = new ArrayList<>();
+ for (final GifBlock gifBlock : blocks) {
+ if (gifBlock.blockCode == code) {
+ filteredBlocks.add((T) gifBlock);
+ }
}
+ return filteredBlocks;
+ }
- final int logicalScreenWidth = read2Bytes("Logical Screen Width", is, "Not a Valid GIF File", getByteOrder());
- final int logicalScreenHeight = read2Bytes("Logical Screen Height", is, "Not a Valid GIF File", getByteOrder());
+ private List<GifImageData> findAllImageData(final GifImageContents imageContents) throws ImageReadException {
+ final List<ImageDescriptor> descriptors = findAllBlocks(imageContents.blocks, IMAGE_SEPARATOR);
- if (formatCompliance != null) {
- formatCompliance.checkBounds("Width", 1, Integer.MAX_VALUE,
- logicalScreenWidth);
- formatCompliance.checkBounds("Height", 1, Integer.MAX_VALUE,
- logicalScreenHeight);
+ if (descriptors.isEmpty()) {
+ throw new ImageReadException("GIF: Couldn't read Image Descriptor");
}
- final byte packedFields = readByte("Packed Fields", is,
- "Not a Valid GIF File");
- final byte backgroundColorIndex = readByte("Background Color Index", is,
- "Not a Valid GIF File");
- final byte pixelAspectRatio = readByte("Pixel Aspect Ratio", is,
- "Not a Valid GIF File");
+ final List<GraphicControlExtension> gcExtensions = findAllBlocks(imageContents.blocks, GRAPHIC_CONTROL_EXTENSION);
- if (LOGGER.isLoggable(Level.FINEST)) {
- printByteBits("PackedFields bits", packedFields);
+ if (!gcExtensions.isEmpty() && gcExtensions.size() != descriptors.size()) {
+ throw new ImageReadException("GIF: Invalid amount of Graphic Control Extensions");
}
... 31725 lines suppressed ...