org.apache.commons.imaging.ImageReadException Java Examples

The following examples show how to use org.apache.commons.imaging.ImageReadException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RgbeReadTest.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws IOException, ImageReadException {
    Debug.debug("start");

    final List<File> images = getRgbeImages();

    for (final File imageFile : images) {

        Debug.debug("imageFile", imageFile);

        final ImageMetadata metadata = Imaging.getMetadata(imageFile);
        assertNotNull(metadata);

        final ImageInfo imageInfo = Imaging.getImageInfo(imageFile);
        assertNotNull(imageInfo);

        final BufferedImage image = Imaging.getBufferedImage(imageFile);
        assertNotNull(image);
    }
}
 
Example #2
Source File: PhotometricInterpreterBiLevel.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
@Override
public void interpretPixel(final ImageBuilder imageBuilder, final int[] samples, final int x,
        final int y) throws ImageReadException, IOException {
    int sample = samples[0];

    if (invert) {
        sample = 255 - sample;
    }

    final int red = sample;
    final int green = sample;
    final int blue = sample;

    final int alpha = 0xff;
    final int rgb = (alpha << 24) | (red << 16) | (green << 8) | (blue << 0);

    imageBuilder.setRGB(x, y, rgb);
}
 
Example #3
Source File: PngChunkZtxt.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
public PngChunkZtxt(final int length, final int chunkType, final int crc, final byte[] bytes)
        throws ImageReadException, IOException {
    super(length, chunkType, crc, bytes);

    int index = findNull(bytes);
    if (index < 0) {
        throw new ImageReadException(
                "PNG zTXt chunk keyword is unterminated.");
    }

    keyword = new String(bytes, 0, index, StandardCharsets.ISO_8859_1);
    index++;

    final int compressionMethod = bytes[index++];
    if (compressionMethod != PngConstants.COMPRESSION_DEFLATE_INFLATE) {
        throw new ImageReadException(
                "PNG zTXt chunk has unexpected compression method: "
                        + compressionMethod);
    }

    final int compressedTextLength = bytes.length - index;
    final byte[] compressedText = new byte[compressedTextLength];
    System.arraycopy(bytes, index, compressedText, 0, compressedTextLength);

    text = new String(getStreamBytes(new InflaterInputStream(new ByteArrayInputStream(compressedText))), StandardCharsets.ISO_8859_1);
}
 
Example #4
Source File: JpegXmpRewriter.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a Jpeg image, replaces the XMP XML and writes the result to a
 * stream.
 *
 * @param byteSource
 *            ByteSource containing Jpeg image data.
 * @param os
 *            OutputStream to write the image to.
 * @param xmpXml
 *            String containing XMP XML.
 * @throws ImageReadException if it fails to read the JFIF segments
 * @throws IOException if it fails to read or write the data from the segments
 * @throws ImageWriteException if it fails to write the JFIF segments
 */
public void updateXmpXml(final ByteSource byteSource, final OutputStream os,
        final String xmpXml) throws ImageReadException, IOException,
        ImageWriteException {
    final JFIFPieces jfifPieces = analyzeJFIF(byteSource);
    List<JFIFPiece> pieces = jfifPieces.pieces;
    pieces = removeXmpSegments(pieces);

    final List<JFIFPieceSegment> newPieces = new ArrayList<>();
    final byte[] xmpXmlBytes = xmpXml.getBytes(StandardCharsets.UTF_8);
    int index = 0;
    while (index < xmpXmlBytes.length) {
        final int segmentSize = Math.min(xmpXmlBytes.length, JpegConstants.MAX_SEGMENT_SIZE);
        final byte[] segmentData = writeXmpSegment(xmpXmlBytes, index,
                segmentSize);
        newPieces.add(new JFIFPieceSegment(JpegConstants.JPEG_APP1_MARKER, segmentData));
        index += segmentSize;
    }

    pieces = insertAfterLastAppSegments(pieces, newPieces);

    writeSegments(os, pieces);
}
 
Example #5
Source File: Image.java    From qart4j with GNU General Public License v3.0 6 votes vote down vote up
public Image(int[][] target, int dx, int dy, String URL,
             int version, int mask, int rotation,
             boolean randControl, long seed, boolean dither, boolean onlyDataBits, boolean saveControl) throws IOException, ImageReadException {
    this.target = target;
    this.dx = dx;
    this.dy = dy;
    this.URL = URL;

    this.version = version;
    this.mask = mask;
    this.rotation = rotation;

    this.randControl = randControl;
    this.seed = seed;
    this.dither = dither;
    this.onlyDataBits = onlyDataBits;
    this.saveControl = saveControl;

    this.divider = calculateDivider();
}
 
Example #6
Source File: TextFieldTest.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
@Override
protected void checkField(final File imageFile, final TiffField field)
        throws IOException, ImageReadException, ImageWriteException {
    if (field.getTag() == ExifTagConstants.EXIF_TAG_USER_COMMENT.tag) {
        // do nothing
    } else if (field.getTag() == GpsTagConstants.GPS_TAG_GPS_PROCESSING_METHOD.tag
            && field.getDirectoryType() == TiffDirectoryType.EXIF_DIRECTORY_GPS.directoryType) {
            // do nothing
    } else if (field.getTag() == GpsTagConstants.GPS_TAG_GPS_AREA_INFORMATION.tag
            && field.getDirectoryType() == TiffDirectoryType.EXIF_DIRECTORY_GPS.directoryType) {
            // do nothing
    } else {
        return;
    }

    try {
        final Object textFieldValue = field.getValue();
        Assertions.assertNotNull(textFieldValue);
        // TODO what else to assert?
    } catch (final ImageReadException e) {
        Debug.debug("imageFile", imageFile.getAbsoluteFile());
        Debug.debug(e);
        throw e;
    }

}
 
Example #7
Source File: PngChunkScal.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
public PngChunkScal(final int length, final int chunkType, final int crc, final byte[] bytes)
      throws ImageReadException, IOException {
   super(length, chunkType, crc, bytes);

   unitSpecifier = bytes[0];
   if (unitSpecifier != 1 && unitSpecifier != 2) {
      throw new ImageReadException("PNG sCAL invalid unit specifier: " + unitSpecifier);
   }

   final int separator = findNull(bytes);
   if (separator < 0) {
      throw new ImageReadException("PNG sCAL x and y axis value separator not found.");
   }

   final int xIndex = 1;
   final String xStr = new String(bytes, xIndex, separator - 1, StandardCharsets.ISO_8859_1);
   unitsPerPixelXAxis = toDouble(xStr);

   final int yIndex = separator + 1;
   if (yIndex >= length) {
      throw new ImageReadException("PNG sCAL chunk missing the y axis value.");
   }

   final String yStr = new String(bytes, yIndex, length - yIndex, StandardCharsets.ISO_8859_1);
   unitsPerPixelYAxis = toDouble(yStr);
}
 
Example #8
Source File: DcxImageParser.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
@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 HashMap<String, Object>());
            images.add(image);
        }
    }
    return images;
}
 
Example #9
Source File: TiffDirectory.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
private List<ImageDataElement> getRawImageDataElements(
        final TiffField offsetsField, final TiffField byteCountsField)
        throws ImageReadException {
    final int[] offsets = offsetsField.getIntArrayValue();
    final int[] byteCounts = byteCountsField.getIntArrayValue();

    if (offsets.length != byteCounts.length) {
        throw new ImageReadException("offsets.length(" + offsets.length
                + ") != byteCounts.length(" + byteCounts.length + ")");
    }

    final List<ImageDataElement> result = new ArrayList<>(offsets.length);
    for (int i = 0; i < offsets.length; i++) {
        result.add(new ImageDataElement(offsets[i], byteCounts[i]));
    }
    return result;
}
 
Example #10
Source File: JpegImageMetadata.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the data of the first JPEG thumbnail found in the EXIF metadata.
 *
 * @return JPEG data or null if no thumbnail.
 * @throws ImageReadException if it fails to read the image
 * @throws IOException if an IO error occurred
 */
public byte[] getEXIFThumbnailData() throws ImageReadException, IOException {
    if (exif == null) {
        return null;
    }
    final List<? extends ImageMetadataItem> dirs = exif.getDirectories();
    for (final ImageMetadataItem d : dirs) {
        final TiffImageMetadata.Directory dir = (TiffImageMetadata.Directory) d;

        byte[] data = null;
        if (dir.getJpegImageData() != null) {
            data = dir.getJpegImageData().getData();
        }
        // Support other image formats here.

        if (data != null) {
            // already cloned, safe to return this copy
            return data;
        }
    }
    return null;
}
 
Example #11
Source File: TiffReader.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
private TiffHeader readTiffHeader(final InputStream is) throws ImageReadException, IOException {
    final int byteOrder1 = readByte("BYTE_ORDER_1", is, "Not a Valid TIFF File");
    final int byteOrder2 = readByte("BYTE_ORDER_2", is, "Not a Valid TIFF File");
    if (byteOrder1 != byteOrder2) {
        throw new ImageReadException("Byte Order bytes don't match (" + byteOrder1 + ", " + byteOrder2 + ").");
    }

    final ByteOrder byteOrder = getTiffByteOrder(byteOrder1);
    setByteOrder(byteOrder);

    final int tiffVersion = read2Bytes("tiffVersion", is, "Not a Valid TIFF File", getByteOrder());
    if (tiffVersion != 42) {
        throw new ImageReadException("Unknown Tiff Version: " + tiffVersion);
    }

    final long offsetToFirstIFD =
            0xFFFFffffL & read4Bytes("offsetToFirstIFD", is, "Not a Valid TIFF File", getByteOrder());

    skipBytes(is, offsetToFirstIFD - 8, "Not a Valid TIFF File: couldn't find IFDs");

    return new TiffHeader(byteOrder, tiffVersion, offsetToFirstIFD);
}
 
Example #12
Source File: IcnsImageParser.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
@Override
public Dimension getImageSize(final ByteSource byteSource, Map<String, Object> params)
        throws ImageReadException, IOException {
    // make copy of params; we'll clear keys as we consume them.
    params = (params == null) ? new HashMap<>() : new HashMap<>(params);

    if (!params.isEmpty()) {
        final Object firstKey = params.keySet().iterator().next();
        throw new ImageReadException("Unknown parameter: " + firstKey);
    }

    final IcnsContents contents = readImage(byteSource);
    final List<BufferedImage> images = IcnsDecoder.decodeAllImages(contents.icnsElements);
    if (images.isEmpty()) {
        throw new ImageReadException("No icons in ICNS file");
    }
    final BufferedImage image0 = images.get(0);
    return new Dimension(image0.getWidth(), image0.getHeight());
}
 
Example #13
Source File: JpegImageParser.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
public TiffImageMetadata getExifMetadata(final ByteSource byteSource, Map<String, Object> params)
        throws ImageReadException, IOException {
    final byte[] bytes = getExifRawData(byteSource);
    if (null == bytes) {
        return null;
    }

    if (params == null) {
        params = new HashMap<>();
    }
    if (!params.containsKey(PARAM_KEY_READ_THUMBNAILS)) {
        params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.TRUE);
    }

    return (TiffImageMetadata) new TiffImageParser().getMetadata(bytes,
            params);
}
 
Example #14
Source File: RgbeImageParser.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
@Override
public BufferedImage getBufferedImage(final ByteSource byteSource, final Map<String, Object> params)
        throws ImageReadException, IOException {
    try (RgbeInfo info = new RgbeInfo(byteSource)) {
        // It is necessary to create our own BufferedImage here as the
        // org.apache.commons.imaging.common.IBufferedImageFactory interface does
        // not expose this complexity
        final DataBuffer buffer = new DataBufferFloat(info.getPixelData(),
                info.getWidth() * info.getHeight());

        final BufferedImage ret = new BufferedImage(new ComponentColorModel(
                ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false,
                Transparency.OPAQUE, buffer.getDataType()),
                Raster.createWritableRaster(
                        new BandedSampleModel(buffer.getDataType(),
                                info.getWidth(), info.getHeight(), 3),
                        buffer,
                        new Point()), false, null);
        return ret;
    }
}
 
Example #15
Source File: ScanlineFilterAverageTest.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnfilterWithNull() throws IOException, ImageReadException {
    final ScanlineFilterAverage scanlineFilterAverage = new ScanlineFilterAverage(2);
    final byte[] byteArray = new byte[9];
    scanlineFilterAverage.unfilter(byteArray, byteArray, null);

    assertArrayEquals(new byte[] {(byte)0, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0}, byteArray);
}
 
Example #16
Source File: PngImageParser.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
@Override
public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource)
        throws ImageReadException, IOException {
    final ImageInfo imageInfo = getImageInfo(byteSource);
    if (imageInfo == null) {
        return false;
    }

    imageInfo.toString(pw, "");

    final List<PngChunk> chunks = readChunks(byteSource, null, false);
    final List<PngChunk> IHDRs = filterChunks(chunks, ChunkType.IHDR);
    if (IHDRs.size() != 1) {
        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.finest("PNG contains more than one Header");
        }
        return false;
    }
    final PngChunkIhdr pngChunkIHDR = (PngChunkIhdr) IHDRs.get(0);
    pw.println("Color: " + pngChunkIHDR.pngColorType.name());

    pw.println("chunks: " + chunks.size());

    if ((chunks.isEmpty())) {
        return false;
    }

    for (int i = 0; i < chunks.size(); i++) {
        final PngChunk chunk = chunks.get(i);
        printCharQuad(pw, "\t" + i + ": ", chunk.chunkType);
    }

    pw.println("");

    pw.flush();

    return true;
}
 
Example #17
Source File: TiffReader.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
private ByteOrder getTiffByteOrder(final int byteOrderByte) throws ImageReadException {
    if (byteOrderByte == 'I') {
        return ByteOrder.LITTLE_ENDIAN; // Intel
    } else if (byteOrderByte == 'M') {
        return ByteOrder.BIG_ENDIAN; // Motorola
    } else {
        throw new ImageReadException("Invalid TIFF byte order " + (0xff & byteOrderByte));
    }
}
 
Example #18
Source File: ImageReadExample.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
public static BufferedImage imageReadExample(final File file)
        throws ImageReadException, IOException {
    final Map<String, Object> params = new HashMap<>();

    // set optional parameters if you like
    params.put(ImagingConstants.BUFFERED_IMAGE_FACTORY,
            new ManagedImageBufferedImageFactory());

    // params.put(ImagingConstants.PARAM_KEY_VERBOSE, Boolean.TRUE);

    // read image
    final BufferedImage image = Imaging.getBufferedImage(file, params);

    return image;
}
 
Example #19
Source File: RoundtripBase.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
protected void roundtrip(final FormatInfo formatInfo, final BufferedImage testImage,
                         final String tempPrefix, final boolean imageExact) throws IOException,
        ImageReadException, ImageWriteException {
    final File temp1 = File.createTempFile(tempPrefix + ".", "."
            + formatInfo.format.getExtension());
    Debug.debug("tempFile: " + temp1.getName());

    final Map<String, Object> params = new HashMap<>();
    Imaging.writeImage(testImage, temp1, formatInfo.format, params);

    final Map<String, Object> readParams = new HashMap<>();
    readParams.put(ImagingConstants.BUFFERED_IMAGE_FACTORY,
            new RgbBufferedImageFactory());
    final BufferedImage image2 = Imaging.getBufferedImage(temp1, readParams);
    assertNotNull(image2);

    if (imageExact) {
        // note tolerance when comparing grayscale images
        // BufferedImages of
        ImageAsserts.assertEquals(testImage, image2);
    }

    if (formatInfo.identicalSecondWrite) {
        final File temp2 = File.createTempFile(tempPrefix + ".", "."
                + formatInfo.format.getExtension());
        // Debug.debug("tempFile: " + tempFile.getName());
        Imaging.writeImage(image2, temp2, formatInfo.format, params);

        ImageAsserts.assertEquals(temp1, temp2);
    }
}
 
Example #20
Source File: JpegImageParser.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
@Override
public ImageMetadata getMetadata(final ByteSource byteSource, final Map<String, Object> params)
        throws ImageReadException, IOException {
    final TiffImageMetadata exif = getExifMetadata(byteSource, params);

    final JpegPhotoshopMetadata photoshop = getPhotoshopMetadata(byteSource,
            params);

    if (null == exif && null == photoshop) {
        return null;
    }

    return new JpegImageMetadata(photoshop, exif);
}
 
Example #21
Source File: RgbeImageParser.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
@Override
public Dimension getImageSize(final ByteSource byteSource, final Map<String, Object> params)
        throws ImageReadException, IOException {
    try (RgbeInfo info = new RgbeInfo(byteSource)) {
        final Dimension ret = new Dimension(info.getWidth(), info.getHeight());
        return ret;
    }
}
 
Example #22
Source File: TiffImageMetadata.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
public double getLatitudeAsDegreesNorth() throws ImageReadException {
    final double result = latitudeDegrees.doubleValue()
            + (latitudeMinutes.doubleValue() / 60.0)
            + (latitudeSeconds.doubleValue() / 3600.0);

    if (latitudeRef.trim().equalsIgnoreCase("n")) {
        return result;
    } else if (latitudeRef.trim().equalsIgnoreCase("s")) {
        return -result;
    } else {
        throw new ImageReadException("Unknown latitude ref: \""
                + latitudeRef + "\"");
    }
}
 
Example #23
Source File: ExifRewriter.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a Jpeg image, replaces the EXIF metadata and writes the result to a
 * stream.
 *
 * <p>Note that this uses the "Lossless" approach - in order to preserve data
 * embedded in the EXIF segment that it can't parse (such as Maker Notes),
 * this algorithm avoids overwriting any part of the original segment that
 * it couldn't parse. This can cause the EXIF segment to grow with each
 * update, which is a serious issue, since all EXIF data must fit in a
 * single APP1 segment of the Jpeg image.</p>
 *
 * @param byteSource
 *            ByteSource containing Jpeg image data.
 * @param os
 *            OutputStream to write the image to.
 * @param outputSet
 *            TiffOutputSet containing the EXIF data to write.
 * @throws ImageReadException if it fails to read the JFIF segments
 * @throws IOException if it fails to read the image data
 * @throws ImageWriteException if it fails to write the updated data
 */
public void updateExifMetadataLossless(final ByteSource byteSource,
        final OutputStream os, final TiffOutputSet outputSet)
        throws ImageReadException, IOException, ImageWriteException {
    // List outputDirectories = outputSet.getDirectories();
    final JFIFPieces jfifPieces = analyzeJFIF(byteSource);
    final List<JFIFPiece> pieces = jfifPieces.pieces;

    TiffImageWriterBase writer;
    // Just use first APP1 segment for now.
    // Multiple APP1 segments are rare and poorly supported.
    if (!jfifPieces.exifPieces.isEmpty()) {
        JFIFPieceSegment exifPiece = null;
        exifPiece = (JFIFPieceSegment) jfifPieces.exifPieces.get(0);

        byte[] exifBytes = exifPiece.segmentData;
        exifBytes = remainingBytes("trimmed exif bytes", exifBytes, 6);

        writer = new TiffImageWriterLossless(outputSet.byteOrder, exifBytes);

    } else {
        writer = new TiffImageWriterLossy(outputSet.byteOrder);
    }

    final boolean includeEXIFPrefix = true;
    final byte[] newBytes = writeExifSegment(writer, outputSet, includeEXIFPrefix);

    writeSegmentsReplacingExif(os, pieces, newBytes);
}
 
Example #24
Source File: ScanlineFilterPaethTest.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnfilter() throws IOException, ImageReadException {
    final ScanlineFilterPaeth scanlineFilterPaeth = new ScanlineFilterPaeth(0);
    final byte[] byteArray = new byte[5];
    scanlineFilterPaeth.unfilter(byteArray, byteArray, null);

    assertArrayEquals(new byte[] {(byte)0, (byte)0, (byte)0, (byte)0, (byte)0}, byteArray);
}
 
Example #25
Source File: PsdImageParser.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
private PsdHeaderInfo readHeader(final ByteSource byteSource)
        throws ImageReadException, IOException {
    try (InputStream is = byteSource.getInputStream()) {
        final PsdHeaderInfo ret = readHeader(is);
        return ret;
    }
}
 
Example #26
Source File: JpegImageParser.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getICCProfileBytes(final ByteSource byteSource, final Map<String, Object> params)
        throws ImageReadException, IOException {
    final List<Segment> segments = readSegments(byteSource,
            new int[] { JpegConstants.JPEG_APP2_MARKER, }, false);

    final List<App2Segment> filtered = new ArrayList<>();
    if (segments != null) {
        // throw away non-icc profile app2 segments.
        for (final Segment s : segments) {
            final App2Segment segment = (App2Segment) s;
            if (segment.getIccBytes() != null) {
                filtered.add(segment);
            }
        }
    }

    if (filtered.isEmpty()) {
        return null;
    }

    final byte[] bytes = assembleSegments(filtered);

    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.finest("bytes" + ": " + bytes.length);
    }

    return bytes;
}
 
Example #27
Source File: IcnsDecoder.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
private static void apply1BPPMask(final byte[] maskData, final ImageBuilder image) throws ImageReadException {
    int position = 0;
    int bitsLeft = 0;
    int value = 0;

    // 1 bit icon types have image data followed by mask data in the same
    // entry
    final int totalBytes = (image.getWidth() * image.getHeight() + 7) / 8;
    if (maskData.length >= 2 * totalBytes) {
        position = totalBytes;
    } else {
        throw new ImageReadException("1 BPP mask underrun parsing ICNS file");
    }

    for (int y = 0; y < image.getHeight(); y++) {
        for (int x = 0; x < image.getWidth(); x++) {
            if (bitsLeft == 0) {
                value = 0xff & maskData[position++];
                bitsLeft = 8;
            }
            int alpha;
            if ((value & 0x80) != 0) {
                alpha = 0xff;
            } else {
                alpha = 0x00;
            }
            value <<= 1;
            bitsLeft--;
            image.setRGB(x, y, (alpha << 24) | (0xffffff & image.getRGB(x, y)));
        }
    }
}
 
Example #28
Source File: TiffImageMetadata.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
public double[] getFieldValue(final TagInfoDoubles tag) throws ImageReadException {
    final TiffField field = findField(tag);
    if (field == null) {
        return null;
    }
    if (!tag.dataTypes.contains(field.getFieldType())) {
        return null;
    }
    final byte[] bytes = field.getByteArrayValue();
    return tag.getValue(field.getByteOrder(), bytes);
}
 
Example #29
Source File: JfifSegment.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
public JfifSegment(final int marker, final int markerLength, final InputStream is)
        throws ImageReadException, IOException {
    super(marker, markerLength);

    final byte[] signature = readBytes(is, JpegConstants.JFIF0_SIGNATURE.size());
    if (!JpegConstants.JFIF0_SIGNATURE.equals(signature)
            && !JpegConstants.JFIF0_SIGNATURE_ALTERNATIVE.equals(signature)) {
        throw new ImageReadException(
                "Not a Valid JPEG File: missing JFIF string");
    }

    jfifMajorVersion = readByte("JFIF_major_version", is,
            "Not a Valid JPEG File");
    jfifMinorVersion = readByte("JFIF_minor_version", is,
            "Not a Valid JPEG File");
    densityUnits = readByte("density_units", is, "Not a Valid JPEG File");
    xDensity = read2Bytes("x_density", is, "Not a Valid JPEG File", getByteOrder());
    yDensity = read2Bytes("y_density", is, "Not a Valid JPEG File", getByteOrder());

    xThumbnail = readByte("x_thumbnail", is, "Not a Valid JPEG File");
    yThumbnail = readByte("y_thumbnail", is, "Not a Valid JPEG File");
    thumbnailSize = xThumbnail * yThumbnail;
    if (thumbnailSize > 0) {
        skipBytes(is, thumbnailSize,
                "Not a Valid JPEG File: missing thumbnail");

    }
}
 
Example #30
Source File: BmpRoundtripTest.java    From commons-imaging with Apache License 2.0 5 votes vote down vote up
private void writeAndReadImageData(final int[][] rawData) throws IOException,
        ImageReadException, ImageWriteException {
    final BufferedImage srcImage = imageDataToBufferedImage(rawData);

    final Map<String, Object> writeParams = new HashMap<>();
    // writeParams.put(ImagingConstants.PARAM_KEY_FORMAT,
    // ImageFormat.IMAGE_FORMAT_BMP);
    // writeParams.put(PngConstants.PARAM_KEY_BMP_FORCE_TRUE_COLOR,
    // Boolean.TRUE);

    final byte[] bytes = Imaging.writeImageToBytes(srcImage,
            ImageFormats.BMP, writeParams);

    // Debug.debug("bytes", bytes);

    final File tempFile = File.createTempFile("temp", ".bmp");
    FileUtils.writeByteArrayToFile(tempFile, bytes);

    final BufferedImage dstImage = Imaging.getBufferedImage(bytes);

    assertNotNull(dstImage);
    assertTrue(srcImage.getWidth() == dstImage.getWidth());
    assertTrue(srcImage.getHeight() == dstImage.getHeight());

    final int dstData[][] = bufferedImageToImageData(dstImage);
    compare(rawData, dstData);
}