Java Examples for javax.imageio.IIOException

The following java examples will help you to understand the usage of javax.imageio.IIOException. These source code samples are taken from different open source projects.

Example 1
Project: imic-master  File: JpegReader.java View source code
public BufferedImage readImage(InputStream imageData) throws IOException {
    ImageInputStream stream = ImageIO.createImageInputStream(imageData);
    for (Iterator<ImageReader> iterator = ImageIO.getImageReaders(stream); iterator.hasNext(); ) {
        ImageReader imageReader = iterator.next();
        imageReader.setInput(stream);
        try {
            BufferedImage image = imageReader.read(0);
            stream.close();
            return image;
        } catch (IIOException e) {
            LOGGER.error("Reading stream failed, attempting to read with next JPEG reader.", e);
        }
    }
    return null;
}
Example 2
Project: GeDBIT-master  File: WholeFileRecordReader.java View source code
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    if (key == null) {
        key = new Text();
    }
    if (value == null) {
        value = new BytesWritable();
    }
    if (!processed) {
        byte[] content = new byte[(int) fileSplit.getLength()];
        Path file = fileSplit.getPath();
        System.out.println(file.getName());
        key.set(file.getName());
        try {
            IOUtils.readFully(fis, content, 0, content.length);
            value.set(new BytesWritable(content));
        } catch (IIOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeStream(fis);
        }
        processed = true;
        return true;
    }
    return false;
}
Example 3
Project: similarImage-master  File: ImageHashJob.java View source code
@Override
public void run() {
    try {
        long hash = processFile(image);
        if (hashAttribute != null) {
            hashAttribute.writeHash(image, hash);
        }
    } catch (IIOException e) {
        LOGGER.warn("Failed to process image {} (IIO Error): {}", image, e.toString());
        LOGGER.debug(EXCEPTION_STACKTRACE, image, e);
        statistics.incrementFailedFiles();
    } catch (IOException e) {
        LOGGER.warn("Failed to load file {}: {}", image, e.toString());
        statistics.incrementFailedFiles();
    } catch (RepositoryException e) {
        LOGGER.warn("Failed to query repository for {}: {}", image, e.toString());
        statistics.incrementFailedFiles();
    } catch (ArrayIndexOutOfBoundsException e) {
        LOGGER.error("Failed to process image {}: {}", image, e.toString());
        LOGGER.debug(EXCEPTION_STACKTRACE, image, e);
        statistics.incrementFailedFiles();
    }
}
Example 4
Project: ios-driver-master  File: ResourceServlet.java View source code
private boolean validImage(File f) throws IOException {
    InputStream is = new FileInputStream(f);
    try {
        //is = new FileInputStream(f);
        final ImageInputStream imageInputStream = ImageIO.createImageInputStream(is);
        final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
        if (!imageReaders.hasNext()) {
            // not an image
            return false;
        }
        final ImageReader imageReader = imageReaders.next();
        imageReader.setInput(imageInputStream);
        final BufferedImage image = imageReader.read(0);
        if (image == null) {
            // empty
            return false;
        }
        image.flush();
        return true;
    } catch (final IndexOutOfBoundsException e) {
        return false;
    } catch (final IIOException e) {
        if (e.getCause() instanceof EOFException) {
            return false;
        }
    } catch (Exception e) {
        return false;
    } finally {
        is.close();
    }
    return true;
}
Example 5
Project: plantuml-server-master  File: ProxyServlet.java View source code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    final String fmt = request.getParameter("fmt");
    final String source = request.getParameter("src");
    final String index = request.getParameter("idx");
    final URL srcUrl;
    // Check if the src URL is valid
    try {
        srcUrl = new URL(source);
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
        return;
    }
    // generate the response
    String diagmarkup = getSource(srcUrl);
    SourceStringReader reader = new SourceStringReader(diagmarkup);
    int n = index == null ? 0 : Integer.parseInt(index);
    List<BlockUml> blocks = reader.getBlocks();
    BlockUml block = blocks.get(n);
    Diagram diagram = block.getDiagram();
    UmlSource umlSrc = diagram.getSource();
    String uml = umlSrc.getPlainString();
    //System.out.println("uml=" + uml);
    // generate the response
    DiagramResponse dr = new DiagramResponse(response, getOutputFormat(fmt), request);
    try {
        dr.sendDiagram(uml, 0);
    } catch (IIOException iioe) {
    }
    dr = null;
}
Example 6
Project: Weasis-master  File: SeriesBuilder.java View source code
private static double writeBlock(RawImage[] newSeries, MediaSeries<DicomImageElement> series, Iterable<DicomImageElement> medias, ViewParameter params, final MprView view, Thread thread, final boolean[] abort, String seriesID) throws IOException {
    // TODO should return the more frequent space!
    final JProgressBar bar = view.getProgressBar();
    try {
        File dir = new File(MPR_CACHE_DIR, params.seriesUID);
        dir.mkdirs();
        for (int i = 0; i < newSeries.length; i++) {
            //$NON-NLS-1$
            newSeries[i] = new RawImage(new File(dir, "mpr_" + (i + 1)));
        }
        double epsilon = 1e-3;
        double lastPos = 0.0;
        double lastSpace = 0.0;
        int index = 0;
        Iterator<DicomImageElement> iter = medias.iterator();
        while (iter.hasNext()) {
            if (thread.isInterrupted()) {
                return lastSpace;
            }
            DicomImageElement dcm = iter.next();
            double[] sp = (double[]) dcm.getTagValue(TagW.SlicePosition);
            if (sp == null && !abort[1]) {
                //$NON-NLS-1$
                confirmMessage(view, Messages.getString("SeriesBuilder.space_missing"), abort);
            } else {
                double pos = sp[0] + sp[1] + sp[2];
                if (index > 0) {
                    double space = Math.abs(pos - lastPos);
                    if (!abort[1] && (MathUtil.isEqualToZero(space) || (index > 1 && lastSpace - space > epsilon))) {
                        //$NON-NLS-1$
                        confirmMessage(view, Messages.getString("SeriesBuilder.space"), abort);
                    }
                    lastSpace = space;
                }
                lastPos = pos;
                index++;
                if (bar != null) {
                    GuiExecutor.instance().execute(() -> {
                        bar.setValue(bar.getValue() + 1);
                        view.repaint();
                    });
                }
            }
            // TODO do not open more than 512 files (Limitation to open 1024 in the same time on Ubuntu)
            PlanarImage image = dcm.getImage();
            if (image == null) {
                abort[0] = true;
                //$NON-NLS-1$
                throw new IIOException("Cannot read an image!");
            }
            if (MathUtil.isDifferent(dcm.getRescaleX(), dcm.getRescaleY())) {
                ParameterBlock pb = new ParameterBlock();
                pb.addSource(image);
                pb.add((float) dcm.getRescaleX()).add((float) dcm.getRescaleY()).add(0.0f).add(0.0f);
                pb.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR));
                //$NON-NLS-1$
                image = JAI.create("scale", pb, ImageToolkit.NOCACHE_HINT);
            }
            writeRasterInRaw(getImage(image, params.transposeImage), newSeries);
        }
        return lastSpace;
    } finally {
        for (int i = 0; i < newSeries.length; i++) {
            if (newSeries[i] != null) {
                newSeries[i].disposeOutputStream();
                if (abort[0]) {
                    newSeries[i].getFile().delete();
                }
            }
        }
    }
}
Example 7
Project: ewcms-master  File: ImageUtil.java View source code
/**
	 * 图象压缩 
	 * 
	 * @param sourcePath æº?文件å??
	 * @param targetPath 目标文件å??
	 * @param width 压缩宽度
	 * @param hight 压缩高度
	 * @return 压缩是��功
	 */
public static Boolean compression(String sourcePath, String targetPath, int width, int hight) {
    try {
        File sourceFile = new File(sourcePath);
        File targetFile = new File(targetPath);
        String format = getFormatName(new File(sourcePath));
        logger.info("Image Format is {}", format);
        BufferedImage srcImage = ImageIO.read(sourceFile);
        if (width > 0 || hight > 0) {
            srcImage = resize(srcImage, width, hight);
        }
        ImageIO.write(srcImage, format, targetFile);
    } catch (IIOException e) {
        logger.error("Image IIOException:{}", e);
        return false;
    } catch (IOException e) {
        logger.error("Image file IOException:{}", e);
        return false;
    }
    return true;
}
Example 8
Project: openjdk-master  File: TIFFImageWriter.java View source code
public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) {
    // Check arguments.
    if (inData == null) {
        throw new NullPointerException("inData == null!");
    }
    if (imageType == null) {
        throw new NullPointerException("imageType == null!");
    }
    TIFFImageMetadata outData = null;
    // Obtain a TIFFImageMetadata object.
    if (inData instanceof TIFFImageMetadata) {
        // Create a new metadata object from a clone of the input IFD.
        TIFFIFD inIFD = ((TIFFImageMetadata) inData).getRootIFD();
        outData = new TIFFImageMetadata(inIFD.getShallowClone());
    } else if (Arrays.asList(inData.getMetadataFormatNames()).contains(TIFFImageMetadata.NATIVE_METADATA_FORMAT_NAME)) {
        // Initialize from the native metadata form of the input tree.
        try {
            outData = convertNativeImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
            return null;
        }
    } else if (inData.isStandardMetadataFormatSupported()) {
        // Initialize from the standard metadata form of the input tree.
        try {
            outData = convertStandardImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
            return null;
        }
    }
    // Update the metadata per the image type and param.
    if (outData != null) {
        TIFFImageWriter bogusWriter = new TIFFImageWriter(this.originatingProvider);
        bogusWriter.imageMetadata = outData;
        bogusWriter.param = param;
        SampleModel sm = imageType.getSampleModel();
        try {
            bogusWriter.setupMetadata(imageType.getColorModel(), sm, sm.getWidth(), sm.getHeight());
            return bogusWriter.imageMetadata;
        } catch (IIOException e) {
            return null;
        }
    }
    return outData;
}
Example 9
Project: PSD-master  File: PSDImageReader.java View source code
private ImageTypeSpecifier getRawImageTypeForCompositeLayer() throws IOException {
    ColorSpace cs;
    switch(header.mode) {
        case PSD.COLOR_MODE_BITMAP:
            if (header.channels == 1 && header.bits == 1) {
                return ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for Monochrome PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_INDEXED:
            if (header.channels == 1 && header.bits == 8) {
                return ImageTypeSpecifiers.createFromIndexColorModel(metadata.colorData.getIndexColorModel());
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for Indexed Color PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_DUOTONE:
        // Fall-through
        case PSD.COLOR_MODE_GRAYSCALE:
            cs = getEmbeddedColorSpace();
            if (cs == null) {
                cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            }
            if (header.channels == 1 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0 }, new int[] { 0 }, DataBuffer.TYPE_BYTE, false, false);
            } else if (header.channels == 2 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, DataBuffer.TYPE_BYTE, true, false);
            } else if (header.channels == 1 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0 }, new int[] { 0 }, DataBuffer.TYPE_USHORT, false, false);
            } else if (header.channels == 2 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, DataBuffer.TYPE_USHORT, true, false);
            } else if (header.channels == 1 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0 }, new int[] { 0 }, DataBuffer.TYPE_INT, false, false);
            } else if (header.channels == 2 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, DataBuffer.TYPE_INT, true, false);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for Gray Scale PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_RGB:
            cs = getEmbeddedColorSpace();
            if (cs == null) {
                cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
            }
            if (header.channels == 3 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, DataBuffer.TYPE_BYTE, false, false);
            } else if (header.channels >= 4 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_BYTE, true, false);
            } else if (header.channels == 3 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, DataBuffer.TYPE_USHORT, false, false);
            } else if (header.channels >= 4 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_USHORT, true, false);
            } else if (header.channels == 3 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, DataBuffer.TYPE_INT, false, false);
            } else if (header.channels >= 4 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_INT, true, false);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for RGB PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_CMYK:
            cs = getEmbeddedColorSpace();
            if (cs == null) {
                cs = ColorSpaces.getColorSpace(ColorSpaces.CS_GENERIC_CMYK);
            }
            if (header.channels == 4 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_BYTE, false, false);
            } else if (header.channels == 5 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, DataBuffer.TYPE_BYTE, true, false);
            } else if (header.channels == 4 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_USHORT, false, false);
            } else if (header.channels == 5 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, DataBuffer.TYPE_USHORT, true, false);
            } else if (header.channels == 4 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_INT, false, false);
            } else if (header.channels == 5 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, DataBuffer.TYPE_INT, true, false);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for CMYK PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_MULTICHANNEL:
        // TODO: Implement
        case PSD.COLOR_MODE_LAB:
        // TODO: See the LAB color handling in TIFF
        default:
            throw new IIOException(String.format("Unsupported PSD MODE: %s (%d channels/%d bits)", header.mode, header.channels, header.bits));
    }
}
Example 10
Project: softwarecave-master  File: Main.java View source code
private void createTempFileWithDirOldWay() throws IOException {
    File tempDir = new File(System.getProperty("java.io.tmpdir", null), "tempdir-old");
    if (!tempDir.exists() && !tempDir.mkdir()) {
        throw new IIOException("Failed to create temporary directory " + tempDir);
    }
    File tempFile = File.createTempFile("tempfile-old", ".tmp", tempDir);
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(new FileWriter(tempFile));
        writer.println("Line1");
        writer.println("Line2");
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
    System.out.printf("Wrote text to temporary file %s%n", tempFile.toString());
}
Example 11
Project: TwelveMonkeys-master  File: PSDImageReader.java View source code
private ImageTypeSpecifier getRawImageTypeForCompositeLayer() throws IOException {
    ColorSpace cs;
    switch(header.mode) {
        case PSD.COLOR_MODE_BITMAP:
            if (header.channels == 1 && header.bits == 1) {
                return ImageTypeSpecifiers.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for Monochrome PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_INDEXED:
            if (header.channels == 1 && header.bits == 8) {
                return ImageTypeSpecifiers.createFromIndexColorModel(metadata.colorData.getIndexColorModel());
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for Indexed Color PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_DUOTONE:
        // Fall-through
        case PSD.COLOR_MODE_GRAYSCALE:
            cs = getEmbeddedColorSpace();
            if (cs == null) {
                cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            }
            if (header.channels == 1 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0 }, new int[] { 0 }, DataBuffer.TYPE_BYTE, false, false);
            } else if (header.channels == 2 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, DataBuffer.TYPE_BYTE, true, false);
            } else if (header.channels == 1 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0 }, new int[] { 0 }, DataBuffer.TYPE_USHORT, false, false);
            } else if (header.channels == 2 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, DataBuffer.TYPE_USHORT, true, false);
            } else if (header.channels == 1 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0 }, new int[] { 0 }, DataBuffer.TYPE_INT, false, false);
            } else if (header.channels == 2 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1 }, new int[] { 0, 0 }, DataBuffer.TYPE_INT, true, false);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for Gray Scale PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_RGB:
            cs = getEmbeddedColorSpace();
            if (cs == null) {
                cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
            }
            if (header.channels == 3 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, DataBuffer.TYPE_BYTE, false, false);
            } else if (header.channels >= 4 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_BYTE, true, false);
            } else if (header.channels == 3 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, DataBuffer.TYPE_USHORT, false, false);
            } else if (header.channels >= 4 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_USHORT, true, false);
            } else if (header.channels == 3 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2 }, new int[] { 0, 0, 0 }, DataBuffer.TYPE_INT, false, false);
            } else if (header.channels >= 4 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_INT, true, false);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for RGB PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_CMYK:
            cs = getEmbeddedColorSpace();
            if (cs == null) {
                cs = ColorSpaces.getColorSpace(ColorSpaces.CS_GENERIC_CMYK);
            }
            if (header.channels == 4 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_BYTE, false, false);
            } else if (header.channels == 5 && header.bits == 8) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, DataBuffer.TYPE_BYTE, true, false);
            } else if (header.channels == 4 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_USHORT, false, false);
            } else if (header.channels == 5 && header.bits == 16) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, DataBuffer.TYPE_USHORT, true, false);
            } else if (header.channels == 4 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3 }, new int[] { 0, 0, 0, 0 }, DataBuffer.TYPE_INT, false, false);
            } else if (header.channels == 5 && header.bits == 32) {
                return ImageTypeSpecifiers.createBanded(cs, new int[] { 0, 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0, 0 }, DataBuffer.TYPE_INT, true, false);
            }
            throw new IIOException(String.format("Unsupported channel count/bit depth for CMYK PSD: %d channels/%d bits", header.channels, header.bits));
        case PSD.COLOR_MODE_MULTICHANNEL:
        // TODO: Implement
        case PSD.COLOR_MODE_LAB:
        // TODO: See the LAB color handling in TIFF
        default:
            throw new IIOException(String.format("Unsupported PSD MODE: %s (%d channels/%d bits)", header.mode, header.channels, header.bits));
    }
}
Example 12
Project: twist-master  File: Starter.java View source code
public void init(ArrayList<Item> suite, ArrayList<Item> suitetest, Hashtable<String, String> variables, final Document pluginsConfig, Applet container) {
    RunnerRepository.starter = this;
    URL url = null;
    try {
        url = new URL(container.getCodeBase() + "/logo.png");
        RunnerRepository.logo = ImageIO.read(url).getScaledInstance(230, 100, Image.SCALE_FAST);
    } catch (IIOException e) {
        System.out.println("Could not get image: " + url.toExternalForm());
    } catch (Exception e) {
        e.printStackTrace();
    }
    readLogoTxt(container);
    PermissionValidator.init(variables.get("permissions"));
    RunnerRepository.user = variables.get("user");
    RunnerRepository.password = variables.get("password");
    RunnerRepository.host = variables.get("host");
    RunnerRepository.CENTRALENGINEPORT = variables.get("centralengineport");
    container.removeAll();
    container.revalidate();
    container.repaint();
    RunnerRepository.initialize("true", variables.get("host"), container, container);
    resizePlugin((int) container.getSize().getWidth(), (int) container.getSize().getHeight());
}
Example 13
Project: QuiltPlayer-master  File: WebServiceAlbum.java View source code
/**
     * @param file
     * @param image
     */
private void checkIfImageExists(Album album, File file, String uri) throws MalformedURLException, IOException {
    if (!file.exists()) {
        try {
            log.debug("Image file in album " + album + " does not exist, downloading...");
            URL imageUrl = new URL(uri);
            BufferedImage i = ImageIO.read(imageUrl);
            ImageIO.write(i, "jpg", file);
        } catch (javax.imageio.IIOException e) {
            log.debug("Image file does not exist on discogs!");
            return;
        }
    } else {
        log.debug("Image file " + file.getName() + " already exist.");
    }
}
Example 14
Project: acs-aem-commons-master  File: AbstractRenditionModifyingProcess.java View source code
public final void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap metaData, WorkflowHelper workflowHelper) throws WorkflowException {
    String[] args = workflowHelper.buildArguments(metaData);
    final String renditionName = workflowHelper.getValuesFromArgs(ARG_RENDITION_NAME, args).size() > 0 ? workflowHelper.getValuesFromArgs(ARG_RENDITION_NAME, args).get(0) : null;
    // image quality: from 0 t0 100%
    final String qualityStr = workflowHelper.getValuesFromArgs(ARG_QUALITY, args).size() > 0 ? workflowHelper.getValuesFromArgs(ARG_QUALITY, args).get(0) : DEFAULT_QUALITY;
    if (renditionName == null) {
        log.warn("Rendition name was not configured in arguments. Skipping.");
        return;
    }
    final WorkflowHelper.AssetResourceResolverPair pair = workflowHelper.getAssetFromPayload(workItem, workflowSession);
    if (pair == null) {
        return;
    }
    final Rendition rendition = pair.asset.getRendition(new PrefixRenditionPicker(renditionName));
    if (rendition == null) {
        log.warn("Rendition name {} was not available for asset {}. Skipping.", renditionName, pair.asset);
        return;
    }
    Layer layer = null;
    try {
        layer = new Layer(rendition.getStream());
        layer = processLayer(layer, rendition, workflowSession, args);
        String mimetype = layer.getMimeType();
        double quality = mimetype.equals("image/gif") ? workflowHelper.getQuality(MAX_GIF_QUALITY, qualityStr) : workflowHelper.getQuality(1.0, qualityStr);
        saveImage(pair.asset, rendition, layer, mimetype, quality, workflowHelper);
    } catch (IIOException e) {
        log.warn("Unable to load image layer from " + rendition.getPath(), e);
    } catch (IOException e) {
        log.warn("Unable to load image layer from " + rendition.getPath(), e);
    } finally {
        if (layer != null) {
            layer.dispose();
            layer = null;
        }
        pair.resourceResolver.close();
    }
}
Example 15
Project: Density-master  File: ImageUtil.java View source code
public static LoadedImage loadImage(File input) throws Exception {
    if (input == null) {
        throw new IllegalArgumentException("input == null!");
    }
    if (!input.canRead()) {
        throw new IIOException("Can't read input file!");
    }
    ImageInputStream stream = ImageIO.createImageInputStream(input);
    if (stream == null) {
        throw new IIOException("Can't create an ImageInputStream!");
    }
    LoadedImage image = read(stream, Arguments.getImageType(input));
    if (image.getImage() == null) {
        stream.close();
    }
    return new LoadedImage(input, image.getImage(), image.getMetadata(), readExif(input));
}
Example 16
Project: ikvm-monotouch-master  File: JPEGImageWriter.java View source code
/**
     * {@inheritDoc}
     */
@Override
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    ImageCodecInfo codec = null;
    for (ImageCodecInfo ici : ImageCodecInfo.GetImageEncoders()) {
        if (ici.get_FormatID().equals(ImageFormat.get_Jpeg().get_Guid()) && (ici.get_Flags().Value & ImageCodecFlags.Builtin) != 0) {
            codec = ici;
            break;
        }
    }
    if (codec == null) {
        throw new IIOException("JPEG codec not found");
    }
    BufferedImage img = (BufferedImage) image.getRenderedImage();
    cli.System.Drawing.Bitmap bitmap = img.getBitmap();
    ImageOutputStream imgOutput = (ImageOutputStream) getOutput();
    JPEGImageWriteParam jparam = null;
    JPEGQTable[] qTables = null;
    if (param != null) {
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
        }
    }
    if (qTables == null) {
        if (jparam != null && jparam.areTablesSet()) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // Create a MemoryStream with publicly visible buffer
    cli.System.IO.MemoryStream stream = new cli.System.IO.MemoryStream(1024);
    EncoderParameters params = new EncoderParameters(2);
    try {
        params.get_Param()[0] = new EncoderParameter(Encoder.LuminanceTable, qTableToShortArray(qTables[0]));
        params.get_Param()[1] = new EncoderParameter(Encoder.ChrominanceTable, qTableToShortArray(qTables[1]));
        bitmap.Save(stream, codec, params);
    } finally {
        params.Dispose();
    }
    imgOutput.write(stream.GetBuffer(), 0, (int) stream.get_Length());
}
Example 17
Project: IKVM.NET-cvs-clone-master  File: JPEGImageWriter.java View source code
/**
     * {@inheritDoc}
     */
@Override
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    ImageCodecInfo codec = null;
    for (ImageCodecInfo ici : ImageCodecInfo.GetImageEncoders()) {
        if (ici.get_FormatID().equals(ImageFormat.get_Jpeg().get_Guid()) && (ici.get_Flags().Value & ImageCodecFlags.Builtin) != 0) {
            codec = ici;
            break;
        }
    }
    if (codec == null) {
        throw new IIOException("JPEG codec not found");
    }
    BufferedImage img = (BufferedImage) image.getRenderedImage();
    cli.System.Drawing.Bitmap bitmap = img.getBitmap();
    ImageOutputStream imgOutput = (ImageOutputStream) getOutput();
    JPEGImageWriteParam jparam = null;
    JPEGQTable[] qTables = null;
    if (param != null) {
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
        }
    }
    if (qTables == null) {
        if (jparam != null && jparam.areTablesSet()) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // Create a MemoryStream with publicly visible buffer
    cli.System.IO.MemoryStream stream = new cli.System.IO.MemoryStream(1024);
    EncoderParameters params = new EncoderParameters(2);
    try {
        params.get_Param()[0] = new EncoderParameter(Encoder.LuminanceTable, qTableToShortArray(qTables[0]));
        params.get_Param()[1] = new EncoderParameter(Encoder.ChrominanceTable, qTableToShortArray(qTables[1]));
        bitmap.Save(stream, codec, params);
    } finally {
        params.Dispose();
    }
    imgOutput.write(stream.GetBuffer(), 0, (int) stream.get_Length());
}
Example 18
Project: jai-imageio-core-master  File: TIFFDecompressor.java View source code
/**
     * Return the number of bits occupied by <code>dataType</code>
     * which must be one of the <code>DataBuffer</code> <code>TYPE</code>s.
     */
private static int getDataTypeSize(int dataType) throws IIOException {
    int dataTypeSize = 0;
    switch(dataType) {
        case DataBuffer.TYPE_BYTE:
            dataTypeSize = 8;
            break;
        case DataBuffer.TYPE_SHORT:
        case DataBuffer.TYPE_USHORT:
            dataTypeSize = 16;
            break;
        case DataBuffer.TYPE_INT:
        case DataBuffer.TYPE_FLOAT:
            dataTypeSize = 32;
            break;
        case DataBuffer.TYPE_DOUBLE:
            dataTypeSize = 64;
            break;
        default:
            throw new IIOException("Unknown data type " + dataType);
    }
    return dataTypeSize;
}
Example 19
Project: libbio-formats-java-master  File: TIFFImageWriter.java View source code
public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) {
    // Check arguments.
    if (inData == null) {
        throw new IllegalArgumentException("inData == null!");
    }
    if (imageType == null) {
        throw new IllegalArgumentException("imageType == null!");
    }
    TIFFImageMetadata outData = null;
    // Obtain a TIFFImageMetadata object.
    if (inData instanceof TIFFImageMetadata) {
        // Create a new metadata object from a clone of the input IFD.
        TIFFIFD inIFD = ((TIFFImageMetadata) inData).getRootIFD();
        outData = new TIFFImageMetadata(inIFD.getShallowClone());
    } else if (Arrays.asList(inData.getMetadataFormatNames()).contains(TIFFImageMetadata.nativeMetadataFormatName)) {
        // Initialize from the native metadata form of the input tree.
        try {
            outData = convertNativeImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
        }
    } else if (inData.isStandardMetadataFormatSupported()) {
        // Initialize from the standard metadata form of the input tree.
        try {
            outData = convertStandardImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
        }
    }
    // Update the metadata per the image type and param.
    if (outData != null) {
        TIFFImageWriter bogusWriter = new TIFFImageWriter(this.originatingProvider);
        bogusWriter.imageMetadata = outData;
        bogusWriter.param = param;
        SampleModel sm = imageType.getSampleModel();
        try {
            bogusWriter.setupMetadata(imageType.getColorModel(), sm, sm.getWidth(), sm.getHeight());
            return bogusWriter.imageMetadata;
        } catch (IIOException e) {
            return null;
        }
    }
    return outData;
}
Example 20
Project: lorsource-master  File: ImageUtil.java View source code
public static void resizeImage(String filename, String iconname, int size) throws IOException, BadImageException {
    try {
        BufferedImage source = ImageIO.read(new File(filename));
        BufferedImage destination = Scalr.resize(source, Scalr.Mode.FIT_TO_WIDTH, size);
        ImageIO.write(destination, "JPEG", new File(iconname));
    } catch (IIOException ex) {
        throw new BadImageException("Can't resize image", ex);
    }
}
Example 21
Project: transform-swf-master  File: BufferedImagePNGEncoderIT.java View source code
@Test
public void showImage() {
    try {
        final BufferedImageEncoder encoder = new BufferedImageEncoder();
        final ImageFactory factory = new ImageFactory();
        factory.read(sourceFile);
        final ImageTag imgIn = factory.defineImage(1);
        encoder.setImage(imgIn);
        final BufferedImage imgOut = encoder.getBufferedImage();
        imgOut.flush();
        ImageIO.write(imgOut, "png", destFile);
    } catch (IIOException e) {
        if (System.getProperty("test.trace") != null) {
            e.printStackTrace();
        }
    } catch (DataFormatException e) {
        if (System.getProperty("test.trace") != null) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        if (System.getProperty("test.trace") != null) {
            e.printStackTrace();
        }
        if (!sourceFile.getName().startsWith("x")) {
            fail(sourceFile.getPath());
        }
    }
}
Example 22
Project: with-aes-master  File: PDJpeg.java View source code
/**
     * Returns an image of the JPeg, or null if JPegs are not supported. (They should be. )
     * {@inheritDoc}
     */
public BufferedImage getRGBImage() throws IOException {
    if (image != null) {
        return image;
    }
    BufferedImage bi = null;
    boolean readError = false;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    removeAllFiltersButDCT(os);
    os.close();
    byte[] img = os.toByteArray();
    PDColorSpace cs = getColorSpace();
    try {
        if (cs instanceof PDDeviceCMYK || (cs instanceof PDICCBased && cs.getNumberOfComponents() == 4)) {
            // create BufferedImage based on the converted color values
            bi = convertCMYK2RGB(readImage(img), cs);
        } else if (cs instanceof PDSeparation) {
            // create BufferedImage based on the converted color values
            bi = processTintTransformation(readImage(img), ((PDSeparation) cs).getTintTransform(), cs.getJavaColorSpace());
        } else if (cs instanceof PDDeviceN) {
            // create BufferedImage based on the converted color values
            bi = processTintTransformation(readImage(img), ((PDDeviceN) cs).getTintTransform(), cs.getJavaColorSpace());
        } else {
            ByteArrayInputStream bai = new ByteArrayInputStream(img);
            bi = ImageIO.read(bai);
        }
    } catch (IIOException exception) {
        readError = true;
    }
    // TODO : not sure if it works for all cases
    if (bi == null && readError) {
        byte[] newImage = replaceHeader(img);
        ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
        bi = ImageIO.read(bai);
    }
    // If there is a 'soft mask' image then we use that as a transparency mask.
    PDXObjectImage smask = getSMaskImage();
    if (smask != null) {
        BufferedImage smaskBI = smask.getRGBImage();
        COSArray decodeArray = smask.getDecode();
        CompositeImage compositeImage = new CompositeImage(bi, smaskBI);
        BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);
        image = rgbImage;
    } else {
        // But if there is no soft mask, use the unaltered image.
        image = bi;
    }
    return image;
}
Example 23
Project: ae-awt-master  File: JPEGImageWriter.java View source code
private void writeOnThread(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (ios == null) {
        throw new IllegalStateException("Output has not been set!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image is null!");
    }
    // if streamMetadata is not null, issue a warning
    if (streamMetadata != null) {
        warningOccurred(WARNING_STREAM_METADATA_IGNORED);
    }
    // Obtain the raster and image, if there is one
    boolean rasterOnly = image.hasRaster();
    RenderedImage rimage = null;
    if (rasterOnly) {
        srcRas = image.getRaster();
    } else {
        rimage = image.getRenderedImage();
        if (rimage instanceof BufferedImage) {
            // Use the Raster directly.
            srcRas = ((BufferedImage) rimage).getRaster();
        } else if (rimage.getNumXTiles() == 1 && rimage.getNumYTiles() == 1) {
            // Get the unique tile.
            srcRas = rimage.getTile(rimage.getMinTileX(), rimage.getMinTileY());
            // as the tile dimensions might differ.
            if (srcRas.getWidth() != rimage.getWidth() || srcRas.getHeight() != rimage.getHeight()) {
                srcRas = srcRas.createChild(srcRas.getMinX(), srcRas.getMinY(), rimage.getWidth(), rimage.getHeight(), srcRas.getMinX(), srcRas.getMinY(), null);
            }
        } else {
            // Image is tiled so get a contiguous raster by copying.
            srcRas = rimage.getData();
        }
    }
    // Now determine if we are using a band subset
    // By default, we are using all source bands
    int numSrcBands = srcRas.getNumBands();
    indexed = false;
    indexCM = null;
    ColorModel cm = null;
    ColorSpace cs = null;
    isAlphaPremultiplied = false;
    srcCM = null;
    if (!rasterOnly) {
        cm = rimage.getColorModel();
        if (cm != null) {
            cs = cm.getColorSpace();
            if (cm instanceof IndexColorModel) {
                indexed = true;
                indexCM = (IndexColorModel) cm;
                numSrcBands = cm.getNumComponents();
            }
            if (cm.isAlphaPremultiplied()) {
                isAlphaPremultiplied = true;
                srcCM = cm;
            }
        }
    }
    srcBands = JPEG.bandOffsets[numSrcBands - 1];
    int numBandsUsed = numSrcBands;
    if (param != null) {
        int[] sBands = param.getSourceBands();
        if (sBands != null) {
            if (indexed) {
                warningOccurred(WARNING_NO_BANDS_ON_INDEXED);
            } else {
                srcBands = sBands;
                numBandsUsed = srcBands.length;
                if (numBandsUsed > numSrcBands) {
                    throw new IIOException("ImageWriteParam specifies too many source bands");
                }
            }
        }
    }
    boolean usingBandSubset = (numBandsUsed != numSrcBands);
    boolean fullImage = ((!rasterOnly) && (!usingBandSubset));
    int[] bandSizes = null;
    if (!indexed) {
        bandSizes = srcRas.getSampleModel().getSampleSize();
        // If this is a subset, we must adjust bandSizes
        if (usingBandSubset) {
            int[] temp = new int[numBandsUsed];
            for (int i = 0; i < numBandsUsed; i++) {
                temp[i] = bandSizes[srcBands[i]];
            }
            bandSizes = temp;
        }
    } else {
        int[] tempSize = srcRas.getSampleModel().getSampleSize();
        bandSizes = new int[numSrcBands];
        for (int i = 0; i < numSrcBands; i++) {
            // All the same
            bandSizes[i] = tempSize[0];
        }
    }
    for (int i = 0; i < bandSizes.length; i++) {
        // per sample.
        if (bandSizes[i] > 8) {
            throw new IIOException("Sample size must be <= 8");
        }
        // to 8-bit.
        if (indexed) {
            bandSizes[i] = 8;
        }
    }
    if (debug) {
        System.out.println("numSrcBands is " + numSrcBands);
        System.out.println("numBandsUsed is " + numBandsUsed);
        System.out.println("usingBandSubset is " + usingBandSubset);
        System.out.println("fullImage is " + fullImage);
        System.out.print("Band sizes:");
        for (int i = 0; i < bandSizes.length; i++) {
            System.out.print(" " + bandSizes[i]);
        }
        System.out.println();
    }
    // Destination type, if there is one
    ImageTypeSpecifier destType = null;
    if (param != null) {
        destType = param.getDestinationType();
        // Ignore dest type if we are writing a complete image
        if ((fullImage) && (destType != null)) {
            warningOccurred(WARNING_DEST_IGNORED);
            destType = null;
        }
    }
    // Examine the param
    sourceXOffset = srcRas.getMinX();
    sourceYOffset = srcRas.getMinY();
    int imageWidth = srcRas.getWidth();
    int imageHeight = srcRas.getHeight();
    sourceWidth = imageWidth;
    sourceHeight = imageHeight;
    int periodX = 1;
    int periodY = 1;
    int gridX = 0;
    int gridY = 0;
    JPEGQTable[] qTables = null;
    JPEGHuffmanTable[] DCHuffmanTables = null;
    JPEGHuffmanTable[] ACHuffmanTables = null;
    boolean optimizeHuffman = false;
    JPEGImageWriteParam jparam = null;
    int progressiveMode = ImageWriteParam.MODE_DISABLED;
    if (param != null) {
        Rectangle sourceRegion = param.getSourceRegion();
        if (sourceRegion != null) {
            Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
            sourceRegion = sourceRegion.intersection(imageBounds);
            sourceXOffset = sourceRegion.x;
            sourceYOffset = sourceRegion.y;
            sourceWidth = sourceRegion.width;
            sourceHeight = sourceRegion.height;
        }
        if (sourceWidth + sourceXOffset > imageWidth) {
            sourceWidth = imageWidth - sourceXOffset;
        }
        if (sourceHeight + sourceYOffset > imageHeight) {
            sourceHeight = imageHeight - sourceYOffset;
        }
        periodX = param.getSourceXSubsampling();
        periodY = param.getSourceYSubsampling();
        gridX = param.getSubsamplingXOffset();
        gridY = param.getSubsamplingYOffset();
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        progressiveMode = param.getProgressiveMode();
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
            optimizeHuffman = jparam.getOptimizeHuffmanTables();
        }
    }
    // Now examine the metadata
    IIOMetadata mdata = image.getMetadata();
    if (mdata != null) {
        if (mdata instanceof JPEGMetadata) {
            metadata = (JPEGMetadata) mdata;
            if (debug) {
                System.out.println("We have metadata, and it's JPEG metadata");
            }
        } else {
            if (!rasterOnly) {
                ImageTypeSpecifier type = destType;
                if (type == null) {
                    type = new ImageTypeSpecifier(rimage);
                }
                metadata = (JPEGMetadata) convertImageMetadata(mdata, type, param);
            } else {
                warningOccurred(WARNING_METADATA_NOT_JPEG_FOR_RASTER);
            }
        }
    }
    // First set a default state
    // If it's there, use it
    ignoreJFIF = false;
    // If it's there, use it
    ignoreAdobe = false;
    // Change if needed
    newAdobeTransform = JPEG.ADOBE_IMPOSSIBLE;
    writeDefaultJFIF = false;
    writeAdobe = false;
    // By default we'll do no conversion:
    int inCsType = JPEG.JCS_UNKNOWN;
    int outCsType = JPEG.JCS_UNKNOWN;
    JFIFMarkerSegment jfif = null;
    AdobeMarkerSegment adobe = null;
    SOFMarkerSegment sof = null;
    if (metadata != null) {
        jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        adobe = (AdobeMarkerSegment) metadata.findMarkerSegment(AdobeMarkerSegment.class, true);
        sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
    }
    // By default don't write one
    iccProfile = null;
    // PhotoYCC does this
    convertTosRGB = false;
    converted = null;
    if (destType != null) {
        if (numBandsUsed != destType.getNumBands()) {
            throw new IIOException("Number of source bands != number of destination bands");
        }
        cs = destType.getColorModel().getColorSpace();
        // Check the metadata against the destination type
        if (metadata != null) {
            checkSOFBands(sof, numBandsUsed);
            checkJFIF(jfif, destType, false);
            // Do we want to write an ICC profile?
            if ((jfif != null) && (ignoreJFIF == false)) {
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            }
            checkAdobe(adobe, destType, false);
        } else {
            // If we can add a JFIF or an Adobe marker segment, do so
            if (JPEG.isJFIFcompliant(destType, false)) {
                writeDefaultJFIF = true;
                // Do we want to write an ICC profile?
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            } else {
                int transform = JPEG.transformForType(destType, false);
                if (transform != JPEG.ADOBE_IMPOSSIBLE) {
                    writeAdobe = true;
                    newAdobeTransform = transform;
                }
            }
            // re-create the metadata
            metadata = new JPEGMetadata(destType, null, this);
        }
        inCsType = getSrcCSType(destType);
        outCsType = getDefaultDestCSType(destType);
    } else {
        // no destination type
        if (metadata == null) {
            if (fullImage) {
                // no dest, no metadata, full image
                // Use default metadata matching the image and param
                metadata = new JPEGMetadata(new ImageTypeSpecifier(rimage), param, this);
                if (metadata.findMarkerSegment(JFIFMarkerSegment.class, true) != null) {
                    cs = rimage.getColorModel().getColorSpace();
                    if (JPEG.isNonStandardICC(cs)) {
                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                    }
                }
                inCsType = getSrcCSType(rimage);
                outCsType = getDefaultDestCSType(rimage);
            }
        // else no dest, no metadata, not an image,
        // so no special headers, no color conversion
        } else {
            // no dest type, but there is metadata
            checkSOFBands(sof, numBandsUsed);
            if (fullImage) {
                // no dest, metadata, image
                // Check that the metadata and the image match
                ImageTypeSpecifier inputType = new ImageTypeSpecifier(rimage);
                inCsType = getSrcCSType(rimage);
                if (cm != null) {
                    boolean alpha = cm.hasAlpha();
                    switch(cs.getType()) {
                        case ColorSpace.TYPE_GRAY:
                            if (!alpha) {
                                outCsType = JPEG.JCS_GRAYSCALE;
                            } else {
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                            // out colorspace remains unknown
                            }
                            if ((adobe != null) && (adobe.transform != JPEG.ADOBE_UNKNOWN)) {
                                newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                            }
                            break;
                        case ColorSpace.TYPE_RGB:
                            if (!alpha) {
                                if (jfif != null) {
                                    outCsType = JPEG.JCS_YCbCr;
                                    if (JPEG.isNonStandardICC(cs) || ((cs instanceof ICC_ColorSpace) && (jfif.iccSegment != null))) {
                                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                                    }
                                } else if (adobe != null) {
                                    switch(adobe.transform) {
                                        case JPEG.ADOBE_UNKNOWN:
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                        case JPEG.ADOBE_YCC:
                                            outCsType = JPEG.JCS_YCbCr;
                                            break;
                                        default:
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                    }
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        if (subsampled) {
                                            outCsType = JPEG.JCS_YCbCr;
                                        } else {
                                            outCsType = JPEG.JCS_RGB;
                                        }
                                    }
                                }
                            } else {
                                // RGBA
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                                if (adobe != null) {
                                    if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                        newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                        warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                    }
                                    outCsType = JPEG.JCS_RGBA;
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        outCsType = subsampled ? JPEG.JCS_YCbCrA : JPEG.JCS_RGBA;
                                    }
                                }
                            }
                            break;
                        case ColorSpace.TYPE_3CLR:
                            if (cs == JPEG.YCC) {
                                if (!alpha) {
                                    if (jfif != null) {
                                        convertTosRGB = true;
                                        convertOp = new ColorConvertOp(cs, JPEG.sRGB, null);
                                        outCsType = JPEG.JCS_YCbCr;
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_YCC) {
                                            newAdobeTransform = JPEG.ADOBE_YCC;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                        outCsType = JPEG.JCS_YCC;
                                    } else {
                                        outCsType = JPEG.JCS_YCC;
                                    }
                                } else {
                                    // PhotoYCCA
                                    if (jfif != null) {
                                        ignoreJFIF = true;
                                        warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                    }
                                    outCsType = JPEG.JCS_YCCA;
                                }
                            }
                    }
                }
            }
        // else no dest, metadata, not an image.  Defaults ok
        }
    }
    boolean metadataProgressive = false;
    int[] scans = null;
    if (metadata != null) {
        if (sof == null) {
            sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
        }
        if ((sof != null) && (sof.tag == JPEG.SOF2)) {
            metadataProgressive = true;
            if (progressiveMode == ImageWriteParam.MODE_COPY_FROM_METADATA) {
                // Might still be null
                scans = collectScans(metadata, sof);
            } else {
                numScans = 0;
            }
        }
        if (jfif == null) {
            jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        }
    }
    thumbnails = image.getThumbnails();
    int numThumbs = image.getNumThumbnails();
    forceJFIF = false;
    // then thumbnails can be written
    if (!writeDefaultJFIF) {
        // If there is no metadata, then we can't write thumbnails
        if (metadata == null) {
            thumbnails = null;
            if (numThumbs != 0) {
                warningOccurred(WARNING_IGNORING_THUMBS);
            }
        } else {
            // then the user must specify JFIF on the metadata
            if (fullImage == false) {
                if (jfif == null) {
                    // Or we can't include thumbnails
                    thumbnails = null;
                    if (numThumbs != 0) {
                        warningOccurred(WARNING_IGNORING_THUMBS);
                    }
                }
            } else {
                // It is a full image, and there is metadata
                if (jfif == null) {
                    // Can it have JFIF?
                    if ((outCsType == JPEG.JCS_GRAYSCALE) || (outCsType == JPEG.JCS_YCbCr)) {
                        if (numThumbs != 0) {
                            forceJFIF = true;
                            warningOccurred(WARNING_FORCING_JFIF);
                        }
                    } else {
                        // Nope, not JFIF-compatible
                        thumbnails = null;
                        if (numThumbs != 0) {
                            warningOccurred(WARNING_IGNORING_THUMBS);
                        }
                    }
                }
            }
        }
    }
    // Set up a boolean to indicate whether we need to call back to
    // write metadata
    boolean haveMetadata = ((metadata != null) || writeDefaultJFIF || writeAdobe);
    // Now that we have dealt with metadata, finalize our tables set up
    // Are we going to write tables?  By default, yes.
    boolean writeDQT = true;
    boolean writeDHT = true;
    // But if the metadata has no tables, no.
    DQTMarkerSegment dqt = null;
    DHTMarkerSegment dht = null;
    int restartInterval = 0;
    if (metadata != null) {
        dqt = (DQTMarkerSegment) metadata.findMarkerSegment(DQTMarkerSegment.class, true);
        dht = (DHTMarkerSegment) metadata.findMarkerSegment(DHTMarkerSegment.class, true);
        DRIMarkerSegment dri = (DRIMarkerSegment) metadata.findMarkerSegment(DRIMarkerSegment.class, true);
        if (dri != null) {
            restartInterval = dri.restartInterval;
        }
        if (dqt == null) {
            writeDQT = false;
        }
        if (dht == null) {
            // Ignored if optimizeHuffman is true
            writeDHT = false;
        }
    }
    // to use
    if (qTables == null) {
        // Get them from metadata, or use defaults
        if (dqt != null) {
            qTables = collectQTablesFromMetadata(metadata);
        } else if (streamQTables != null) {
            qTables = streamQTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // If we are optimizing, we don't want any tables.
    if (optimizeHuffman == false) {
        // If they were for progressive scans, we can't use them.
        if ((dht != null) && (metadataProgressive == false)) {
            DCHuffmanTables = collectHTablesFromMetadata(metadata, true);
            ACHuffmanTables = collectHTablesFromMetadata(metadata, false);
        } else if (streamDCHuffmanTables != null) {
            DCHuffmanTables = streamDCHuffmanTables;
            ACHuffmanTables = streamACHuffmanTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            DCHuffmanTables = jparam.getDCHuffmanTables();
            ACHuffmanTables = jparam.getACHuffmanTables();
        } else {
            DCHuffmanTables = JPEG.getDefaultHuffmanTables(true);
            ACHuffmanTables = JPEG.getDefaultHuffmanTables(false);
        }
    }
    // By default, ids are 1 - N, no subsampling
    int[] componentIds = new int[numBandsUsed];
    int[] HsamplingFactors = new int[numBandsUsed];
    int[] VsamplingFactors = new int[numBandsUsed];
    int[] QtableSelectors = new int[numBandsUsed];
    for (int i = 0; i < numBandsUsed; i++) {
        // JFIF compatible
        componentIds[i] = i + 1;
        HsamplingFactors[i] = 1;
        VsamplingFactors[i] = 1;
        QtableSelectors[i] = 0;
    }
    // Now override them with the contents of sof, if there is one,
    if (sof != null) {
        for (int i = 0; i < numBandsUsed; i++) {
            if (forceJFIF == false) {
                // else use JFIF-compatible default
                componentIds[i] = sof.componentSpecs[i].componentId;
            }
            HsamplingFactors[i] = sof.componentSpecs[i].HsamplingFactor;
            VsamplingFactors[i] = sof.componentSpecs[i].VsamplingFactor;
            QtableSelectors[i] = sof.componentSpecs[i].QtableSelector;
        }
    }
    sourceXOffset += gridX;
    sourceWidth -= gridX;
    sourceYOffset += gridY;
    sourceHeight -= gridY;
    int destWidth = (sourceWidth + periodX - 1) / periodX;
    int destHeight = (sourceHeight + periodY - 1) / periodY;
    // Create an appropriate 1-line databuffer for writing
    int lineSize = sourceWidth * numBandsUsed;
    DataBufferByte buffer = new DataBufferByte(lineSize);
    // Create a raster from that
    int[] bandOffs = JPEG.bandOffsets[numBandsUsed - 1];
    raster = Raster.createInterleavedRaster(buffer, sourceWidth, 1, lineSize, numBandsUsed, bandOffs, null);
    // Call the writer, who will call back for every scanline
    processImageStarted(currentImage);
    boolean aborted = false;
    if (debug) {
        System.out.println("inCsType: " + inCsType);
        System.out.println("outCsType: " + outCsType);
    }
    // Note that getData disables acceleration on buffer, but it is
    // just a 1-line intermediate data transfer buffer that does not
    // affect the acceleration of the source image.
    aborted = writeImage(structPointer, buffer.getData(), inCsType, outCsType, numBandsUsed, bandSizes, sourceWidth, destWidth, destHeight, periodX, periodY, qTables, writeDQT, DCHuffmanTables, ACHuffmanTables, writeDHT, optimizeHuffman, (progressiveMode != ImageWriteParam.MODE_DISABLED), numScans, scans, componentIds, HsamplingFactors, VsamplingFactors, QtableSelectors, haveMetadata, restartInterval);
    if (aborted) {
        processWriteAborted();
    } else {
        processImageComplete();
    }
    ios.flush();
    // After a successful write
    currentImage++;
}
Example 24
Project: bioformats-master  File: TIFFImageWriter.java View source code
public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) {
    // Check arguments.
    if (inData == null) {
        throw new IllegalArgumentException("inData == null!");
    }
    if (imageType == null) {
        throw new IllegalArgumentException("imageType == null!");
    }
    TIFFImageMetadata outData = null;
    // Obtain a TIFFImageMetadata object.
    if (inData instanceof TIFFImageMetadata) {
        // Create a new metadata object from a clone of the input IFD.
        TIFFIFD inIFD = ((TIFFImageMetadata) inData).getRootIFD();
        outData = new TIFFImageMetadata(inIFD.getShallowClone());
    } else if (Arrays.asList(inData.getMetadataFormatNames()).contains(TIFFImageMetadata.nativeMetadataFormatName)) {
        // Initialize from the native metadata form of the input tree.
        try {
            outData = convertNativeImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
        }
    } else if (inData.isStandardMetadataFormatSupported()) {
        // Initialize from the standard metadata form of the input tree.
        try {
            outData = convertStandardImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
        }
    }
    // Update the metadata per the image type and param.
    if (outData != null) {
        TIFFImageWriter bogusWriter = new TIFFImageWriter(this.originatingProvider);
        bogusWriter.imageMetadata = outData;
        bogusWriter.param = param;
        SampleModel sm = imageType.getSampleModel();
        try {
            bogusWriter.setupMetadata(imageType.getColorModel(), sm, sm.getWidth(), sm.getHeight());
            return bogusWriter.imageMetadata;
        } catch (IIOException e) {
            return null;
        }
    }
    return outData;
}
Example 25
Project: celements-photo-master  File: DecodeImageCommand.java View source code
public BufferedImage readImage(XWikiAttachment att, XWikiContext context) throws IOException, ImageReadException, XWikiException {
    colorType = COLOR_TYPE_RGB;
    boolean hasAdobeMarker = false;
    ImageInputStream stream = ImageIO.createImageInputStream(att.getContentInputStream(context));
    Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
    while (iter.hasNext()) {
        ImageReader reader = iter.next();
        reader.setInput(stream);
        BufferedImage image;
        ICC_Profile profile = null;
        try {
            try {
                image = reader.read(0);
            } catch (CMMException cmmExcp) {
                image = readUsingJAI(att, context);
            }
        } catch (IIOException iioExcp) {
            colorType = COLOR_TYPE_CMYK;
            hasAdobeMarker = hasAdobeMarker(att.getContentInputStream(context), att.getFilename());
            profile = Sanselan.getICCProfile(att.getContentInputStream(context), att.getFilename());
            WritableRaster raster = (WritableRaster) reader.readRaster(0, null);
            if (colorType == COLOR_TYPE_YCCK) {
                convertYcckToCmyk(raster);
            }
            if (hasAdobeMarker) {
                convertInvertedColors(raster);
            }
            image = convertCmykToRgb(raster, profile);
        }
        return image;
    }
    return null;
}
Example 26
Project: classlib6-master  File: PNGImageReader.java View source code
private void readHeader() throws IIOException {
    if (gotHeader) {
        return;
    }
    if (stream == null) {
        throw new IllegalStateException("Input source not set!");
    }
    try {
        byte[] signature = new byte[8];
        stream.readFully(signature);
        if (signature[0] != (byte) 137 || signature[1] != (byte) 80 || signature[2] != (byte) 78 || signature[3] != (byte) 71 || signature[4] != (byte) 13 || signature[5] != (byte) 10 || signature[6] != (byte) 26 || signature[7] != (byte) 10) {
            throw new IIOException("Bad PNG signature!");
        }
        int IHDR_length = stream.readInt();
        if (IHDR_length != 13) {
            throw new IIOException("Bad length for IHDR chunk!");
        }
        int IHDR_type = stream.readInt();
        if (IHDR_type != IHDR_TYPE) {
            throw new IIOException("Bad type for IHDR chunk!");
        }
        this.metadata = new PNGMetadata();
        int width = stream.readInt();
        int height = stream.readInt();
        // Re-use signature array to bulk-read these unsigned byte values
        stream.readFully(signature, 0, 5);
        int bitDepth = signature[0] & 0xff;
        int colorType = signature[1] & 0xff;
        int compressionMethod = signature[2] & 0xff;
        int filterMethod = signature[3] & 0xff;
        int interlaceMethod = signature[4] & 0xff;
        // Skip IHDR CRC
        stream.skipBytes(4);
        stream.flushBefore(stream.getStreamPosition());
        if (width == 0) {
            throw new IIOException("Image width == 0!");
        }
        if (height == 0) {
            throw new IIOException("Image height == 0!");
        }
        if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 && bitDepth != 16) {
            throw new IIOException("Bit depth must be 1, 2, 4, 8, or 16!");
        }
        if (colorType != 0 && colorType != 2 && colorType != 3 && colorType != 4 && colorType != 6) {
            throw new IIOException("Color type must be 0, 2, 3, 4, or 6!");
        }
        if (colorType == PNG_COLOR_PALETTE && bitDepth == 16) {
            throw new IIOException("Bad color type/bit depth combination!");
        }
        if ((colorType == PNG_COLOR_RGB || colorType == PNG_COLOR_RGB_ALPHA || colorType == PNG_COLOR_GRAY_ALPHA) && (bitDepth != 8 && bitDepth != 16)) {
            throw new IIOException("Bad color type/bit depth combination!");
        }
        if (compressionMethod != 0) {
            throw new IIOException("Unknown compression method (not 0)!");
        }
        if (filterMethod != 0) {
            throw new IIOException("Unknown filter method (not 0)!");
        }
        if (interlaceMethod != 0 && interlaceMethod != 1) {
            throw new IIOException("Unknown interlace method (not 0 or 1)!");
        }
        metadata.IHDR_present = true;
        metadata.IHDR_width = width;
        metadata.IHDR_height = height;
        metadata.IHDR_bitDepth = bitDepth;
        metadata.IHDR_colorType = colorType;
        metadata.IHDR_compressionMethod = compressionMethod;
        metadata.IHDR_filterMethod = filterMethod;
        metadata.IHDR_interlaceMethod = interlaceMethod;
        gotHeader = true;
    } catch (IOException e) {
        throw new IIOException("I/O error reading PNG header!", e);
    }
}
Example 27
Project: dataverse-master  File: DTAFileReaderSpi.java View source code
@Override
public boolean canDecodeInput(File file) throws IOException {
    if (file == null) {
        throw new IllegalArgumentException("file == null!");
    }
    if (!file.canRead()) {
        throw new IIOException("cannot read the input file");
    }
    // set-up a FileChannel instance for a given file object
    FileChannel srcChannel = new FileInputStream(file).getChannel();
    // create a read-only MappedByteBuffer
    MappedByteBuffer buff = srcChannel.map(FileChannel.MapMode.READ_ONLY, 0, DTA_HEADER_SIZE);
    //printHexDump(buff, "hex dump of the byte-buffer");
    buff.rewind();
    dbgLog.fine("applying the dta test\n");
    byte[] hdr4 = new byte[4];
    buff.get(hdr4, 0, 4);
    dbgLog.fine("hex dump: 1st 4bytes =>" + new String(Hex.encodeHex(hdr4)) + "<-");
    if (hdr4[2] != 1) {
        dbgLog.fine("3rd byte is not 1: given file is not stata-dta type");
        return false;
    } else if ((hdr4[1] != 1) && (hdr4[1] != 2)) {
        dbgLog.fine("2nd byte is neither 0 nor 1: this file is not stata-dta type");
        return false;
    } else if (!stataReleaseNumber.containsKey(hdr4[0])) {
        dbgLog.fine("1st byte (" + hdr4[0] + ") is not within the ingestable range [rel. 3-10]: this file is NOT stata-dta type");
        return false;
    } else {
        dbgLog.fine("this file is stata-dta type: " + stataReleaseNumber.get(hdr4[0]) + "(No in HEX=" + hdr4[0] + ")");
        return true;
    }
}
Example 28
Project: ddf-master  File: PptxInputTransformer.java View source code
/**
     * If the slide show doesn't contain any slides, then return null. Otherwise, return jpeg
     * image data of the first slide in the deck.
     *
     * @param slideShow
     * @return jpeg thumbnail or null if thumbnail can't be created
     * @throws IOException
     */
private byte[] generatePptxThumbnail(XMLSlideShow slideShow) throws IOException {
    if (slideShow.getSlides().isEmpty()) {
        LOGGER.debug("the powerpoint file does not contain any slides, skipping thumbnail generation");
        return null;
    }
    Dimension pgsize = slideShow.getPageSize();
    int largestDimension = (int) Math.max(pgsize.getHeight(), pgsize.getWidth());
    float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension;
    int scaledHeight = (int) (pgsize.getHeight() * scalingFactor);
    int scaledWidth = (int) (pgsize.getWidth() * scalingFactor);
    BufferedImage img = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = img.createGraphics();
    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        graphics.scale(scalingFactor, scalingFactor);
        slideShow.getSlides().get(0).draw(graphics);
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIOUtil.writeImage(img, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY);
            return outputStream.toByteArray();
        }
    } catch (RuntimeException e) {
        if (e.getCause() instanceof javax.imageio.IIOException) {
            LOGGER.debug("unable to generate thumbnail for PPTX file", e);
        } else {
            throw e;
        }
    } finally {
        graphics.dispose();
    }
    return null;
}
Example 29
Project: dvn-master  File: ExploreDataPage.java View source code
private void writeImageFile(File fileIn, File pdfFileIn) {
    File imagePngFile = null;
    try {
        String decoded = URLDecoder.decode(imageURL, "UTF-8");
        if (!decoded.isEmpty()) {
            URL imageURLnew = new URL(imageURL);
            try {
                BufferedImage image = ImageIO.read(imageURLnew);
                BufferedImage combinedImage = getCompositeImage(image);
                if (fileIn != null) {
                    ImageIO.write(combinedImage, "png", fileIn);
                }
                if (pdfFileIn != null) {
                    imagePngFile = File.createTempFile("pdfDownload", "png");
                    ImageIO.write(combinedImage, "png", imagePngFile);
                    Document convertPngToPdf = new Document();
                    PdfWriter.getInstance(convertPngToPdf, new FileOutputStream(pdfFileIn, true));
                    convertPngToPdf.open();
                    Image convertBmp = PngImage.getImage(imagePngFile.getAbsolutePath());
                    convertBmp.scaleToFit(530f, 500f);
                    convertPngToPdf.add(convertBmp);
                    convertPngToPdf.close();
                }
            } catch (IIOException io) {
                System.out.println(io.getMessage().toString());
                System.out.println(io.getCause().toString());
                System.out.println("IIOException " + imageURLnew);
            } catch (FontFormatException ff) {
                System.out.println("FontFormatException " + imageURLnew);
                System.out.println("FontFormatException " + ff.toString());
            }
        }
    } catch (UnsupportedEncodingException uee) {
        System.out.println("UnsupportedEncodingException ");
    } catch (MalformedURLException mue) {
        System.out.println("MalformedURLException ");
    } catch (IOException io) {
        System.out.println("IOException - outer ");
    } catch (DocumentException io) {
        System.out.println("IOException - document ");
        System.out.println(io.getMessage());
    } finally {
        if (imagePngFile != null && imagePngFile.exists()) {
            if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) {
                imagePngFile.delete();
            }
        }
    }
}
Example 30
Project: geotoolkit-master  File: TiffImageWriter.java View source code
/**
     * {@inheritDoc }
     *
     * If param is {@code null} a default tiling mode 256 x 256 is choosen.
     */
@Override
public void prepareWriteEmpty(IIOMetadata streamMetadata, ImageTypeSpecifier imageType, int width, int height, IIOMetadata imageMetadata, List<? extends BufferedImage> thumbnails, ImageWriteParam param) throws IOException {
    ArgumentChecks.ensureNonNull("imageType", imageType);
    if (param == null) {
        param = getDefaultWriteParam();
    }
    // TODO : Remove test when tiles won't be necessary.
    if (param.getTilingMode() != ImageWriteParam.MODE_EXPLICIT || param.getTileWidth() <= 0 || param.getTileHeight() <= 0) {
        //-- with prepare write empty force writing by tile 256 x 256--//
        param.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
        param.setTiling(256, 256, 0, 0);
    }
    // avant d'appeler open definir sil sagit d'une bigtiff
    // 1 : isBigTiff
    final SampleModel sm = imageType.getSampleModel();
    //-- 1 for interleaved, 2 for banded
    final short planarConfiguration = ImageUtils.getPlanarConfiguration(sm);
    final int[] sampleSize = sm.getSampleSize();
    final int numBands = sm.getNumBands();
    int pixelSize = 0;
    for (int i = 0; i < sampleSize.length; i++) {
        pixelSize += sampleSize[i];
    }
    //-- >= 1Go
    isBigTIFF = ((long) width * height * pixelSize / Byte.SIZE) >= 1E9;
    if (channel != null) {
        //-- define if nextPositionIFD has already been set --//
        if (ifdPosition[1] > 0) {
            /*
                 * If an image has already been written we stipulate next ifd position.
                 */
            final long offset = (channel.getStreamPosition());
            channel.seek(ifdPosition[1]);
            if (isBigTIFF)
                channel.writeLong(offset);
            else
                channel.writeInt((int) offset);
            channel.seek(offset);
            ifdPosition[0] = offset;
        }
    } else {
        if (isBigTIFF) {
            currentSizeEntry = SIZE_BIG_ENTRY;
            // long
            currentSizeTagNumber = Long.SIZE / Byte.SIZE;
            // long
            currentSizeNextIFD = Long.SIZE / Byte.SIZE;
        } else {
            currentSizeEntry = SIZE_ENTRY;
            // short
            currentSizeTagNumber = Short.SIZE / Byte.SIZE;
            // int
            currentSizeNextIFD = Integer.SIZE / Byte.SIZE;
        }
    }
    //-- open
    open(ifdPosition);
    assert headProperties == null;
    //-- a new distinct map for each layer --//
    headProperties = new TreeMap<>();
    //-- get metadata from stream --//
    if (streamMetadata != null) {
        final IIOMetadata strMetadata = toGTiffFormat(streamMetadata);
        final Node iioNode = strMetadata.getAsTree(strMetadata.getNativeMetadataFormatName());
        addMetadataProperties(iioNode, headProperties);
    }
    //-- get metadata from image --//
    if (imageMetadata != null) {
        final IIOMetadata imgMetadata = toGTiffFormat(streamMetadata);
        final Node iioNode = imgMetadata.getAsTree(imgMetadata.getNativeMetadataFormatName());
        addMetadataProperties(iioNode, headProperties);
    }
    //-- end metadatas --//
    //-- image study --//
    //-- hidden computeregion()
    addImageProperties(imageType, width, height, headProperties, param);
    if (//uncompressed
    compression != 1)
        throw new IllegalArgumentException("impossible to write empty with compression. Expected compression value 1, found : " + compression);
    //-- write all image properties. --//
    //-- write tiff tags --//
    writeTags(headProperties, ifdPosition);
    //-- write arrays byte count and offset
    //-- write empty always tiled
    {
        assert currentImgTW != 0;
        assert currentImgTH != 0;
        final int dstNumXT = tileRegion.width / currentImgTW;
        assert tileRegion.width % currentImgTW == 0;
        final int dstNumYT = tileRegion.height / currentImgTH;
        assert tileRegion.height % currentImgTH == 0;
        assert bitPerSample != 0;
        final boolean isBanded = planarConfiguration == 2;
        final int numTiles = dstNumXT * dstNumYT * (isBanded ? numBands : 1);
        final Object byteCountArray;
        final long byteCountArraySize;
        final Object offsetArray;
        final long offsetArraySize;
        final short arrayType = isBigTIFF ? TYPE_ULONG : TYPE_UINT;
        if (isBigTIFF) {
            byteCountArray = new long[numTiles];
            offsetArray = new long[numTiles];
        } else {
            byteCountArray = new int[numTiles];
            offsetArray = new int[numTiles];
        }
        byteCountArraySize = offsetArraySize = numTiles * TYPE_SIZE[arrayType];
        final long buffPos = channel.getStreamPosition();
        //-- to know if bytecountArray will be written deffered
        final int datasize = (isBigTIFF) ? Long.SIZE / Byte.SIZE : Integer.SIZE / Byte.SIZE;
        final long destByteCountArraySize = (byteCountArraySize > datasize) ? byteCountArraySize : 0;
        final long destOffsetArraySize = (offsetArraySize > datasize) ? offsetArraySize : 0;
        //-- write current tile byte position --//
        final long currentByteCount = (long) currentImgTW * currentImgTH * (isBanded ? 1 : numBands) * bitPerSample / Byte.SIZE;
        //-- position in bytes
        final long tileOffsetBeg = buffPos + destByteCountArraySize + destOffsetArraySize;
        long currentoffset = tileOffsetBeg;
        // fill byte count array
        if (isBigTIFF) {
            Arrays.fill((long[]) byteCountArray, currentByteCount);
            for (int i = 0; i < numTiles; i++) {
                Array.setLong(offsetArray, i, currentoffset);
                currentoffset += currentByteCount;
            }
        } else {
            Arrays.fill((int[]) byteCountArray, (int) currentByteCount);
            for (int i = 0; i < numTiles; i++) {
                Array.setInt(offsetArray, i, (int) currentoffset);
                currentoffset += currentByteCount;
            }
        }
        endOfFile = currentoffset;
        assert endOfFile == tileOffsetBeg + numTiles * currentByteCount;
        writeByteCountAndOffsets(byteCountTagPosition, arrayType, byteCountArray, offsetTagPosition, arrayType, offsetArray);
        //-- add current offset array in current headProperties --//
        addProperty(TileOffsets, (isBigTIFF) ? TYPE_ULONG : TYPE_UINT, Array.getLength(offsetArray), offsetArray, headProperties);
        if ((byteCountArraySize > datasize))
            assert tileOffsetBeg == channel.getStreamPosition() : "expected : " + tileOffsetBeg + ". found : " + channel.getStreamPosition();
        else
            assert (offsetTagPosition + datasize) == channel.getStreamPosition() : "expected : " + tileOffsetBeg + ". found : " + channel.getStreamPosition();
        channel.seek(tileOffsetBeg);
        if (metaIndex == metaHeads.length) {
            metaHeads = Arrays.copyOf(metaHeads, metaHeads.length << 1);
        }
        metaHeads[metaIndex++] = headProperties;
        this.headProperties = null;
        final int dataType = sm.getDataType();
        /*
             * Banded      = numbands tiles of size (tileWidth * tileHeight)
             * Interleaved = one tile of size (tilewidth * tileHeight * numbands)
             */
        final int fakeTileArrayLength = currentImgTW * currentImgTH * (isBanded ? 1 : numBands);
        Object fakeTile;
        switch(dataType) {
            case DataBuffer.TYPE_BYTE:
                fakeTile = new byte[fakeTileArrayLength];
                break;
            case DataBuffer.TYPE_USHORT:
            case DataBuffer.TYPE_SHORT:
                fakeTile = new short[fakeTileArrayLength];
                break;
            case DataBuffer.TYPE_INT:
                fakeTile = new int[fakeTileArrayLength];
                break;
            case DataBuffer.TYPE_FLOAT:
                fakeTile = new float[fakeTileArrayLength];
                break;
            case DataBuffer.TYPE_DOUBLE:
                fakeTile = new double[fakeTileArrayLength];
                break;
            default:
                throw new IIOException(error(Errors.Keys.UnsupportedDataType, dataType));
        }
        for (int ty = 0; ty < numTiles; ty++) {
            write(fakeTile, dataType, 0, fakeTileArrayLength, bitPerSample, compression);
        }
        assert channel.getStreamPosition() == endOfFile;
    }
// 1 : etude du image type specifier
// 2 : garder width and height
// 3 : etude du compute region en fonction de width heigth et param
// 4 : injecter les metadatas
// 5 : garder les thumbnails pour les ecrires au endwriteempty
//        super.prepareWriteEmpty(streamMetadata, imageType, width, height, imageMetadata, thumbnails, param); //To change body of generated methods, choose Tools | Templates.
}
Example 31
Project: ikvm-openjdk-master  File: JPEGImageWriter.java View source code
private void writeOnThread(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (ios == null) {
        throw new IllegalStateException("Output has not been set!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image is null!");
    }
    // if streamMetadata is not null, issue a warning
    if (streamMetadata != null) {
        warningOccurred(WARNING_STREAM_METADATA_IGNORED);
    }
    // Obtain the raster and image, if there is one
    boolean rasterOnly = image.hasRaster();
    RenderedImage rimage = null;
    if (rasterOnly) {
        srcRas = image.getRaster();
    } else {
        rimage = image.getRenderedImage();
        if (rimage instanceof BufferedImage) {
            // Use the Raster directly.
            srcRas = ((BufferedImage) rimage).getRaster();
        } else if (rimage.getNumXTiles() == 1 && rimage.getNumYTiles() == 1) {
            // Get the unique tile.
            srcRas = rimage.getTile(rimage.getMinTileX(), rimage.getMinTileY());
            // as the tile dimensions might differ.
            if (srcRas.getWidth() != rimage.getWidth() || srcRas.getHeight() != rimage.getHeight()) {
                srcRas = srcRas.createChild(srcRas.getMinX(), srcRas.getMinY(), rimage.getWidth(), rimage.getHeight(), srcRas.getMinX(), srcRas.getMinY(), null);
            }
        } else {
            // Image is tiled so get a contiguous raster by copying.
            srcRas = rimage.getData();
        }
    }
    // Now determine if we are using a band subset
    // By default, we are using all source bands
    int numSrcBands = srcRas.getNumBands();
    indexed = false;
    indexCM = null;
    ColorModel cm = null;
    ColorSpace cs = null;
    isAlphaPremultiplied = false;
    srcCM = null;
    if (!rasterOnly) {
        cm = rimage.getColorModel();
        if (cm != null) {
            cs = cm.getColorSpace();
            if (cm instanceof IndexColorModel) {
                indexed = true;
                indexCM = (IndexColorModel) cm;
                numSrcBands = cm.getNumComponents();
            }
            if (cm.isAlphaPremultiplied()) {
                isAlphaPremultiplied = true;
                srcCM = cm;
            }
        }
    }
    srcBands = JPEG.bandOffsets[numSrcBands - 1];
    int numBandsUsed = numSrcBands;
    if (param != null) {
        int[] sBands = param.getSourceBands();
        if (sBands != null) {
            if (indexed) {
                warningOccurred(WARNING_NO_BANDS_ON_INDEXED);
            } else {
                srcBands = sBands;
                numBandsUsed = srcBands.length;
                if (numBandsUsed > numSrcBands) {
                    throw new IIOException("ImageWriteParam specifies too many source bands");
                }
            }
        }
    }
    boolean usingBandSubset = (numBandsUsed != numSrcBands);
    boolean fullImage = ((!rasterOnly) && (!usingBandSubset));
    int[] bandSizes = null;
    if (!indexed) {
        bandSizes = srcRas.getSampleModel().getSampleSize();
        // If this is a subset, we must adjust bandSizes
        if (usingBandSubset) {
            int[] temp = new int[numBandsUsed];
            for (int i = 0; i < numBandsUsed; i++) {
                temp[i] = bandSizes[srcBands[i]];
            }
            bandSizes = temp;
        }
    } else {
        int[] tempSize = srcRas.getSampleModel().getSampleSize();
        bandSizes = new int[numSrcBands];
        for (int i = 0; i < numSrcBands; i++) {
            // All the same
            bandSizes[i] = tempSize[0];
        }
    }
    for (int i = 0; i < bandSizes.length; i++) {
        // per sample.
        if (bandSizes[i] > 8) {
            throw new IIOException("Sample size must be <= 8");
        }
        // to 8-bit.
        if (indexed) {
            bandSizes[i] = 8;
        }
    }
    if (debug) {
        System.out.println("numSrcBands is " + numSrcBands);
        System.out.println("numBandsUsed is " + numBandsUsed);
        System.out.println("usingBandSubset is " + usingBandSubset);
        System.out.println("fullImage is " + fullImage);
        System.out.print("Band sizes:");
        for (int i = 0; i < bandSizes.length; i++) {
            System.out.print(" " + bandSizes[i]);
        }
        System.out.println();
    }
    // Destination type, if there is one
    ImageTypeSpecifier destType = null;
    if (param != null) {
        destType = param.getDestinationType();
        // Ignore dest type if we are writing a complete image
        if ((fullImage) && (destType != null)) {
            warningOccurred(WARNING_DEST_IGNORED);
            destType = null;
        }
    }
    // Examine the param
    sourceXOffset = srcRas.getMinX();
    sourceYOffset = srcRas.getMinY();
    int imageWidth = srcRas.getWidth();
    int imageHeight = srcRas.getHeight();
    sourceWidth = imageWidth;
    sourceHeight = imageHeight;
    int periodX = 1;
    int periodY = 1;
    int gridX = 0;
    int gridY = 0;
    JPEGQTable[] qTables = null;
    JPEGHuffmanTable[] DCHuffmanTables = null;
    JPEGHuffmanTable[] ACHuffmanTables = null;
    boolean optimizeHuffman = false;
    JPEGImageWriteParam jparam = null;
    int progressiveMode = ImageWriteParam.MODE_DISABLED;
    if (param != null) {
        Rectangle sourceRegion = param.getSourceRegion();
        if (sourceRegion != null) {
            Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
            sourceRegion = sourceRegion.intersection(imageBounds);
            sourceXOffset = sourceRegion.x;
            sourceYOffset = sourceRegion.y;
            sourceWidth = sourceRegion.width;
            sourceHeight = sourceRegion.height;
        }
        if (sourceWidth + sourceXOffset > imageWidth) {
            sourceWidth = imageWidth - sourceXOffset;
        }
        if (sourceHeight + sourceYOffset > imageHeight) {
            sourceHeight = imageHeight - sourceYOffset;
        }
        periodX = param.getSourceXSubsampling();
        periodY = param.getSourceYSubsampling();
        gridX = param.getSubsamplingXOffset();
        gridY = param.getSubsamplingYOffset();
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        progressiveMode = param.getProgressiveMode();
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
            optimizeHuffman = jparam.getOptimizeHuffmanTables();
        }
    }
    // Now examine the metadata
    IIOMetadata mdata = image.getMetadata();
    if (mdata != null) {
        if (mdata instanceof JPEGMetadata) {
            metadata = (JPEGMetadata) mdata;
            if (debug) {
                System.out.println("We have metadata, and it's JPEG metadata");
            }
        } else {
            if (!rasterOnly) {
                ImageTypeSpecifier type = destType;
                if (type == null) {
                    type = new ImageTypeSpecifier(rimage);
                }
                metadata = (JPEGMetadata) convertImageMetadata(mdata, type, param);
            } else {
                warningOccurred(WARNING_METADATA_NOT_JPEG_FOR_RASTER);
            }
        }
    }
    // First set a default state
    // If it's there, use it
    ignoreJFIF = false;
    // If it's there, use it
    ignoreAdobe = false;
    // Change if needed
    newAdobeTransform = JPEG.ADOBE_IMPOSSIBLE;
    writeDefaultJFIF = false;
    writeAdobe = false;
    // By default we'll do no conversion:
    int inCsType = JPEG.JCS_UNKNOWN;
    int outCsType = JPEG.JCS_UNKNOWN;
    JFIFMarkerSegment jfif = null;
    AdobeMarkerSegment adobe = null;
    SOFMarkerSegment sof = null;
    if (metadata != null) {
        jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        adobe = (AdobeMarkerSegment) metadata.findMarkerSegment(AdobeMarkerSegment.class, true);
        sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
    }
    // By default don't write one
    iccProfile = null;
    // PhotoYCC does this
    convertTosRGB = false;
    converted = null;
    if (destType != null) {
        if (numBandsUsed != destType.getNumBands()) {
            throw new IIOException("Number of source bands != number of destination bands");
        }
        cs = destType.getColorModel().getColorSpace();
        // Check the metadata against the destination type
        if (metadata != null) {
            checkSOFBands(sof, numBandsUsed);
            checkJFIF(jfif, destType, false);
            // Do we want to write an ICC profile?
            if ((jfif != null) && (ignoreJFIF == false)) {
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            }
            checkAdobe(adobe, destType, false);
        } else {
            // If we can add a JFIF or an Adobe marker segment, do so
            if (JPEG.isJFIFcompliant(destType, false)) {
                writeDefaultJFIF = true;
                // Do we want to write an ICC profile?
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            } else {
                int transform = JPEG.transformForType(destType, false);
                if (transform != JPEG.ADOBE_IMPOSSIBLE) {
                    writeAdobe = true;
                    newAdobeTransform = transform;
                }
            }
            // re-create the metadata
            metadata = new JPEGMetadata(destType, null, this);
        }
        inCsType = getSrcCSType(destType);
        outCsType = getDefaultDestCSType(destType);
    } else {
        // no destination type
        if (metadata == null) {
            if (fullImage) {
                // no dest, no metadata, full image
                // Use default metadata matching the image and param
                metadata = new JPEGMetadata(new ImageTypeSpecifier(rimage), param, this);
                if (metadata.findMarkerSegment(JFIFMarkerSegment.class, true) != null) {
                    cs = rimage.getColorModel().getColorSpace();
                    if (JPEG.isNonStandardICC(cs)) {
                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                    }
                }
                inCsType = getSrcCSType(rimage);
                outCsType = getDefaultDestCSType(rimage);
            }
        // else no dest, no metadata, not an image,
        // so no special headers, no color conversion
        } else {
            // no dest type, but there is metadata
            checkSOFBands(sof, numBandsUsed);
            if (fullImage) {
                // no dest, metadata, image
                // Check that the metadata and the image match
                ImageTypeSpecifier inputType = new ImageTypeSpecifier(rimage);
                inCsType = getSrcCSType(rimage);
                if (cm != null) {
                    boolean alpha = cm.hasAlpha();
                    switch(cs.getType()) {
                        case ColorSpace.TYPE_GRAY:
                            if (!alpha) {
                                outCsType = JPEG.JCS_GRAYSCALE;
                            } else {
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                            // out colorspace remains unknown
                            }
                            if ((adobe != null) && (adobe.transform != JPEG.ADOBE_UNKNOWN)) {
                                newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                            }
                            break;
                        case ColorSpace.TYPE_RGB:
                            if (!alpha) {
                                if (jfif != null) {
                                    outCsType = JPEG.JCS_YCbCr;
                                    if (JPEG.isNonStandardICC(cs) || ((cs instanceof ICC_ColorSpace) && (jfif.iccSegment != null))) {
                                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                                    }
                                } else if (adobe != null) {
                                    switch(adobe.transform) {
                                        case JPEG.ADOBE_UNKNOWN:
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                        case JPEG.ADOBE_YCC:
                                            outCsType = JPEG.JCS_YCbCr;
                                            break;
                                        default:
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                    }
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        if (subsampled) {
                                            outCsType = JPEG.JCS_YCbCr;
                                        } else {
                                            outCsType = JPEG.JCS_RGB;
                                        }
                                    }
                                }
                            } else {
                                // RGBA
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                                if (adobe != null) {
                                    if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                        newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                        warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                    }
                                    outCsType = JPEG.JCS_RGBA;
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        outCsType = subsampled ? JPEG.JCS_YCbCrA : JPEG.JCS_RGBA;
                                    }
                                }
                            }
                            break;
                        case ColorSpace.TYPE_3CLR:
                            if (cs == JPEG.YCC) {
                                if (!alpha) {
                                    if (jfif != null) {
                                        convertTosRGB = true;
                                        convertOp = new ColorConvertOp(cs, JPEG.sRGB, null);
                                        outCsType = JPEG.JCS_YCbCr;
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_YCC) {
                                            newAdobeTransform = JPEG.ADOBE_YCC;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                        outCsType = JPEG.JCS_YCC;
                                    } else {
                                        outCsType = JPEG.JCS_YCC;
                                    }
                                } else {
                                    // PhotoYCCA
                                    if (jfif != null) {
                                        ignoreJFIF = true;
                                        warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                    }
                                    outCsType = JPEG.JCS_YCCA;
                                }
                            }
                    }
                }
            }
        // else no dest, metadata, not an image.  Defaults ok
        }
    }
    boolean metadataProgressive = false;
    int[] scans = null;
    if (metadata != null) {
        if (sof == null) {
            sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
        }
        if ((sof != null) && (sof.tag == JPEG.SOF2)) {
            metadataProgressive = true;
            if (progressiveMode == ImageWriteParam.MODE_COPY_FROM_METADATA) {
                // Might still be null
                scans = collectScans(metadata, sof);
            } else {
                numScans = 0;
            }
        }
        if (jfif == null) {
            jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        }
    }
    thumbnails = image.getThumbnails();
    int numThumbs = image.getNumThumbnails();
    forceJFIF = false;
    // then thumbnails can be written
    if (!writeDefaultJFIF) {
        // If there is no metadata, then we can't write thumbnails
        if (metadata == null) {
            thumbnails = null;
            if (numThumbs != 0) {
                warningOccurred(WARNING_IGNORING_THUMBS);
            }
        } else {
            // then the user must specify JFIF on the metadata
            if (fullImage == false) {
                if (jfif == null) {
                    // Or we can't include thumbnails
                    thumbnails = null;
                    if (numThumbs != 0) {
                        warningOccurred(WARNING_IGNORING_THUMBS);
                    }
                }
            } else {
                // It is a full image, and there is metadata
                if (jfif == null) {
                    // Can it have JFIF?
                    if ((outCsType == JPEG.JCS_GRAYSCALE) || (outCsType == JPEG.JCS_YCbCr)) {
                        if (numThumbs != 0) {
                            forceJFIF = true;
                            warningOccurred(WARNING_FORCING_JFIF);
                        }
                    } else {
                        // Nope, not JFIF-compatible
                        thumbnails = null;
                        if (numThumbs != 0) {
                            warningOccurred(WARNING_IGNORING_THUMBS);
                        }
                    }
                }
            }
        }
    }
    // Set up a boolean to indicate whether we need to call back to
    // write metadata
    boolean haveMetadata = ((metadata != null) || writeDefaultJFIF || writeAdobe);
    // Now that we have dealt with metadata, finalize our tables set up
    // Are we going to write tables?  By default, yes.
    boolean writeDQT = true;
    boolean writeDHT = true;
    // But if the metadata has no tables, no.
    DQTMarkerSegment dqt = null;
    DHTMarkerSegment dht = null;
    int restartInterval = 0;
    if (metadata != null) {
        dqt = (DQTMarkerSegment) metadata.findMarkerSegment(DQTMarkerSegment.class, true);
        dht = (DHTMarkerSegment) metadata.findMarkerSegment(DHTMarkerSegment.class, true);
        DRIMarkerSegment dri = (DRIMarkerSegment) metadata.findMarkerSegment(DRIMarkerSegment.class, true);
        if (dri != null) {
            restartInterval = dri.restartInterval;
        }
        if (dqt == null) {
            writeDQT = false;
        }
        if (dht == null) {
            // Ignored if optimizeHuffman is true
            writeDHT = false;
        }
    }
    // to use
    if (qTables == null) {
        // Get them from metadata, or use defaults
        if (dqt != null) {
            qTables = collectQTablesFromMetadata(metadata);
        } else if (streamQTables != null) {
            qTables = streamQTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // If we are optimizing, we don't want any tables.
    if (optimizeHuffman == false) {
        // If they were for progressive scans, we can't use them.
        if ((dht != null) && (metadataProgressive == false)) {
            DCHuffmanTables = collectHTablesFromMetadata(metadata, true);
            ACHuffmanTables = collectHTablesFromMetadata(metadata, false);
        } else if (streamDCHuffmanTables != null) {
            DCHuffmanTables = streamDCHuffmanTables;
            ACHuffmanTables = streamACHuffmanTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            DCHuffmanTables = jparam.getDCHuffmanTables();
            ACHuffmanTables = jparam.getACHuffmanTables();
        } else {
            DCHuffmanTables = JPEG.getDefaultHuffmanTables(true);
            ACHuffmanTables = JPEG.getDefaultHuffmanTables(false);
        }
    }
    // By default, ids are 1 - N, no subsampling
    int[] componentIds = new int[numBandsUsed];
    int[] HsamplingFactors = new int[numBandsUsed];
    int[] VsamplingFactors = new int[numBandsUsed];
    int[] QtableSelectors = new int[numBandsUsed];
    for (int i = 0; i < numBandsUsed; i++) {
        // JFIF compatible
        componentIds[i] = i + 1;
        HsamplingFactors[i] = 1;
        VsamplingFactors[i] = 1;
        QtableSelectors[i] = 0;
    }
    // Now override them with the contents of sof, if there is one,
    if (sof != null) {
        for (int i = 0; i < numBandsUsed; i++) {
            if (forceJFIF == false) {
                // else use JFIF-compatible default
                componentIds[i] = sof.componentSpecs[i].componentId;
            }
            HsamplingFactors[i] = sof.componentSpecs[i].HsamplingFactor;
            VsamplingFactors[i] = sof.componentSpecs[i].VsamplingFactor;
            QtableSelectors[i] = sof.componentSpecs[i].QtableSelector;
        }
    }
    sourceXOffset += gridX;
    sourceWidth -= gridX;
    sourceYOffset += gridY;
    sourceHeight -= gridY;
    int destWidth = (sourceWidth + periodX - 1) / periodX;
    int destHeight = (sourceHeight + periodY - 1) / periodY;
    // Create an appropriate 1-line databuffer for writing
    int lineSize = sourceWidth * numBandsUsed;
    DataBufferByte buffer = new DataBufferByte(lineSize);
    // Create a raster from that
    int[] bandOffs = JPEG.bandOffsets[numBandsUsed - 1];
    raster = Raster.createInterleavedRaster(buffer, sourceWidth, 1, lineSize, numBandsUsed, bandOffs, null);
    // Call the writer, who will call back for every scanline
    processImageStarted(currentImage);
    boolean aborted = false;
    if (debug) {
        System.out.println("inCsType: " + inCsType);
        System.out.println("outCsType: " + outCsType);
    }
    // Note that getData disables acceleration on buffer, but it is
    // just a 1-line intermediate data transfer buffer that does not
    // affect the acceleration of the source image.
    aborted = writeImage(structPointer, buffer.getData(), inCsType, outCsType, numBandsUsed, bandSizes, sourceWidth, destWidth, destHeight, periodX, periodY, qTables, writeDQT, DCHuffmanTables, ACHuffmanTables, writeDHT, optimizeHuffman, (progressiveMode != ImageWriteParam.MODE_DISABLED), numScans, scans, componentIds, HsamplingFactors, VsamplingFactors, QtableSelectors, haveMetadata, restartInterval);
    if (aborted) {
        processWriteAborted();
    } else {
        processImageComplete();
    }
    ios.flush();
    // After a successful write
    currentImage++;
}
Example 32
Project: imageio-ext-master  File: TIFFImageWriter.java View source code
public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) {
    // Check arguments.
    if (inData == null) {
        throw new IllegalArgumentException("inData == null!");
    }
    if (imageType == null) {
        throw new IllegalArgumentException("imageType == null!");
    }
    TIFFImageMetadata outData = null;
    // Obtain a TIFFImageMetadata object.
    if (inData instanceof TIFFImageMetadata) {
        // Create a new metadata object from a clone of the input IFD.
        TIFFIFD inIFD = ((TIFFImageMetadata) inData).getRootIFD();
        outData = new TIFFImageMetadata(inIFD.getShallowClone());
    } else if (Arrays.asList(inData.getMetadataFormatNames()).contains(TIFFImageMetadata.nativeMetadataFormatName)) {
        // Initialize from the native metadata form of the input tree.
        try {
            outData = convertNativeImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
        }
    } else if (inData.isStandardMetadataFormatSupported()) {
        // Initialize from the standard metadata form of the input tree.
        try {
            outData = convertStandardImageMetadata(inData);
        } catch (IIOInvalidTreeException e) {
        }
    }
    // Update the metadata per the image type and param.
    if (outData != null) {
        TIFFImageWriter bogusWriter = new TIFFImageWriter(this.originatingProvider);
        bogusWriter.imageMetadata = outData;
        bogusWriter.param = param;
        SampleModel sm = imageType.getSampleModel();
        try {
            bogusWriter.setupMetadata(imageType.getColorModel(), sm, sm.getWidth(), sm.getHeight());
            return bogusWriter.imageMetadata;
        } catch (IIOException e) {
            return null;
        }
    }
    return outData;
}
Example 33
Project: jajuk-master  File: LastFmArtistThumbnail.java View source code
/**
   * Long part of the populating process. Longest parts (images download) should
   * have already been done by the caller outside the EDT. we only pop the image
   * from the cache here.
   */
private void preLoad() {
    try {
        // Check if artist is null
        String artistUrl = artist.getImageUrl();
        if (StringUtils.isBlank(artistUrl)) {
            return;
        }
        // Download thumb
        URL remote = new URL(artistUrl);
        // Download the picture and store file reference (to
        // generate the popup thumb for ie)
        fCover = DownloadManager.downloadToCache(remote);
        if (fCover == null) {
            Log.warn("Could not read remote file: {{" + remote.toString() + "}}");
            return;
        }
        BufferedImage image = ImageIO.read(fCover);
        if (image == null) {
            Log.warn("Could not read image data in file: {{" + fCover + "}}");
            return;
        }
        ImageIcon downloadedImage = new ImageIcon(image);
        // In artist view, do not reduce artist picture
        if (isArtistView()) {
            ii = downloadedImage;
        } else {
            ii = UtilGUI.getScaledImage(downloadedImage, 100);
        }
        // Free images memory
        downloadedImage.getImage().flush();
        image.flush();
    } catch (IIOException e) {
        Log.warn("Could not read image: {{" + artist.getImageUrl() + "}} Cache: {{" + fCover + "}}", e.getMessage());
    } catch (UnknownHostException e) {
        Log.warn("Could not contact host for loading images: {{" + e.getMessage() + "}}");
    } catch (Exception e) {
        Log.error(e);
    }
}
Example 34
Project: java-image-processing-survival-guide-master  File: ImageConversionJaiTest.java View source code
// ======================================================================
// JPEG CMYK Images
// ======================================================================
/**
     * Process the JPEGs with CMYK color space and store them as JPEG again.
     */
@Test
// javax.imageio.IIOException: Unsupported Image Type
@Ignore
public void testProcessCMYKImages() throws Exception {
    String formatName = "jpeg";
    List<File> sourceImageFileList = new ArrayList<File>();
    sourceImageFileList.add(getImageFile("jpg", "test-image-cmyk-lzw.jpg"));
    sourceImageFileList.add(getImageFile("jpg", "test-image-cmyk-uncompressed.jpg"));
    for (File sourceImageFile : sourceImageFileList) {
        BufferedImage bufferedImage = createBufferedImage(sourceImageFile);
        assertValidBufferedImage(bufferedImage);
        File targetImageFile = createOutputFileName("testProcessCMYKImages", sourceImageFile, formatName);
        writeBufferedImage(resample(bufferedImage, 320, 320), formatName, targetImageFile);
    }
}
Example 35
Project: JDK-master  File: JPEGImageWriter.java View source code
private void writeOnThread(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (ios == null) {
        throw new IllegalStateException("Output has not been set!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image is null!");
    }
    // if streamMetadata is not null, issue a warning
    if (streamMetadata != null) {
        warningOccurred(WARNING_STREAM_METADATA_IGNORED);
    }
    // Obtain the raster and image, if there is one
    boolean rasterOnly = image.hasRaster();
    RenderedImage rimage = null;
    if (rasterOnly) {
        srcRas = image.getRaster();
    } else {
        rimage = image.getRenderedImage();
        if (rimage instanceof BufferedImage) {
            // Use the Raster directly.
            srcRas = ((BufferedImage) rimage).getRaster();
        } else if (rimage.getNumXTiles() == 1 && rimage.getNumYTiles() == 1) {
            // Get the unique tile.
            srcRas = rimage.getTile(rimage.getMinTileX(), rimage.getMinTileY());
            // as the tile dimensions might differ.
            if (srcRas.getWidth() != rimage.getWidth() || srcRas.getHeight() != rimage.getHeight()) {
                srcRas = srcRas.createChild(srcRas.getMinX(), srcRas.getMinY(), rimage.getWidth(), rimage.getHeight(), srcRas.getMinX(), srcRas.getMinY(), null);
            }
        } else {
            // Image is tiled so get a contiguous raster by copying.
            srcRas = rimage.getData();
        }
    }
    // Now determine if we are using a band subset
    // By default, we are using all source bands
    int numSrcBands = srcRas.getNumBands();
    indexed = false;
    indexCM = null;
    ColorModel cm = null;
    ColorSpace cs = null;
    isAlphaPremultiplied = false;
    srcCM = null;
    if (!rasterOnly) {
        cm = rimage.getColorModel();
        if (cm != null) {
            cs = cm.getColorSpace();
            if (cm instanceof IndexColorModel) {
                indexed = true;
                indexCM = (IndexColorModel) cm;
                numSrcBands = cm.getNumComponents();
            }
            if (cm.isAlphaPremultiplied()) {
                isAlphaPremultiplied = true;
                srcCM = cm;
            }
        }
    }
    srcBands = JPEG.bandOffsets[numSrcBands - 1];
    int numBandsUsed = numSrcBands;
    if (param != null) {
        int[] sBands = param.getSourceBands();
        if (sBands != null) {
            if (indexed) {
                warningOccurred(WARNING_NO_BANDS_ON_INDEXED);
            } else {
                srcBands = sBands;
                numBandsUsed = srcBands.length;
                if (numBandsUsed > numSrcBands) {
                    throw new IIOException("ImageWriteParam specifies too many source bands");
                }
            }
        }
    }
    boolean usingBandSubset = (numBandsUsed != numSrcBands);
    boolean fullImage = ((!rasterOnly) && (!usingBandSubset));
    int[] bandSizes = null;
    if (!indexed) {
        bandSizes = srcRas.getSampleModel().getSampleSize();
        // If this is a subset, we must adjust bandSizes
        if (usingBandSubset) {
            int[] temp = new int[numBandsUsed];
            for (int i = 0; i < numBandsUsed; i++) {
                temp[i] = bandSizes[srcBands[i]];
            }
            bandSizes = temp;
        }
    } else {
        int[] tempSize = srcRas.getSampleModel().getSampleSize();
        bandSizes = new int[numSrcBands];
        for (int i = 0; i < numSrcBands; i++) {
            // All the same
            bandSizes[i] = tempSize[0];
        }
    }
    for (int i = 0; i < bandSizes.length; i++) {
        // per sample.
        if (bandSizes[i] > 8) {
            throw new IIOException("Sample size must be <= 8");
        }
        // to 8-bit.
        if (indexed) {
            bandSizes[i] = 8;
        }
    }
    if (debug) {
        System.out.println("numSrcBands is " + numSrcBands);
        System.out.println("numBandsUsed is " + numBandsUsed);
        System.out.println("usingBandSubset is " + usingBandSubset);
        System.out.println("fullImage is " + fullImage);
        System.out.print("Band sizes:");
        for (int i = 0; i < bandSizes.length; i++) {
            System.out.print(" " + bandSizes[i]);
        }
        System.out.println();
    }
    // Destination type, if there is one
    ImageTypeSpecifier destType = null;
    if (param != null) {
        destType = param.getDestinationType();
        // Ignore dest type if we are writing a complete image
        if ((fullImage) && (destType != null)) {
            warningOccurred(WARNING_DEST_IGNORED);
            destType = null;
        }
    }
    // Examine the param
    sourceXOffset = srcRas.getMinX();
    sourceYOffset = srcRas.getMinY();
    int imageWidth = srcRas.getWidth();
    int imageHeight = srcRas.getHeight();
    sourceWidth = imageWidth;
    sourceHeight = imageHeight;
    int periodX = 1;
    int periodY = 1;
    int gridX = 0;
    int gridY = 0;
    JPEGQTable[] qTables = null;
    JPEGHuffmanTable[] DCHuffmanTables = null;
    JPEGHuffmanTable[] ACHuffmanTables = null;
    boolean optimizeHuffman = false;
    JPEGImageWriteParam jparam = null;
    int progressiveMode = ImageWriteParam.MODE_DISABLED;
    if (param != null) {
        Rectangle sourceRegion = param.getSourceRegion();
        if (sourceRegion != null) {
            Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
            sourceRegion = sourceRegion.intersection(imageBounds);
            sourceXOffset = sourceRegion.x;
            sourceYOffset = sourceRegion.y;
            sourceWidth = sourceRegion.width;
            sourceHeight = sourceRegion.height;
        }
        if (sourceWidth + sourceXOffset > imageWidth) {
            sourceWidth = imageWidth - sourceXOffset;
        }
        if (sourceHeight + sourceYOffset > imageHeight) {
            sourceHeight = imageHeight - sourceYOffset;
        }
        periodX = param.getSourceXSubsampling();
        periodY = param.getSourceYSubsampling();
        gridX = param.getSubsamplingXOffset();
        gridY = param.getSubsamplingYOffset();
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        progressiveMode = param.getProgressiveMode();
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
            optimizeHuffman = jparam.getOptimizeHuffmanTables();
        }
    }
    // Now examine the metadata
    IIOMetadata mdata = image.getMetadata();
    if (mdata != null) {
        if (mdata instanceof JPEGMetadata) {
            metadata = (JPEGMetadata) mdata;
            if (debug) {
                System.out.println("We have metadata, and it's JPEG metadata");
            }
        } else {
            if (!rasterOnly) {
                ImageTypeSpecifier type = destType;
                if (type == null) {
                    type = new ImageTypeSpecifier(rimage);
                }
                metadata = (JPEGMetadata) convertImageMetadata(mdata, type, param);
            } else {
                warningOccurred(WARNING_METADATA_NOT_JPEG_FOR_RASTER);
            }
        }
    }
    // First set a default state
    // If it's there, use it
    ignoreJFIF = false;
    // If it's there, use it
    ignoreAdobe = false;
    // Change if needed
    newAdobeTransform = JPEG.ADOBE_IMPOSSIBLE;
    writeDefaultJFIF = false;
    writeAdobe = false;
    // By default we'll do no conversion:
    int inCsType = JPEG.JCS_UNKNOWN;
    int outCsType = JPEG.JCS_UNKNOWN;
    JFIFMarkerSegment jfif = null;
    AdobeMarkerSegment adobe = null;
    SOFMarkerSegment sof = null;
    if (metadata != null) {
        jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        adobe = (AdobeMarkerSegment) metadata.findMarkerSegment(AdobeMarkerSegment.class, true);
        sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
    }
    // By default don't write one
    iccProfile = null;
    // PhotoYCC does this
    convertTosRGB = false;
    converted = null;
    if (destType != null) {
        if (numBandsUsed != destType.getNumBands()) {
            throw new IIOException("Number of source bands != number of destination bands");
        }
        cs = destType.getColorModel().getColorSpace();
        // Check the metadata against the destination type
        if (metadata != null) {
            checkSOFBands(sof, numBandsUsed);
            checkJFIF(jfif, destType, false);
            // Do we want to write an ICC profile?
            if ((jfif != null) && (ignoreJFIF == false)) {
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            }
            checkAdobe(adobe, destType, false);
        } else {
            // If we can add a JFIF or an Adobe marker segment, do so
            if (JPEG.isJFIFcompliant(destType, false)) {
                writeDefaultJFIF = true;
                // Do we want to write an ICC profile?
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            } else {
                int transform = JPEG.transformForType(destType, false);
                if (transform != JPEG.ADOBE_IMPOSSIBLE) {
                    writeAdobe = true;
                    newAdobeTransform = transform;
                }
            }
            // re-create the metadata
            metadata = new JPEGMetadata(destType, null, this);
        }
        inCsType = getSrcCSType(destType);
        outCsType = getDefaultDestCSType(destType);
    } else {
        // no destination type
        if (metadata == null) {
            if (fullImage) {
                // no dest, no metadata, full image
                // Use default metadata matching the image and param
                metadata = new JPEGMetadata(new ImageTypeSpecifier(rimage), param, this);
                if (metadata.findMarkerSegment(JFIFMarkerSegment.class, true) != null) {
                    cs = rimage.getColorModel().getColorSpace();
                    if (JPEG.isNonStandardICC(cs)) {
                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                    }
                }
                inCsType = getSrcCSType(rimage);
                outCsType = getDefaultDestCSType(rimage);
            }
        // else no dest, no metadata, not an image,
        // so no special headers, no color conversion
        } else {
            // no dest type, but there is metadata
            checkSOFBands(sof, numBandsUsed);
            if (fullImage) {
                // no dest, metadata, image
                // Check that the metadata and the image match
                ImageTypeSpecifier inputType = new ImageTypeSpecifier(rimage);
                inCsType = getSrcCSType(rimage);
                if (cm != null) {
                    boolean alpha = cm.hasAlpha();
                    switch(cs.getType()) {
                        case ColorSpace.TYPE_GRAY:
                            if (!alpha) {
                                outCsType = JPEG.JCS_GRAYSCALE;
                            } else {
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                            // out colorspace remains unknown
                            }
                            if ((adobe != null) && (adobe.transform != JPEG.ADOBE_UNKNOWN)) {
                                newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                            }
                            break;
                        case ColorSpace.TYPE_RGB:
                            if (!alpha) {
                                if (jfif != null) {
                                    outCsType = JPEG.JCS_YCbCr;
                                    if (JPEG.isNonStandardICC(cs) || ((cs instanceof ICC_ColorSpace) && (jfif.iccSegment != null))) {
                                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                                    }
                                } else if (adobe != null) {
                                    switch(adobe.transform) {
                                        case JPEG.ADOBE_UNKNOWN:
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                        case JPEG.ADOBE_YCC:
                                            outCsType = JPEG.JCS_YCbCr;
                                            break;
                                        default:
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                    }
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        if (subsampled) {
                                            outCsType = JPEG.JCS_YCbCr;
                                        } else {
                                            outCsType = JPEG.JCS_RGB;
                                        }
                                    }
                                }
                            } else {
                                // RGBA
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                                if (adobe != null) {
                                    if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                        newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                        warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                    }
                                    outCsType = JPEG.JCS_RGBA;
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        outCsType = subsampled ? JPEG.JCS_YCbCrA : JPEG.JCS_RGBA;
                                    }
                                }
                            }
                            break;
                        case ColorSpace.TYPE_3CLR:
                            if (cs == JPEG.JCS.getYCC()) {
                                if (!alpha) {
                                    if (jfif != null) {
                                        convertTosRGB = true;
                                        convertOp = new ColorConvertOp(cs, JPEG.JCS.sRGB, null);
                                        outCsType = JPEG.JCS_YCbCr;
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_YCC) {
                                            newAdobeTransform = JPEG.ADOBE_YCC;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                        outCsType = JPEG.JCS_YCC;
                                    } else {
                                        outCsType = JPEG.JCS_YCC;
                                    }
                                } else {
                                    // PhotoYCCA
                                    if (jfif != null) {
                                        ignoreJFIF = true;
                                        warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                    }
                                    outCsType = JPEG.JCS_YCCA;
                                }
                            }
                    }
                }
            }
        // else no dest, metadata, not an image.  Defaults ok
        }
    }
    boolean metadataProgressive = false;
    int[] scans = null;
    if (metadata != null) {
        if (sof == null) {
            sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
        }
        if ((sof != null) && (sof.tag == JPEG.SOF2)) {
            metadataProgressive = true;
            if (progressiveMode == ImageWriteParam.MODE_COPY_FROM_METADATA) {
                // Might still be null
                scans = collectScans(metadata, sof);
            } else {
                numScans = 0;
            }
        }
        if (jfif == null) {
            jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        }
    }
    thumbnails = image.getThumbnails();
    int numThumbs = image.getNumThumbnails();
    forceJFIF = false;
    // then thumbnails can be written
    if (!writeDefaultJFIF) {
        // If there is no metadata, then we can't write thumbnails
        if (metadata == null) {
            thumbnails = null;
            if (numThumbs != 0) {
                warningOccurred(WARNING_IGNORING_THUMBS);
            }
        } else {
            // then the user must specify JFIF on the metadata
            if (fullImage == false) {
                if (jfif == null) {
                    // Or we can't include thumbnails
                    thumbnails = null;
                    if (numThumbs != 0) {
                        warningOccurred(WARNING_IGNORING_THUMBS);
                    }
                }
            } else {
                // It is a full image, and there is metadata
                if (jfif == null) {
                    // Can it have JFIF?
                    if ((outCsType == JPEG.JCS_GRAYSCALE) || (outCsType == JPEG.JCS_YCbCr)) {
                        if (numThumbs != 0) {
                            forceJFIF = true;
                            warningOccurred(WARNING_FORCING_JFIF);
                        }
                    } else {
                        // Nope, not JFIF-compatible
                        thumbnails = null;
                        if (numThumbs != 0) {
                            warningOccurred(WARNING_IGNORING_THUMBS);
                        }
                    }
                }
            }
        }
    }
    // Set up a boolean to indicate whether we need to call back to
    // write metadata
    boolean haveMetadata = ((metadata != null) || writeDefaultJFIF || writeAdobe);
    // Now that we have dealt with metadata, finalize our tables set up
    // Are we going to write tables?  By default, yes.
    boolean writeDQT = true;
    boolean writeDHT = true;
    // But if the metadata has no tables, no.
    DQTMarkerSegment dqt = null;
    DHTMarkerSegment dht = null;
    int restartInterval = 0;
    if (metadata != null) {
        dqt = (DQTMarkerSegment) metadata.findMarkerSegment(DQTMarkerSegment.class, true);
        dht = (DHTMarkerSegment) metadata.findMarkerSegment(DHTMarkerSegment.class, true);
        DRIMarkerSegment dri = (DRIMarkerSegment) metadata.findMarkerSegment(DRIMarkerSegment.class, true);
        if (dri != null) {
            restartInterval = dri.restartInterval;
        }
        if (dqt == null) {
            writeDQT = false;
        }
        if (dht == null) {
            // Ignored if optimizeHuffman is true
            writeDHT = false;
        }
    }
    // to use
    if (qTables == null) {
        // Get them from metadata, or use defaults
        if (dqt != null) {
            qTables = collectQTablesFromMetadata(metadata);
        } else if (streamQTables != null) {
            qTables = streamQTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // If we are optimizing, we don't want any tables.
    if (optimizeHuffman == false) {
        // If they were for progressive scans, we can't use them.
        if ((dht != null) && (metadataProgressive == false)) {
            DCHuffmanTables = collectHTablesFromMetadata(metadata, true);
            ACHuffmanTables = collectHTablesFromMetadata(metadata, false);
        } else if (streamDCHuffmanTables != null) {
            DCHuffmanTables = streamDCHuffmanTables;
            ACHuffmanTables = streamACHuffmanTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            DCHuffmanTables = jparam.getDCHuffmanTables();
            ACHuffmanTables = jparam.getACHuffmanTables();
        } else {
            DCHuffmanTables = JPEG.getDefaultHuffmanTables(true);
            ACHuffmanTables = JPEG.getDefaultHuffmanTables(false);
        }
    }
    // By default, ids are 1 - N, no subsampling
    int[] componentIds = new int[numBandsUsed];
    int[] HsamplingFactors = new int[numBandsUsed];
    int[] VsamplingFactors = new int[numBandsUsed];
    int[] QtableSelectors = new int[numBandsUsed];
    for (int i = 0; i < numBandsUsed; i++) {
        // JFIF compatible
        componentIds[i] = i + 1;
        HsamplingFactors[i] = 1;
        VsamplingFactors[i] = 1;
        QtableSelectors[i] = 0;
    }
    // Now override them with the contents of sof, if there is one,
    if (sof != null) {
        for (int i = 0; i < numBandsUsed; i++) {
            if (forceJFIF == false) {
                // else use JFIF-compatible default
                componentIds[i] = sof.componentSpecs[i].componentId;
            }
            HsamplingFactors[i] = sof.componentSpecs[i].HsamplingFactor;
            VsamplingFactors[i] = sof.componentSpecs[i].VsamplingFactor;
            QtableSelectors[i] = sof.componentSpecs[i].QtableSelector;
        }
    }
    sourceXOffset += gridX;
    sourceWidth -= gridX;
    sourceYOffset += gridY;
    sourceHeight -= gridY;
    int destWidth = (sourceWidth + periodX - 1) / periodX;
    int destHeight = (sourceHeight + periodY - 1) / periodY;
    // Create an appropriate 1-line databuffer for writing
    int lineSize = sourceWidth * numBandsUsed;
    DataBufferByte buffer = new DataBufferByte(lineSize);
    // Create a raster from that
    int[] bandOffs = JPEG.bandOffsets[numBandsUsed - 1];
    raster = Raster.createInterleavedRaster(buffer, sourceWidth, 1, lineSize, numBandsUsed, bandOffs, null);
    // Call the writer, who will call back for every scanline
    processImageStarted(currentImage);
    boolean aborted = false;
    if (debug) {
        System.out.println("inCsType: " + inCsType);
        System.out.println("outCsType: " + outCsType);
    }
    // Note that getData disables acceleration on buffer, but it is
    // just a 1-line intermediate data transfer buffer that does not
    // affect the acceleration of the source image.
    aborted = writeImage(structPointer, buffer.getData(), inCsType, outCsType, numBandsUsed, bandSizes, sourceWidth, destWidth, destHeight, periodX, periodY, qTables, writeDQT, DCHuffmanTables, ACHuffmanTables, writeDHT, optimizeHuffman, (progressiveMode != ImageWriteParam.MODE_DISABLED), numScans, scans, componentIds, HsamplingFactors, VsamplingFactors, QtableSelectors, haveMetadata, restartInterval);
    cbLock.lock();
    try {
        if (aborted) {
            processWriteAborted();
        } else {
            processImageComplete();
        }
        ios.flush();
    } finally {
        cbLock.unlock();
    }
    // After a successful write
    currentImage++;
}
Example 36
Project: jdk7u-jdk-master  File: JPEGImageWriter.java View source code
private void writeOnThread(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (ios == null) {
        throw new IllegalStateException("Output has not been set!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image is null!");
    }
    // if streamMetadata is not null, issue a warning
    if (streamMetadata != null) {
        warningOccurred(WARNING_STREAM_METADATA_IGNORED);
    }
    // Obtain the raster and image, if there is one
    boolean rasterOnly = image.hasRaster();
    RenderedImage rimage = null;
    if (rasterOnly) {
        srcRas = image.getRaster();
    } else {
        rimage = image.getRenderedImage();
        if (rimage instanceof BufferedImage) {
            // Use the Raster directly.
            srcRas = ((BufferedImage) rimage).getRaster();
        } else if (rimage.getNumXTiles() == 1 && rimage.getNumYTiles() == 1) {
            // Get the unique tile.
            srcRas = rimage.getTile(rimage.getMinTileX(), rimage.getMinTileY());
            // as the tile dimensions might differ.
            if (srcRas.getWidth() != rimage.getWidth() || srcRas.getHeight() != rimage.getHeight()) {
                srcRas = srcRas.createChild(srcRas.getMinX(), srcRas.getMinY(), rimage.getWidth(), rimage.getHeight(), srcRas.getMinX(), srcRas.getMinY(), null);
            }
        } else {
            // Image is tiled so get a contiguous raster by copying.
            srcRas = rimage.getData();
        }
    }
    // Now determine if we are using a band subset
    // By default, we are using all source bands
    int numSrcBands = srcRas.getNumBands();
    indexed = false;
    indexCM = null;
    ColorModel cm = null;
    ColorSpace cs = null;
    isAlphaPremultiplied = false;
    srcCM = null;
    if (!rasterOnly) {
        cm = rimage.getColorModel();
        if (cm != null) {
            cs = cm.getColorSpace();
            if (cm instanceof IndexColorModel) {
                indexed = true;
                indexCM = (IndexColorModel) cm;
                numSrcBands = cm.getNumComponents();
            }
            if (cm.isAlphaPremultiplied()) {
                isAlphaPremultiplied = true;
                srcCM = cm;
            }
        }
    }
    srcBands = JPEG.bandOffsets[numSrcBands - 1];
    int numBandsUsed = numSrcBands;
    if (param != null) {
        int[] sBands = param.getSourceBands();
        if (sBands != null) {
            if (indexed) {
                warningOccurred(WARNING_NO_BANDS_ON_INDEXED);
            } else {
                srcBands = sBands;
                numBandsUsed = srcBands.length;
                if (numBandsUsed > numSrcBands) {
                    throw new IIOException("ImageWriteParam specifies too many source bands");
                }
            }
        }
    }
    boolean usingBandSubset = (numBandsUsed != numSrcBands);
    boolean fullImage = ((!rasterOnly) && (!usingBandSubset));
    int[] bandSizes = null;
    if (!indexed) {
        bandSizes = srcRas.getSampleModel().getSampleSize();
        // If this is a subset, we must adjust bandSizes
        if (usingBandSubset) {
            int[] temp = new int[numBandsUsed];
            for (int i = 0; i < numBandsUsed; i++) {
                temp[i] = bandSizes[srcBands[i]];
            }
            bandSizes = temp;
        }
    } else {
        int[] tempSize = srcRas.getSampleModel().getSampleSize();
        bandSizes = new int[numSrcBands];
        for (int i = 0; i < numSrcBands; i++) {
            // All the same
            bandSizes[i] = tempSize[0];
        }
    }
    for (int i = 0; i < bandSizes.length; i++) {
        // per sample.
        if (bandSizes[i] > 8) {
            throw new IIOException("Sample size must be <= 8");
        }
        // to 8-bit.
        if (indexed) {
            bandSizes[i] = 8;
        }
    }
    if (debug) {
        System.out.println("numSrcBands is " + numSrcBands);
        System.out.println("numBandsUsed is " + numBandsUsed);
        System.out.println("usingBandSubset is " + usingBandSubset);
        System.out.println("fullImage is " + fullImage);
        System.out.print("Band sizes:");
        for (int i = 0; i < bandSizes.length; i++) {
            System.out.print(" " + bandSizes[i]);
        }
        System.out.println();
    }
    // Destination type, if there is one
    ImageTypeSpecifier destType = null;
    if (param != null) {
        destType = param.getDestinationType();
        // Ignore dest type if we are writing a complete image
        if ((fullImage) && (destType != null)) {
            warningOccurred(WARNING_DEST_IGNORED);
            destType = null;
        }
    }
    // Examine the param
    sourceXOffset = srcRas.getMinX();
    sourceYOffset = srcRas.getMinY();
    int imageWidth = srcRas.getWidth();
    int imageHeight = srcRas.getHeight();
    sourceWidth = imageWidth;
    sourceHeight = imageHeight;
    int periodX = 1;
    int periodY = 1;
    int gridX = 0;
    int gridY = 0;
    JPEGQTable[] qTables = null;
    JPEGHuffmanTable[] DCHuffmanTables = null;
    JPEGHuffmanTable[] ACHuffmanTables = null;
    boolean optimizeHuffman = false;
    JPEGImageWriteParam jparam = null;
    int progressiveMode = ImageWriteParam.MODE_DISABLED;
    if (param != null) {
        Rectangle sourceRegion = param.getSourceRegion();
        if (sourceRegion != null) {
            Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
            sourceRegion = sourceRegion.intersection(imageBounds);
            sourceXOffset = sourceRegion.x;
            sourceYOffset = sourceRegion.y;
            sourceWidth = sourceRegion.width;
            sourceHeight = sourceRegion.height;
        }
        if (sourceWidth + sourceXOffset > imageWidth) {
            sourceWidth = imageWidth - sourceXOffset;
        }
        if (sourceHeight + sourceYOffset > imageHeight) {
            sourceHeight = imageHeight - sourceYOffset;
        }
        periodX = param.getSourceXSubsampling();
        periodY = param.getSourceYSubsampling();
        gridX = param.getSubsamplingXOffset();
        gridY = param.getSubsamplingYOffset();
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        progressiveMode = param.getProgressiveMode();
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
            optimizeHuffman = jparam.getOptimizeHuffmanTables();
        }
    }
    // Now examine the metadata
    IIOMetadata mdata = image.getMetadata();
    if (mdata != null) {
        if (mdata instanceof JPEGMetadata) {
            metadata = (JPEGMetadata) mdata;
            if (debug) {
                System.out.println("We have metadata, and it's JPEG metadata");
            }
        } else {
            if (!rasterOnly) {
                ImageTypeSpecifier type = destType;
                if (type == null) {
                    type = new ImageTypeSpecifier(rimage);
                }
                metadata = (JPEGMetadata) convertImageMetadata(mdata, type, param);
            } else {
                warningOccurred(WARNING_METADATA_NOT_JPEG_FOR_RASTER);
            }
        }
    }
    // First set a default state
    // If it's there, use it
    ignoreJFIF = false;
    // If it's there, use it
    ignoreAdobe = false;
    // Change if needed
    newAdobeTransform = JPEG.ADOBE_IMPOSSIBLE;
    writeDefaultJFIF = false;
    writeAdobe = false;
    // By default we'll do no conversion:
    int inCsType = JPEG.JCS_UNKNOWN;
    int outCsType = JPEG.JCS_UNKNOWN;
    JFIFMarkerSegment jfif = null;
    AdobeMarkerSegment adobe = null;
    SOFMarkerSegment sof = null;
    if (metadata != null) {
        jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        adobe = (AdobeMarkerSegment) metadata.findMarkerSegment(AdobeMarkerSegment.class, true);
        sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
    }
    // By default don't write one
    iccProfile = null;
    // PhotoYCC does this
    convertTosRGB = false;
    converted = null;
    if (destType != null) {
        if (numBandsUsed != destType.getNumBands()) {
            throw new IIOException("Number of source bands != number of destination bands");
        }
        cs = destType.getColorModel().getColorSpace();
        // Check the metadata against the destination type
        if (metadata != null) {
            checkSOFBands(sof, numBandsUsed);
            checkJFIF(jfif, destType, false);
            // Do we want to write an ICC profile?
            if ((jfif != null) && (ignoreJFIF == false)) {
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            }
            checkAdobe(adobe, destType, false);
        } else {
            // If we can add a JFIF or an Adobe marker segment, do so
            if (JPEG.isJFIFcompliant(destType, false)) {
                writeDefaultJFIF = true;
                // Do we want to write an ICC profile?
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            } else {
                int transform = JPEG.transformForType(destType, false);
                if (transform != JPEG.ADOBE_IMPOSSIBLE) {
                    writeAdobe = true;
                    newAdobeTransform = transform;
                }
            }
            // re-create the metadata
            metadata = new JPEGMetadata(destType, null, this);
        }
        inCsType = getSrcCSType(destType);
        outCsType = getDefaultDestCSType(destType);
    } else {
        // no destination type
        if (metadata == null) {
            if (fullImage) {
                // no dest, no metadata, full image
                // Use default metadata matching the image and param
                metadata = new JPEGMetadata(new ImageTypeSpecifier(rimage), param, this);
                if (metadata.findMarkerSegment(JFIFMarkerSegment.class, true) != null) {
                    cs = rimage.getColorModel().getColorSpace();
                    if (JPEG.isNonStandardICC(cs)) {
                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                    }
                }
                inCsType = getSrcCSType(rimage);
                outCsType = getDefaultDestCSType(rimage);
            }
        // else no dest, no metadata, not an image,
        // so no special headers, no color conversion
        } else {
            // no dest type, but there is metadata
            checkSOFBands(sof, numBandsUsed);
            if (fullImage) {
                // no dest, metadata, image
                // Check that the metadata and the image match
                ImageTypeSpecifier inputType = new ImageTypeSpecifier(rimage);
                inCsType = getSrcCSType(rimage);
                if (cm != null) {
                    boolean alpha = cm.hasAlpha();
                    switch(cs.getType()) {
                        case ColorSpace.TYPE_GRAY:
                            if (!alpha) {
                                outCsType = JPEG.JCS_GRAYSCALE;
                            } else {
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                            // out colorspace remains unknown
                            }
                            if ((adobe != null) && (adobe.transform != JPEG.ADOBE_UNKNOWN)) {
                                newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                            }
                            break;
                        case ColorSpace.TYPE_RGB:
                            if (!alpha) {
                                if (jfif != null) {
                                    outCsType = JPEG.JCS_YCbCr;
                                    if (JPEG.isNonStandardICC(cs) || ((cs instanceof ICC_ColorSpace) && (jfif.iccSegment != null))) {
                                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                                    }
                                } else if (adobe != null) {
                                    switch(adobe.transform) {
                                        case JPEG.ADOBE_UNKNOWN:
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                        case JPEG.ADOBE_YCC:
                                            outCsType = JPEG.JCS_YCbCr;
                                            break;
                                        default:
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                    }
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        if (subsampled) {
                                            outCsType = JPEG.JCS_YCbCr;
                                        } else {
                                            outCsType = JPEG.JCS_RGB;
                                        }
                                    }
                                }
                            } else {
                                // RGBA
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                                if (adobe != null) {
                                    if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                        newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                        warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                    }
                                    outCsType = JPEG.JCS_RGBA;
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        outCsType = subsampled ? JPEG.JCS_YCbCrA : JPEG.JCS_RGBA;
                                    }
                                }
                            }
                            break;
                        case ColorSpace.TYPE_3CLR:
                            if (cs == JPEG.JCS.getYCC()) {
                                if (!alpha) {
                                    if (jfif != null) {
                                        convertTosRGB = true;
                                        convertOp = new ColorConvertOp(cs, JPEG.JCS.sRGB, null);
                                        outCsType = JPEG.JCS_YCbCr;
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_YCC) {
                                            newAdobeTransform = JPEG.ADOBE_YCC;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                        outCsType = JPEG.JCS_YCC;
                                    } else {
                                        outCsType = JPEG.JCS_YCC;
                                    }
                                } else {
                                    // PhotoYCCA
                                    if (jfif != null) {
                                        ignoreJFIF = true;
                                        warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                    }
                                    outCsType = JPEG.JCS_YCCA;
                                }
                            }
                    }
                }
            }
        // else no dest, metadata, not an image.  Defaults ok
        }
    }
    boolean metadataProgressive = false;
    int[] scans = null;
    if (metadata != null) {
        if (sof == null) {
            sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
        }
        if ((sof != null) && (sof.tag == JPEG.SOF2)) {
            metadataProgressive = true;
            if (progressiveMode == ImageWriteParam.MODE_COPY_FROM_METADATA) {
                // Might still be null
                scans = collectScans(metadata, sof);
            } else {
                numScans = 0;
            }
        }
        if (jfif == null) {
            jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        }
    }
    thumbnails = image.getThumbnails();
    int numThumbs = image.getNumThumbnails();
    forceJFIF = false;
    // then thumbnails can be written
    if (!writeDefaultJFIF) {
        // If there is no metadata, then we can't write thumbnails
        if (metadata == null) {
            thumbnails = null;
            if (numThumbs != 0) {
                warningOccurred(WARNING_IGNORING_THUMBS);
            }
        } else {
            // then the user must specify JFIF on the metadata
            if (fullImage == false) {
                if (jfif == null) {
                    // Or we can't include thumbnails
                    thumbnails = null;
                    if (numThumbs != 0) {
                        warningOccurred(WARNING_IGNORING_THUMBS);
                    }
                }
            } else {
                // It is a full image, and there is metadata
                if (jfif == null) {
                    // Can it have JFIF?
                    if ((outCsType == JPEG.JCS_GRAYSCALE) || (outCsType == JPEG.JCS_YCbCr)) {
                        if (numThumbs != 0) {
                            forceJFIF = true;
                            warningOccurred(WARNING_FORCING_JFIF);
                        }
                    } else {
                        // Nope, not JFIF-compatible
                        thumbnails = null;
                        if (numThumbs != 0) {
                            warningOccurred(WARNING_IGNORING_THUMBS);
                        }
                    }
                }
            }
        }
    }
    // Set up a boolean to indicate whether we need to call back to
    // write metadata
    boolean haveMetadata = ((metadata != null) || writeDefaultJFIF || writeAdobe);
    // Now that we have dealt with metadata, finalize our tables set up
    // Are we going to write tables?  By default, yes.
    boolean writeDQT = true;
    boolean writeDHT = true;
    // But if the metadata has no tables, no.
    DQTMarkerSegment dqt = null;
    DHTMarkerSegment dht = null;
    int restartInterval = 0;
    if (metadata != null) {
        dqt = (DQTMarkerSegment) metadata.findMarkerSegment(DQTMarkerSegment.class, true);
        dht = (DHTMarkerSegment) metadata.findMarkerSegment(DHTMarkerSegment.class, true);
        DRIMarkerSegment dri = (DRIMarkerSegment) metadata.findMarkerSegment(DRIMarkerSegment.class, true);
        if (dri != null) {
            restartInterval = dri.restartInterval;
        }
        if (dqt == null) {
            writeDQT = false;
        }
        if (dht == null) {
            // Ignored if optimizeHuffman is true
            writeDHT = false;
        }
    }
    // to use
    if (qTables == null) {
        // Get them from metadata, or use defaults
        if (dqt != null) {
            qTables = collectQTablesFromMetadata(metadata);
        } else if (streamQTables != null) {
            qTables = streamQTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // If we are optimizing, we don't want any tables.
    if (optimizeHuffman == false) {
        // If they were for progressive scans, we can't use them.
        if ((dht != null) && (metadataProgressive == false)) {
            DCHuffmanTables = collectHTablesFromMetadata(metadata, true);
            ACHuffmanTables = collectHTablesFromMetadata(metadata, false);
        } else if (streamDCHuffmanTables != null) {
            DCHuffmanTables = streamDCHuffmanTables;
            ACHuffmanTables = streamACHuffmanTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            DCHuffmanTables = jparam.getDCHuffmanTables();
            ACHuffmanTables = jparam.getACHuffmanTables();
        } else {
            DCHuffmanTables = JPEG.getDefaultHuffmanTables(true);
            ACHuffmanTables = JPEG.getDefaultHuffmanTables(false);
        }
    }
    // By default, ids are 1 - N, no subsampling
    int[] componentIds = new int[numBandsUsed];
    int[] HsamplingFactors = new int[numBandsUsed];
    int[] VsamplingFactors = new int[numBandsUsed];
    int[] QtableSelectors = new int[numBandsUsed];
    for (int i = 0; i < numBandsUsed; i++) {
        // JFIF compatible
        componentIds[i] = i + 1;
        HsamplingFactors[i] = 1;
        VsamplingFactors[i] = 1;
        QtableSelectors[i] = 0;
    }
    // Now override them with the contents of sof, if there is one,
    if (sof != null) {
        for (int i = 0; i < numBandsUsed; i++) {
            if (forceJFIF == false) {
                // else use JFIF-compatible default
                componentIds[i] = sof.componentSpecs[i].componentId;
            }
            HsamplingFactors[i] = sof.componentSpecs[i].HsamplingFactor;
            VsamplingFactors[i] = sof.componentSpecs[i].VsamplingFactor;
            QtableSelectors[i] = sof.componentSpecs[i].QtableSelector;
        }
    }
    sourceXOffset += gridX;
    sourceWidth -= gridX;
    sourceYOffset += gridY;
    sourceHeight -= gridY;
    int destWidth = (sourceWidth + periodX - 1) / periodX;
    int destHeight = (sourceHeight + periodY - 1) / periodY;
    // Create an appropriate 1-line databuffer for writing
    int lineSize = sourceWidth * numBandsUsed;
    DataBufferByte buffer = new DataBufferByte(lineSize);
    // Create a raster from that
    int[] bandOffs = JPEG.bandOffsets[numBandsUsed - 1];
    raster = Raster.createInterleavedRaster(buffer, sourceWidth, 1, lineSize, numBandsUsed, bandOffs, null);
    // Call the writer, who will call back for every scanline
    processImageStarted(currentImage);
    boolean aborted = false;
    if (debug) {
        System.out.println("inCsType: " + inCsType);
        System.out.println("outCsType: " + outCsType);
    }
    // Note that getData disables acceleration on buffer, but it is
    // just a 1-line intermediate data transfer buffer that does not
    // affect the acceleration of the source image.
    aborted = writeImage(structPointer, buffer.getData(), inCsType, outCsType, numBandsUsed, bandSizes, sourceWidth, destWidth, destHeight, periodX, periodY, qTables, writeDQT, DCHuffmanTables, ACHuffmanTables, writeDHT, optimizeHuffman, (progressiveMode != ImageWriteParam.MODE_DISABLED), numScans, scans, componentIds, HsamplingFactors, VsamplingFactors, QtableSelectors, haveMetadata, restartInterval);
    if (aborted) {
        processWriteAborted();
    } else {
        processImageComplete();
    }
    ios.flush();
    // After a successful write
    currentImage++;
}
Example 37
Project: lichtstrahlen-master  File: LineEditor.java View source code
public void importPuzzleBoard(IBeamsOfLightPuzzleBoard source) throws NumberFormatException, IIOException, IOException {
    GraficFactory gf = new GraficFactory(source);
    ITile<?> currentTile;
    ITileState currentTileState;
    TilePanel tile;
    char c;
    double angle;
    col = source.getWidth();
    row = source.getHeight();
    gl = new GridLayout(row, col);
    tileList.clear();
    tiles = new JPanel(cl);
    tilesPanel = new TilesPanel();
    tilesPanel.setLayout(gl);
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            currentTile = source.getTileAt(j, i);
            tile = createTilePanel(i, j);
            if (currentTile.getClass().getSimpleName().equals("LightTile")) {
                currentTileState = (LightTileState) currentTile.getTileState();
                c = ((LightTileState) currentTileState).getSign();
                switch(c) {
                    case 'n':
                        angle = NORTH;
                        break;
                    case 'e':
                        angle = EAST;
                        break;
                    case 's':
                        angle = SOUTH;
                        break;
                    case 'w':
                        angle = WEST;
                        break;
                    default:
                        angle = 0.0;
                }
                if (gf.isEnd((LightTile) currentTile)) {
                    tile.setImage("resources/themes/moon/light2.png", angle);
                } else {
                    tile.setImage("resources/themes/moon/light1.png", angle);
                }
            }
            if (currentTile.getClass().getSimpleName().equals("NumberTile")) {
                currentTileState = (NumberTileState) currentTile.getTileState();
                int lightPower = ((NumberTileState) currentTileState).getNumber();
                tile.setLightPower(lightPower);
            }
            tileList.add(tile);
            tilesPanel.add(tile);
        }
    }
    tiles.add(tilesPanel, "1");
}
Example 38
Project: LichtstrahlenSpiel-master  File: LineEditor.java View source code
public void importPuzzleBoard(IBeamsOfLightPuzzleBoard source) throws NumberFormatException, IIOException, IOException {
    GraficFactory gf = new GraficFactory(source);
    ITile<?> currentTile;
    ITileState currentTileState;
    TilePanel tile;
    char c;
    double angle;
    col = source.getWidth();
    row = source.getHeight();
    gl = new GridLayout(row, col);
    tileList.clear();
    tiles = new JPanel(cl);
    tilesPanel = new TilesPanel();
    tilesPanel.setLayout(gl);
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            currentTile = source.getTileAt(j, i);
            tile = createTilePanel(i, j);
            if (currentTile.getClass().getSimpleName().equals("LightTile")) {
                currentTileState = (LightTileState) currentTile.getTileState();
                c = ((LightTileState) currentTileState).getSign();
                switch(c) {
                    case 'n':
                        angle = NORTH;
                        break;
                    case 'e':
                        angle = EAST;
                        break;
                    case 's':
                        angle = SOUTH;
                        break;
                    case 'w':
                        angle = WEST;
                        break;
                    default:
                        angle = 0.0;
                }
                if (gf.isEnd((LightTile) currentTile)) {
                    tile.setImage("resources/themes/moon/light2.png", angle);
                } else {
                    tile.setImage("resources/themes/moon/light1.png", angle);
                }
            }
            if (currentTile.getClass().getSimpleName().equals("NumberTile")) {
                currentTileState = (NumberTileState) currentTile.getTileState();
                int lightPower = ((NumberTileState) currentTileState).getNumber();
                tile.setLightPower(lightPower);
            }
            tileList.add(tile);
            tilesPanel.add(tile);
        }
    }
    tiles.add(tilesPanel, "1");
}
Example 39
Project: ManagedRuntimeInitiative-master  File: JPEGImageWriter.java View source code
private void writeOnThread(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (ios == null) {
        throw new IllegalStateException("Output has not been set!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image is null!");
    }
    // if streamMetadata is not null, issue a warning
    if (streamMetadata != null) {
        warningOccurred(WARNING_STREAM_METADATA_IGNORED);
    }
    // Obtain the raster and image, if there is one
    boolean rasterOnly = image.hasRaster();
    RenderedImage rimage = null;
    if (rasterOnly) {
        srcRas = image.getRaster();
    } else {
        rimage = image.getRenderedImage();
        if (rimage instanceof BufferedImage) {
            // Use the Raster directly.
            srcRas = ((BufferedImage) rimage).getRaster();
        } else if (rimage.getNumXTiles() == 1 && rimage.getNumYTiles() == 1) {
            // Get the unique tile.
            srcRas = rimage.getTile(rimage.getMinTileX(), rimage.getMinTileY());
            // as the tile dimensions might differ.
            if (srcRas.getWidth() != rimage.getWidth() || srcRas.getHeight() != rimage.getHeight()) {
                srcRas = srcRas.createChild(srcRas.getMinX(), srcRas.getMinY(), rimage.getWidth(), rimage.getHeight(), srcRas.getMinX(), srcRas.getMinY(), null);
            }
        } else {
            // Image is tiled so get a contiguous raster by copying.
            srcRas = rimage.getData();
        }
    }
    // Now determine if we are using a band subset
    // By default, we are using all source bands
    int numSrcBands = srcRas.getNumBands();
    indexed = false;
    indexCM = null;
    ColorModel cm = null;
    ColorSpace cs = null;
    isAlphaPremultiplied = false;
    srcCM = null;
    if (!rasterOnly) {
        cm = rimage.getColorModel();
        if (cm != null) {
            cs = cm.getColorSpace();
            if (cm instanceof IndexColorModel) {
                indexed = true;
                indexCM = (IndexColorModel) cm;
                numSrcBands = cm.getNumComponents();
            }
            if (cm.isAlphaPremultiplied()) {
                isAlphaPremultiplied = true;
                srcCM = cm;
            }
        }
    }
    srcBands = JPEG.bandOffsets[numSrcBands - 1];
    int numBandsUsed = numSrcBands;
    if (param != null) {
        int[] sBands = param.getSourceBands();
        if (sBands != null) {
            if (indexed) {
                warningOccurred(WARNING_NO_BANDS_ON_INDEXED);
            } else {
                srcBands = sBands;
                numBandsUsed = srcBands.length;
                if (numBandsUsed > numSrcBands) {
                    throw new IIOException("ImageWriteParam specifies too many source bands");
                }
            }
        }
    }
    boolean usingBandSubset = (numBandsUsed != numSrcBands);
    boolean fullImage = ((!rasterOnly) && (!usingBandSubset));
    int[] bandSizes = null;
    if (!indexed) {
        bandSizes = srcRas.getSampleModel().getSampleSize();
        // If this is a subset, we must adjust bandSizes
        if (usingBandSubset) {
            int[] temp = new int[numBandsUsed];
            for (int i = 0; i < numBandsUsed; i++) {
                temp[i] = bandSizes[srcBands[i]];
            }
            bandSizes = temp;
        }
    } else {
        int[] tempSize = srcRas.getSampleModel().getSampleSize();
        bandSizes = new int[numSrcBands];
        for (int i = 0; i < numSrcBands; i++) {
            // All the same
            bandSizes[i] = tempSize[0];
        }
    }
    for (int i = 0; i < bandSizes.length; i++) {
        // per sample.
        if (bandSizes[i] > 8) {
            throw new IIOException("Sample size must be <= 8");
        }
        // to 8-bit.
        if (indexed) {
            bandSizes[i] = 8;
        }
    }
    if (debug) {
        System.out.println("numSrcBands is " + numSrcBands);
        System.out.println("numBandsUsed is " + numBandsUsed);
        System.out.println("usingBandSubset is " + usingBandSubset);
        System.out.println("fullImage is " + fullImage);
        System.out.print("Band sizes:");
        for (int i = 0; i < bandSizes.length; i++) {
            System.out.print(" " + bandSizes[i]);
        }
        System.out.println();
    }
    // Destination type, if there is one
    ImageTypeSpecifier destType = null;
    if (param != null) {
        destType = param.getDestinationType();
        // Ignore dest type if we are writing a complete image
        if ((fullImage) && (destType != null)) {
            warningOccurred(WARNING_DEST_IGNORED);
            destType = null;
        }
    }
    // Examine the param
    sourceXOffset = srcRas.getMinX();
    sourceYOffset = srcRas.getMinY();
    int imageWidth = srcRas.getWidth();
    int imageHeight = srcRas.getHeight();
    sourceWidth = imageWidth;
    sourceHeight = imageHeight;
    int periodX = 1;
    int periodY = 1;
    int gridX = 0;
    int gridY = 0;
    JPEGQTable[] qTables = null;
    JPEGHuffmanTable[] DCHuffmanTables = null;
    JPEGHuffmanTable[] ACHuffmanTables = null;
    boolean optimizeHuffman = false;
    JPEGImageWriteParam jparam = null;
    int progressiveMode = ImageWriteParam.MODE_DISABLED;
    if (param != null) {
        Rectangle sourceRegion = param.getSourceRegion();
        if (sourceRegion != null) {
            Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
            sourceRegion = sourceRegion.intersection(imageBounds);
            sourceXOffset = sourceRegion.x;
            sourceYOffset = sourceRegion.y;
            sourceWidth = sourceRegion.width;
            sourceHeight = sourceRegion.height;
        }
        if (sourceWidth + sourceXOffset > imageWidth) {
            sourceWidth = imageWidth - sourceXOffset;
        }
        if (sourceHeight + sourceYOffset > imageHeight) {
            sourceHeight = imageHeight - sourceYOffset;
        }
        periodX = param.getSourceXSubsampling();
        periodY = param.getSourceYSubsampling();
        gridX = param.getSubsamplingXOffset();
        gridY = param.getSubsamplingYOffset();
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        progressiveMode = param.getProgressiveMode();
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
            optimizeHuffman = jparam.getOptimizeHuffmanTables();
        }
    }
    // Now examine the metadata
    IIOMetadata mdata = image.getMetadata();
    if (mdata != null) {
        if (mdata instanceof JPEGMetadata) {
            metadata = (JPEGMetadata) mdata;
            if (debug) {
                System.out.println("We have metadata, and it's JPEG metadata");
            }
        } else {
            if (!rasterOnly) {
                ImageTypeSpecifier type = destType;
                if (type == null) {
                    type = new ImageTypeSpecifier(rimage);
                }
                metadata = (JPEGMetadata) convertImageMetadata(mdata, type, param);
            } else {
                warningOccurred(WARNING_METADATA_NOT_JPEG_FOR_RASTER);
            }
        }
    }
    // First set a default state
    // If it's there, use it
    ignoreJFIF = false;
    // If it's there, use it
    ignoreAdobe = false;
    // Change if needed
    newAdobeTransform = JPEG.ADOBE_IMPOSSIBLE;
    writeDefaultJFIF = false;
    writeAdobe = false;
    // By default we'll do no conversion:
    int inCsType = JPEG.JCS_UNKNOWN;
    int outCsType = JPEG.JCS_UNKNOWN;
    JFIFMarkerSegment jfif = null;
    AdobeMarkerSegment adobe = null;
    SOFMarkerSegment sof = null;
    if (metadata != null) {
        jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        adobe = (AdobeMarkerSegment) metadata.findMarkerSegment(AdobeMarkerSegment.class, true);
        sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
    }
    // By default don't write one
    iccProfile = null;
    // PhotoYCC does this
    convertTosRGB = false;
    converted = null;
    if (destType != null) {
        if (numBandsUsed != destType.getNumBands()) {
            throw new IIOException("Number of source bands != number of destination bands");
        }
        cs = destType.getColorModel().getColorSpace();
        // Check the metadata against the destination type
        if (metadata != null) {
            checkSOFBands(sof, numBandsUsed);
            checkJFIF(jfif, destType, false);
            // Do we want to write an ICC profile?
            if ((jfif != null) && (ignoreJFIF == false)) {
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            }
            checkAdobe(adobe, destType, false);
        } else {
            // If we can add a JFIF or an Adobe marker segment, do so
            if (JPEG.isJFIFcompliant(destType, false)) {
                writeDefaultJFIF = true;
                // Do we want to write an ICC profile?
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            } else {
                int transform = JPEG.transformForType(destType, false);
                if (transform != JPEG.ADOBE_IMPOSSIBLE) {
                    writeAdobe = true;
                    newAdobeTransform = transform;
                }
            }
            // re-create the metadata
            metadata = new JPEGMetadata(destType, null, this);
        }
        inCsType = getSrcCSType(destType);
        outCsType = getDefaultDestCSType(destType);
    } else {
        // no destination type
        if (metadata == null) {
            if (fullImage) {
                // no dest, no metadata, full image
                // Use default metadata matching the image and param
                metadata = new JPEGMetadata(new ImageTypeSpecifier(rimage), param, this);
                if (metadata.findMarkerSegment(JFIFMarkerSegment.class, true) != null) {
                    cs = rimage.getColorModel().getColorSpace();
                    if (JPEG.isNonStandardICC(cs)) {
                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                    }
                }
                inCsType = getSrcCSType(rimage);
                outCsType = getDefaultDestCSType(rimage);
            }
        // else no dest, no metadata, not an image,
        // so no special headers, no color conversion
        } else {
            // no dest type, but there is metadata
            checkSOFBands(sof, numBandsUsed);
            if (fullImage) {
                // no dest, metadata, image
                // Check that the metadata and the image match
                ImageTypeSpecifier inputType = new ImageTypeSpecifier(rimage);
                inCsType = getSrcCSType(rimage);
                if (cm != null) {
                    boolean alpha = cm.hasAlpha();
                    switch(cs.getType()) {
                        case ColorSpace.TYPE_GRAY:
                            if (!alpha) {
                                outCsType = JPEG.JCS_GRAYSCALE;
                            } else {
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                            // out colorspace remains unknown
                            }
                            if ((adobe != null) && (adobe.transform != JPEG.ADOBE_UNKNOWN)) {
                                newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                            }
                            break;
                        case ColorSpace.TYPE_RGB:
                            if (!alpha) {
                                if (jfif != null) {
                                    outCsType = JPEG.JCS_YCbCr;
                                    if (JPEG.isNonStandardICC(cs) || ((cs instanceof ICC_ColorSpace) && (jfif.iccSegment != null))) {
                                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                                    }
                                } else if (adobe != null) {
                                    switch(adobe.transform) {
                                        case JPEG.ADOBE_UNKNOWN:
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                        case JPEG.ADOBE_YCC:
                                            outCsType = JPEG.JCS_YCbCr;
                                            break;
                                        default:
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                    }
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        if (subsampled) {
                                            outCsType = JPEG.JCS_YCbCr;
                                        } else {
                                            outCsType = JPEG.JCS_RGB;
                                        }
                                    }
                                }
                            } else {
                                // RGBA
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                                if (adobe != null) {
                                    if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                        newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                        warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                    }
                                    outCsType = JPEG.JCS_RGBA;
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        outCsType = subsampled ? JPEG.JCS_YCbCrA : JPEG.JCS_RGBA;
                                    }
                                }
                            }
                            break;
                        case ColorSpace.TYPE_3CLR:
                            if (cs == JPEG.YCC) {
                                if (!alpha) {
                                    if (jfif != null) {
                                        convertTosRGB = true;
                                        convertOp = new ColorConvertOp(cs, JPEG.sRGB, null);
                                        outCsType = JPEG.JCS_YCbCr;
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_YCC) {
                                            newAdobeTransform = JPEG.ADOBE_YCC;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                        outCsType = JPEG.JCS_YCC;
                                    } else {
                                        outCsType = JPEG.JCS_YCC;
                                    }
                                } else {
                                    // PhotoYCCA
                                    if (jfif != null) {
                                        ignoreJFIF = true;
                                        warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                    }
                                    outCsType = JPEG.JCS_YCCA;
                                }
                            }
                    }
                }
            }
        // else no dest, metadata, not an image.  Defaults ok
        }
    }
    boolean metadataProgressive = false;
    int[] scans = null;
    if (metadata != null) {
        if (sof == null) {
            sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
        }
        if ((sof != null) && (sof.tag == JPEG.SOF2)) {
            metadataProgressive = true;
            if (progressiveMode == ImageWriteParam.MODE_COPY_FROM_METADATA) {
                // Might still be null
                scans = collectScans(metadata, sof);
            } else {
                numScans = 0;
            }
        }
        if (jfif == null) {
            jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        }
    }
    thumbnails = image.getThumbnails();
    int numThumbs = image.getNumThumbnails();
    forceJFIF = false;
    // then thumbnails can be written
    if (!writeDefaultJFIF) {
        // If there is no metadata, then we can't write thumbnails
        if (metadata == null) {
            thumbnails = null;
            if (numThumbs != 0) {
                warningOccurred(WARNING_IGNORING_THUMBS);
            }
        } else {
            // then the user must specify JFIF on the metadata
            if (fullImage == false) {
                if (jfif == null) {
                    // Or we can't include thumbnails
                    thumbnails = null;
                    if (numThumbs != 0) {
                        warningOccurred(WARNING_IGNORING_THUMBS);
                    }
                }
            } else {
                // It is a full image, and there is metadata
                if (jfif == null) {
                    // Can it have JFIF?
                    if ((outCsType == JPEG.JCS_GRAYSCALE) || (outCsType == JPEG.JCS_YCbCr)) {
                        if (numThumbs != 0) {
                            forceJFIF = true;
                            warningOccurred(WARNING_FORCING_JFIF);
                        }
                    } else {
                        // Nope, not JFIF-compatible
                        thumbnails = null;
                        if (numThumbs != 0) {
                            warningOccurred(WARNING_IGNORING_THUMBS);
                        }
                    }
                }
            }
        }
    }
    // Set up a boolean to indicate whether we need to call back to
    // write metadata
    boolean haveMetadata = ((metadata != null) || writeDefaultJFIF || writeAdobe);
    // Now that we have dealt with metadata, finalize our tables set up
    // Are we going to write tables?  By default, yes.
    boolean writeDQT = true;
    boolean writeDHT = true;
    // But if the metadata has no tables, no.
    DQTMarkerSegment dqt = null;
    DHTMarkerSegment dht = null;
    int restartInterval = 0;
    if (metadata != null) {
        dqt = (DQTMarkerSegment) metadata.findMarkerSegment(DQTMarkerSegment.class, true);
        dht = (DHTMarkerSegment) metadata.findMarkerSegment(DHTMarkerSegment.class, true);
        DRIMarkerSegment dri = (DRIMarkerSegment) metadata.findMarkerSegment(DRIMarkerSegment.class, true);
        if (dri != null) {
            restartInterval = dri.restartInterval;
        }
        if (dqt == null) {
            writeDQT = false;
        }
        if (dht == null) {
            // Ignored if optimizeHuffman is true
            writeDHT = false;
        }
    }
    // to use
    if (qTables == null) {
        // Get them from metadata, or use defaults
        if (dqt != null) {
            qTables = collectQTablesFromMetadata(metadata);
        } else if (streamQTables != null) {
            qTables = streamQTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // If we are optimizing, we don't want any tables.
    if (optimizeHuffman == false) {
        // If they were for progressive scans, we can't use them.
        if ((dht != null) && (metadataProgressive == false)) {
            DCHuffmanTables = collectHTablesFromMetadata(metadata, true);
            ACHuffmanTables = collectHTablesFromMetadata(metadata, false);
        } else if (streamDCHuffmanTables != null) {
            DCHuffmanTables = streamDCHuffmanTables;
            ACHuffmanTables = streamACHuffmanTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            DCHuffmanTables = jparam.getDCHuffmanTables();
            ACHuffmanTables = jparam.getACHuffmanTables();
        } else {
            DCHuffmanTables = JPEG.getDefaultHuffmanTables(true);
            ACHuffmanTables = JPEG.getDefaultHuffmanTables(false);
        }
    }
    // By default, ids are 1 - N, no subsampling
    int[] componentIds = new int[numBandsUsed];
    int[] HsamplingFactors = new int[numBandsUsed];
    int[] VsamplingFactors = new int[numBandsUsed];
    int[] QtableSelectors = new int[numBandsUsed];
    for (int i = 0; i < numBandsUsed; i++) {
        // JFIF compatible
        componentIds[i] = i + 1;
        HsamplingFactors[i] = 1;
        VsamplingFactors[i] = 1;
        QtableSelectors[i] = 0;
    }
    // Now override them with the contents of sof, if there is one,
    if (sof != null) {
        for (int i = 0; i < numBandsUsed; i++) {
            if (forceJFIF == false) {
                // else use JFIF-compatible default
                componentIds[i] = sof.componentSpecs[i].componentId;
            }
            HsamplingFactors[i] = sof.componentSpecs[i].HsamplingFactor;
            VsamplingFactors[i] = sof.componentSpecs[i].VsamplingFactor;
            QtableSelectors[i] = sof.componentSpecs[i].QtableSelector;
        }
    }
    sourceXOffset += gridX;
    sourceWidth -= gridX;
    sourceYOffset += gridY;
    sourceHeight -= gridY;
    int destWidth = (sourceWidth + periodX - 1) / periodX;
    int destHeight = (sourceHeight + periodY - 1) / periodY;
    // Create an appropriate 1-line databuffer for writing
    int lineSize = sourceWidth * numBandsUsed;
    DataBufferByte buffer = new DataBufferByte(lineSize);
    // Create a raster from that
    int[] bandOffs = JPEG.bandOffsets[numBandsUsed - 1];
    raster = Raster.createInterleavedRaster(buffer, sourceWidth, 1, lineSize, numBandsUsed, bandOffs, null);
    // Call the writer, who will call back for every scanline
    processImageStarted(currentImage);
    boolean aborted = false;
    if (debug) {
        System.out.println("inCsType: " + inCsType);
        System.out.println("outCsType: " + outCsType);
    }
    // Note that getData disables acceleration on buffer, but it is
    // just a 1-line intermediate data transfer buffer that does not
    // affect the acceleration of the source image.
    aborted = writeImage(structPointer, buffer.getData(), inCsType, outCsType, numBandsUsed, bandSizes, sourceWidth, destWidth, destHeight, periodX, periodY, qTables, writeDQT, DCHuffmanTables, ACHuffmanTables, writeDHT, optimizeHuffman, (progressiveMode != ImageWriteParam.MODE_DISABLED), numScans, scans, componentIds, HsamplingFactors, VsamplingFactors, QtableSelectors, haveMetadata, restartInterval);
    if (aborted) {
        processWriteAborted();
    } else {
        processImageComplete();
    }
    ios.flush();
    // After a successful write
    currentImage++;
}
Example 40
Project: OCRaptor-master  File: ImageParser.java View source code
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
    String type = metadata.get(Metadata.CONTENT_TYPE);
    if (type != null) {
        TikaInputStream tikaStream = TikaInputStream.get(stream);
        File imageFile = tikaStream.getFile();
        // what the canonical one is, fix this up.
        if (CANONICAL_BMP_TYPE.toString().equals(type)) {
            type = JAVA_BMP_TYPE.toString();
        }
        try {
            Iterator<ImageReader> iterator = ImageIO.getImageReadersByMIMEType(type);
            if (iterator.hasNext()) {
                ImageReader reader = iterator.next();
                try {
                    ImageInputStream imageStream = ImageIO.createImageInputStream(new CloseShieldInputStream(tikaStream));
                    try {
                        reader.setInput(imageStream);
                        metadata.set(Metadata.IMAGE_WIDTH, Integer.toString(reader.getWidth(0)));
                        metadata.set(Metadata.IMAGE_LENGTH, Integer.toString(reader.getHeight(0)));
                        metadata.set("height", Integer.toString(reader.getHeight(0)));
                        metadata.set("width", Integer.toString(reader.getWidth(0)));
                        loadMetadata(reader.getImageMetadata(0), metadata);
                    } catch (Exception e) {
                    } finally {
                        imageStream.close();
                    }
                } finally {
                    reader.dispose();
                }
            }
            // Translate certain Metadata tags from the ImageIO
            // specific namespace into the general Tika one
            setIfPresent(metadata, "CommentExtensions CommentExtension", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "markerSequence com", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "Data BitsPerSample", Metadata.BITS_PER_SAMPLE);
        } catch (IIOException e) {
            if (!(e.getMessage().equals("Unexpected block type 0!") && type.equals("image/gif"))) {
                throw new TikaException(type + " parse error", e);
            }
        }
        // ------------------------------------------------ //
        // -- ocr image data
        // ------------------------------------------------ //
        XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
        xhtml.startDocument();
        TikaImageHelper helper = new TikaImageHelper(metadata);
        try {
            helper.addImage(imageFile);
            helper.addTextToHandler(xhtml);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (helper != null) {
                helper.close();
            }
        }
        xhtml.endDocument();
    }
}
Example 41
Project: openjdk8-jdk-master  File: JPEGImageWriter.java View source code
private void writeOnThread(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (ios == null) {
        throw new IllegalStateException("Output has not been set!");
    }
    if (image == null) {
        throw new IllegalArgumentException("image is null!");
    }
    // if streamMetadata is not null, issue a warning
    if (streamMetadata != null) {
        warningOccurred(WARNING_STREAM_METADATA_IGNORED);
    }
    // Obtain the raster and image, if there is one
    boolean rasterOnly = image.hasRaster();
    RenderedImage rimage = null;
    if (rasterOnly) {
        srcRas = image.getRaster();
    } else {
        rimage = image.getRenderedImage();
        if (rimage instanceof BufferedImage) {
            // Use the Raster directly.
            srcRas = ((BufferedImage) rimage).getRaster();
        } else if (rimage.getNumXTiles() == 1 && rimage.getNumYTiles() == 1) {
            // Get the unique tile.
            srcRas = rimage.getTile(rimage.getMinTileX(), rimage.getMinTileY());
            // as the tile dimensions might differ.
            if (srcRas.getWidth() != rimage.getWidth() || srcRas.getHeight() != rimage.getHeight()) {
                srcRas = srcRas.createChild(srcRas.getMinX(), srcRas.getMinY(), rimage.getWidth(), rimage.getHeight(), srcRas.getMinX(), srcRas.getMinY(), null);
            }
        } else {
            // Image is tiled so get a contiguous raster by copying.
            srcRas = rimage.getData();
        }
    }
    // Now determine if we are using a band subset
    // By default, we are using all source bands
    int numSrcBands = srcRas.getNumBands();
    indexed = false;
    indexCM = null;
    ColorModel cm = null;
    ColorSpace cs = null;
    isAlphaPremultiplied = false;
    srcCM = null;
    if (!rasterOnly) {
        cm = rimage.getColorModel();
        if (cm != null) {
            cs = cm.getColorSpace();
            if (cm instanceof IndexColorModel) {
                indexed = true;
                indexCM = (IndexColorModel) cm;
                numSrcBands = cm.getNumComponents();
            }
            if (cm.isAlphaPremultiplied()) {
                isAlphaPremultiplied = true;
                srcCM = cm;
            }
        }
    }
    srcBands = JPEG.bandOffsets[numSrcBands - 1];
    int numBandsUsed = numSrcBands;
    if (param != null) {
        int[] sBands = param.getSourceBands();
        if (sBands != null) {
            if (indexed) {
                warningOccurred(WARNING_NO_BANDS_ON_INDEXED);
            } else {
                srcBands = sBands;
                numBandsUsed = srcBands.length;
                if (numBandsUsed > numSrcBands) {
                    throw new IIOException("ImageWriteParam specifies too many source bands");
                }
            }
        }
    }
    boolean usingBandSubset = (numBandsUsed != numSrcBands);
    boolean fullImage = ((!rasterOnly) && (!usingBandSubset));
    int[] bandSizes = null;
    if (!indexed) {
        bandSizes = srcRas.getSampleModel().getSampleSize();
        // If this is a subset, we must adjust bandSizes
        if (usingBandSubset) {
            int[] temp = new int[numBandsUsed];
            for (int i = 0; i < numBandsUsed; i++) {
                temp[i] = bandSizes[srcBands[i]];
            }
            bandSizes = temp;
        }
    } else {
        int[] tempSize = srcRas.getSampleModel().getSampleSize();
        bandSizes = new int[numSrcBands];
        for (int i = 0; i < numSrcBands; i++) {
            // All the same
            bandSizes[i] = tempSize[0];
        }
    }
    for (int i = 0; i < bandSizes.length; i++) {
        // per sample.
        if (bandSizes[i] > 8) {
            throw new IIOException("Sample size must be <= 8");
        }
        // to 8-bit.
        if (indexed) {
            bandSizes[i] = 8;
        }
    }
    if (debug) {
        System.out.println("numSrcBands is " + numSrcBands);
        System.out.println("numBandsUsed is " + numBandsUsed);
        System.out.println("usingBandSubset is " + usingBandSubset);
        System.out.println("fullImage is " + fullImage);
        System.out.print("Band sizes:");
        for (int i = 0; i < bandSizes.length; i++) {
            System.out.print(" " + bandSizes[i]);
        }
        System.out.println();
    }
    // Destination type, if there is one
    ImageTypeSpecifier destType = null;
    if (param != null) {
        destType = param.getDestinationType();
        // Ignore dest type if we are writing a complete image
        if ((fullImage) && (destType != null)) {
            warningOccurred(WARNING_DEST_IGNORED);
            destType = null;
        }
    }
    // Examine the param
    sourceXOffset = srcRas.getMinX();
    sourceYOffset = srcRas.getMinY();
    int imageWidth = srcRas.getWidth();
    int imageHeight = srcRas.getHeight();
    sourceWidth = imageWidth;
    sourceHeight = imageHeight;
    int periodX = 1;
    int periodY = 1;
    int gridX = 0;
    int gridY = 0;
    JPEGQTable[] qTables = null;
    JPEGHuffmanTable[] DCHuffmanTables = null;
    JPEGHuffmanTable[] ACHuffmanTables = null;
    boolean optimizeHuffman = false;
    JPEGImageWriteParam jparam = null;
    int progressiveMode = ImageWriteParam.MODE_DISABLED;
    if (param != null) {
        Rectangle sourceRegion = param.getSourceRegion();
        if (sourceRegion != null) {
            Rectangle imageBounds = new Rectangle(sourceXOffset, sourceYOffset, sourceWidth, sourceHeight);
            sourceRegion = sourceRegion.intersection(imageBounds);
            sourceXOffset = sourceRegion.x;
            sourceYOffset = sourceRegion.y;
            sourceWidth = sourceRegion.width;
            sourceHeight = sourceRegion.height;
        }
        if (sourceWidth + sourceXOffset > imageWidth) {
            sourceWidth = imageWidth - sourceXOffset;
        }
        if (sourceHeight + sourceYOffset > imageHeight) {
            sourceHeight = imageHeight - sourceYOffset;
        }
        periodX = param.getSourceXSubsampling();
        periodY = param.getSourceYSubsampling();
        gridX = param.getSubsamplingXOffset();
        gridY = param.getSubsamplingYOffset();
        switch(param.getCompressionMode()) {
            case ImageWriteParam.MODE_DISABLED:
                throw new IIOException("JPEG compression cannot be disabled");
            case ImageWriteParam.MODE_EXPLICIT:
                float quality = param.getCompressionQuality();
                quality = JPEG.convertToLinearQuality(quality);
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Luminance.getScaledInstance(quality, true);
                qTables[1] = JPEGQTable.K2Chrominance.getScaledInstance(quality, true);
                break;
            case ImageWriteParam.MODE_DEFAULT:
                qTables = new JPEGQTable[2];
                qTables[0] = JPEGQTable.K1Div2Luminance;
                qTables[1] = JPEGQTable.K2Div2Chrominance;
                break;
        }
        progressiveMode = param.getProgressiveMode();
        if (param instanceof JPEGImageWriteParam) {
            jparam = (JPEGImageWriteParam) param;
            optimizeHuffman = jparam.getOptimizeHuffmanTables();
        }
    }
    // Now examine the metadata
    IIOMetadata mdata = image.getMetadata();
    if (mdata != null) {
        if (mdata instanceof JPEGMetadata) {
            metadata = (JPEGMetadata) mdata;
            if (debug) {
                System.out.println("We have metadata, and it's JPEG metadata");
            }
        } else {
            if (!rasterOnly) {
                ImageTypeSpecifier type = destType;
                if (type == null) {
                    type = new ImageTypeSpecifier(rimage);
                }
                metadata = (JPEGMetadata) convertImageMetadata(mdata, type, param);
            } else {
                warningOccurred(WARNING_METADATA_NOT_JPEG_FOR_RASTER);
            }
        }
    }
    // First set a default state
    // If it's there, use it
    ignoreJFIF = false;
    // If it's there, use it
    ignoreAdobe = false;
    // Change if needed
    newAdobeTransform = JPEG.ADOBE_IMPOSSIBLE;
    writeDefaultJFIF = false;
    writeAdobe = false;
    // By default we'll do no conversion:
    int inCsType = JPEG.JCS_UNKNOWN;
    int outCsType = JPEG.JCS_UNKNOWN;
    JFIFMarkerSegment jfif = null;
    AdobeMarkerSegment adobe = null;
    SOFMarkerSegment sof = null;
    if (metadata != null) {
        jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        adobe = (AdobeMarkerSegment) metadata.findMarkerSegment(AdobeMarkerSegment.class, true);
        sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
    }
    // By default don't write one
    iccProfile = null;
    // PhotoYCC does this
    convertTosRGB = false;
    converted = null;
    if (destType != null) {
        if (numBandsUsed != destType.getNumBands()) {
            throw new IIOException("Number of source bands != number of destination bands");
        }
        cs = destType.getColorModel().getColorSpace();
        // Check the metadata against the destination type
        if (metadata != null) {
            checkSOFBands(sof, numBandsUsed);
            checkJFIF(jfif, destType, false);
            // Do we want to write an ICC profile?
            if ((jfif != null) && (ignoreJFIF == false)) {
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            }
            checkAdobe(adobe, destType, false);
        } else {
            // If we can add a JFIF or an Adobe marker segment, do so
            if (JPEG.isJFIFcompliant(destType, false)) {
                writeDefaultJFIF = true;
                // Do we want to write an ICC profile?
                if (JPEG.isNonStandardICC(cs)) {
                    iccProfile = ((ICC_ColorSpace) cs).getProfile();
                }
            } else {
                int transform = JPEG.transformForType(destType, false);
                if (transform != JPEG.ADOBE_IMPOSSIBLE) {
                    writeAdobe = true;
                    newAdobeTransform = transform;
                }
            }
            // re-create the metadata
            metadata = new JPEGMetadata(destType, null, this);
        }
        inCsType = getSrcCSType(destType);
        outCsType = getDefaultDestCSType(destType);
    } else {
        // no destination type
        if (metadata == null) {
            if (fullImage) {
                // no dest, no metadata, full image
                // Use default metadata matching the image and param
                metadata = new JPEGMetadata(new ImageTypeSpecifier(rimage), param, this);
                if (metadata.findMarkerSegment(JFIFMarkerSegment.class, true) != null) {
                    cs = rimage.getColorModel().getColorSpace();
                    if (JPEG.isNonStandardICC(cs)) {
                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                    }
                }
                inCsType = getSrcCSType(rimage);
                outCsType = getDefaultDestCSType(rimage);
            }
        // else no dest, no metadata, not an image,
        // so no special headers, no color conversion
        } else {
            // no dest type, but there is metadata
            checkSOFBands(sof, numBandsUsed);
            if (fullImage) {
                // no dest, metadata, image
                // Check that the metadata and the image match
                ImageTypeSpecifier inputType = new ImageTypeSpecifier(rimage);
                inCsType = getSrcCSType(rimage);
                if (cm != null) {
                    boolean alpha = cm.hasAlpha();
                    switch(cs.getType()) {
                        case ColorSpace.TYPE_GRAY:
                            if (!alpha) {
                                outCsType = JPEG.JCS_GRAYSCALE;
                            } else {
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                            // out colorspace remains unknown
                            }
                            if ((adobe != null) && (adobe.transform != JPEG.ADOBE_UNKNOWN)) {
                                newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                            }
                            break;
                        case ColorSpace.TYPE_RGB:
                            if (!alpha) {
                                if (jfif != null) {
                                    outCsType = JPEG.JCS_YCbCr;
                                    if (JPEG.isNonStandardICC(cs) || ((cs instanceof ICC_ColorSpace) && (jfif.iccSegment != null))) {
                                        iccProfile = ((ICC_ColorSpace) cs).getProfile();
                                    }
                                } else if (adobe != null) {
                                    switch(adobe.transform) {
                                        case JPEG.ADOBE_UNKNOWN:
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                        case JPEG.ADOBE_YCC:
                                            outCsType = JPEG.JCS_YCbCr;
                                            break;
                                        default:
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            outCsType = JPEG.JCS_RGB;
                                            break;
                                    }
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        if (subsampled) {
                                            outCsType = JPEG.JCS_YCbCr;
                                        } else {
                                            outCsType = JPEG.JCS_RGB;
                                        }
                                    }
                                }
                            } else {
                                // RGBA
                                if (jfif != null) {
                                    ignoreJFIF = true;
                                    warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                }
                                if (adobe != null) {
                                    if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                        newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                        warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                    }
                                    outCsType = JPEG.JCS_RGBA;
                                } else {
                                    // consult the ids
                                    int outCS = sof.getIDencodedCSType();
                                    // consult the sampling factors
                                    if (outCS != JPEG.JCS_UNKNOWN) {
                                        outCsType = outCS;
                                    } else {
                                        boolean subsampled = isSubsampled(sof.componentSpecs);
                                        outCsType = subsampled ? JPEG.JCS_YCbCrA : JPEG.JCS_RGBA;
                                    }
                                }
                            }
                            break;
                        case ColorSpace.TYPE_3CLR:
                            if (cs == JPEG.JCS.getYCC()) {
                                if (!alpha) {
                                    if (jfif != null) {
                                        convertTosRGB = true;
                                        convertOp = new ColorConvertOp(cs, JPEG.JCS.sRGB, null);
                                        outCsType = JPEG.JCS_YCbCr;
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_YCC) {
                                            newAdobeTransform = JPEG.ADOBE_YCC;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                        outCsType = JPEG.JCS_YCC;
                                    } else {
                                        outCsType = JPEG.JCS_YCC;
                                    }
                                } else {
                                    // PhotoYCCA
                                    if (jfif != null) {
                                        ignoreJFIF = true;
                                        warningOccurred(WARNING_IMAGE_METADATA_JFIF_MISMATCH);
                                    } else if (adobe != null) {
                                        if (adobe.transform != JPEG.ADOBE_UNKNOWN) {
                                            newAdobeTransform = JPEG.ADOBE_UNKNOWN;
                                            warningOccurred(WARNING_IMAGE_METADATA_ADOBE_MISMATCH);
                                        }
                                    }
                                    outCsType = JPEG.JCS_YCCA;
                                }
                            }
                    }
                }
            }
        // else no dest, metadata, not an image.  Defaults ok
        }
    }
    boolean metadataProgressive = false;
    int[] scans = null;
    if (metadata != null) {
        if (sof == null) {
            sof = (SOFMarkerSegment) metadata.findMarkerSegment(SOFMarkerSegment.class, true);
        }
        if ((sof != null) && (sof.tag == JPEG.SOF2)) {
            metadataProgressive = true;
            if (progressiveMode == ImageWriteParam.MODE_COPY_FROM_METADATA) {
                // Might still be null
                scans = collectScans(metadata, sof);
            } else {
                numScans = 0;
            }
        }
        if (jfif == null) {
            jfif = (JFIFMarkerSegment) metadata.findMarkerSegment(JFIFMarkerSegment.class, true);
        }
    }
    thumbnails = image.getThumbnails();
    int numThumbs = image.getNumThumbnails();
    forceJFIF = false;
    // then thumbnails can be written
    if (!writeDefaultJFIF) {
        // If there is no metadata, then we can't write thumbnails
        if (metadata == null) {
            thumbnails = null;
            if (numThumbs != 0) {
                warningOccurred(WARNING_IGNORING_THUMBS);
            }
        } else {
            // then the user must specify JFIF on the metadata
            if (fullImage == false) {
                if (jfif == null) {
                    // Or we can't include thumbnails
                    thumbnails = null;
                    if (numThumbs != 0) {
                        warningOccurred(WARNING_IGNORING_THUMBS);
                    }
                }
            } else {
                // It is a full image, and there is metadata
                if (jfif == null) {
                    // Can it have JFIF?
                    if ((outCsType == JPEG.JCS_GRAYSCALE) || (outCsType == JPEG.JCS_YCbCr)) {
                        if (numThumbs != 0) {
                            forceJFIF = true;
                            warningOccurred(WARNING_FORCING_JFIF);
                        }
                    } else {
                        // Nope, not JFIF-compatible
                        thumbnails = null;
                        if (numThumbs != 0) {
                            warningOccurred(WARNING_IGNORING_THUMBS);
                        }
                    }
                }
            }
        }
    }
    // Set up a boolean to indicate whether we need to call back to
    // write metadata
    boolean haveMetadata = ((metadata != null) || writeDefaultJFIF || writeAdobe);
    // Now that we have dealt with metadata, finalize our tables set up
    // Are we going to write tables?  By default, yes.
    boolean writeDQT = true;
    boolean writeDHT = true;
    // But if the metadata has no tables, no.
    DQTMarkerSegment dqt = null;
    DHTMarkerSegment dht = null;
    int restartInterval = 0;
    if (metadata != null) {
        dqt = (DQTMarkerSegment) metadata.findMarkerSegment(DQTMarkerSegment.class, true);
        dht = (DHTMarkerSegment) metadata.findMarkerSegment(DHTMarkerSegment.class, true);
        DRIMarkerSegment dri = (DRIMarkerSegment) metadata.findMarkerSegment(DRIMarkerSegment.class, true);
        if (dri != null) {
            restartInterval = dri.restartInterval;
        }
        if (dqt == null) {
            writeDQT = false;
        }
        if (dht == null) {
            // Ignored if optimizeHuffman is true
            writeDHT = false;
        }
    }
    // to use
    if (qTables == null) {
        // Get them from metadata, or use defaults
        if (dqt != null) {
            qTables = collectQTablesFromMetadata(metadata);
        } else if (streamQTables != null) {
            qTables = streamQTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            qTables = jparam.getQTables();
        } else {
            qTables = JPEG.getDefaultQTables();
        }
    }
    // If we are optimizing, we don't want any tables.
    if (optimizeHuffman == false) {
        // If they were for progressive scans, we can't use them.
        if ((dht != null) && (metadataProgressive == false)) {
            DCHuffmanTables = collectHTablesFromMetadata(metadata, true);
            ACHuffmanTables = collectHTablesFromMetadata(metadata, false);
        } else if (streamDCHuffmanTables != null) {
            DCHuffmanTables = streamDCHuffmanTables;
            ACHuffmanTables = streamACHuffmanTables;
        } else if ((jparam != null) && (jparam.areTablesSet())) {
            DCHuffmanTables = jparam.getDCHuffmanTables();
            ACHuffmanTables = jparam.getACHuffmanTables();
        } else {
            DCHuffmanTables = JPEG.getDefaultHuffmanTables(true);
            ACHuffmanTables = JPEG.getDefaultHuffmanTables(false);
        }
    }
    // By default, ids are 1 - N, no subsampling
    int[] componentIds = new int[numBandsUsed];
    int[] HsamplingFactors = new int[numBandsUsed];
    int[] VsamplingFactors = new int[numBandsUsed];
    int[] QtableSelectors = new int[numBandsUsed];
    for (int i = 0; i < numBandsUsed; i++) {
        // JFIF compatible
        componentIds[i] = i + 1;
        HsamplingFactors[i] = 1;
        VsamplingFactors[i] = 1;
        QtableSelectors[i] = 0;
    }
    // Now override them with the contents of sof, if there is one,
    if (sof != null) {
        for (int i = 0; i < numBandsUsed; i++) {
            if (forceJFIF == false) {
                // else use JFIF-compatible default
                componentIds[i] = sof.componentSpecs[i].componentId;
            }
            HsamplingFactors[i] = sof.componentSpecs[i].HsamplingFactor;
            VsamplingFactors[i] = sof.componentSpecs[i].VsamplingFactor;
            QtableSelectors[i] = sof.componentSpecs[i].QtableSelector;
        }
    }
    sourceXOffset += gridX;
    sourceWidth -= gridX;
    sourceYOffset += gridY;
    sourceHeight -= gridY;
    int destWidth = (sourceWidth + periodX - 1) / periodX;
    int destHeight = (sourceHeight + periodY - 1) / periodY;
    // Create an appropriate 1-line databuffer for writing
    int lineSize = sourceWidth * numBandsUsed;
    DataBufferByte buffer = new DataBufferByte(lineSize);
    // Create a raster from that
    int[] bandOffs = JPEG.bandOffsets[numBandsUsed - 1];
    raster = Raster.createInterleavedRaster(buffer, sourceWidth, 1, lineSize, numBandsUsed, bandOffs, null);
    // Call the writer, who will call back for every scanline
    processImageStarted(currentImage);
    boolean aborted = false;
    if (debug) {
        System.out.println("inCsType: " + inCsType);
        System.out.println("outCsType: " + outCsType);
    }
    // Note that getData disables acceleration on buffer, but it is
    // just a 1-line intermediate data transfer buffer that does not
    // affect the acceleration of the source image.
    aborted = writeImage(structPointer, buffer.getData(), inCsType, outCsType, numBandsUsed, bandSizes, sourceWidth, destWidth, destHeight, periodX, periodY, qTables, writeDQT, DCHuffmanTables, ACHuffmanTables, writeDHT, optimizeHuffman, (progressiveMode != ImageWriteParam.MODE_DISABLED), numScans, scans, componentIds, HsamplingFactors, VsamplingFactors, QtableSelectors, haveMetadata, restartInterval);
    cbLock.lock();
    try {
        if (aborted) {
            processWriteAborted();
        } else {
            processImageComplete();
        }
        ios.flush();
    } finally {
        cbLock.unlock();
    }
    // After a successful write
    currentImage++;
}
Example 42
Project: PDF-to-unusual-HTML-master  File: PDJpeg.java View source code
/**
     * Returns an image of the JPeg, or null if JPegs are not supported. (They should be. )
     * {@inheritDoc}
     */
public BufferedImage getRGBImage() throws IOException {
    //TODO PKOCH
    BufferedImage bi = null;
    boolean readError = false;
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        write2OutputStream(os);
        os.close();
        byte[] img = os.toByteArray();
        // 1. try to read jpeg image
        try {
            bi = ImageIO.read(new ByteArrayInputStream(img));
        } catch (IIOException iioe) {
            readError = true;
        } catch (Exception ignore) {
        }
        // TODO : not sure if it works for all cases
        if (bi == null && readError) {
            byte[] newImage = replaceHeader(img);
            ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
            bi = ImageIO.read(bai);
        }
    } finally {
    }
    // If there is a 'soft mask' image then we use that as a transparency mask.
    PDXObjectImage smask = getSMaskImage();
    if (smask != null) {
        BufferedImage smaskBI = smask.getRGBImage();
        COSArray decodeArray = smask.getDecode();
        CompositeImage compositeImage = new CompositeImage(bi, smaskBI);
        BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);
        return rgbImage;
    } else {
        // But if there is no soft mask, use the unaltered image.
        return bi;
    }
}
Example 43
Project: tika-master  File: ImageParser.java View source code
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
    String type = metadata.get(Metadata.CONTENT_TYPE);
    if (type != null) {
        //  fix it up to the new one, so Java is happy
        if (OLD_BMP_TYPE.toString().equals(type)) {
            type = MAIN_BMP_TYPE.toString();
        }
        try {
            Iterator<ImageReader> iterator = ImageIO.getImageReadersByMIMEType(type);
            if (iterator.hasNext()) {
                ImageReader reader = iterator.next();
                try {
                    try (ImageInputStream imageStream = ImageIO.createImageInputStream(new CloseShieldInputStream(stream))) {
                        reader.setInput(imageStream);
                        metadata.set(Metadata.IMAGE_WIDTH, Integer.toString(reader.getWidth(0)));
                        metadata.set(Metadata.IMAGE_LENGTH, Integer.toString(reader.getHeight(0)));
                        metadata.set("height", Integer.toString(reader.getHeight(0)));
                        metadata.set("width", Integer.toString(reader.getWidth(0)));
                        loadMetadata(reader.getImageMetadata(0), metadata);
                    }
                } finally {
                    reader.dispose();
                }
            }
            // Translate certain Metadata tags from the ImageIO
            //  specific namespace into the general Tika one
            setIfPresent(metadata, "CommentExtensions CommentExtension", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "markerSequence com", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "Data BitsPerSample", Metadata.BITS_PER_SAMPLE);
        } catch (IIOException e) {
            if (!(e.getMessage() != null && e.getMessage().equals("Unexpected block type 0!") && type.equals("image/gif"))) {
                throw new TikaException(type + " parse error", e);
            }
        }
    }
    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();
    xhtml.endDocument();
}
Example 44
Project: geotools-master  File: ImageWorker.java View source code
/**
     * Writes the {@linkplain #image} to the specified file. This method differs from {@link ImageIO#write(String,File)} in a number of ways:
     * <p>
     * <ul>
     * <li>The {@linkplain ImageWriter image writer} to use is inferred from the file extension.</li>
     * <li>If the image writer accepts {@link File} objects as input, then the {@code file} argument is given directly without creating an
     * {@link ImageOutputStream} object. This is important for some formats like HDF, which work <em>only</em> with files.</li>
     * <li>If the {@linkplain #image} is not tiled, then it is tiled prior to be written.</li>
     * <li>If some special processing is needed for a given format, then the corresponding method is invoked. Example:
     * {@link #forceIndexColorModelForGIF}.</li>
     * </ul>
     * 
     * @return this {@link ImageWorker}.
     */
public final ImageWorker write(final File output) throws IOException {
    final String filename = output.getName();
    final int dot = filename.lastIndexOf('.');
    if (dot < 0) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final String extension = filename.substring(dot + 1).trim();
    write(output, ImageIO.getImageWritersBySuffix(extension));
    return this;
}
Example 45
Project: geotools-old-master  File: ImageWorker.java View source code
/**
     * Writes the {@linkplain #image} to the specified file. This method differs
     * from {@link ImageIO#write(String,File)} in a number of ways:
     * <p>
     * <ul>
     *   <li>The {@linkplain ImageWriter image writer} to use is inferred from the file
     *       extension.</li>
     *   <li>If the image writer accepts {@link File} objects as input, then the {@code file}
     *       argument is given directly without creating an {@link ImageOutputStream} object.
     *       This is important for some formats like HDF, which work <em>only</em> with files.</li>
     *   <li>If the {@linkplain #image} is not tiled, then it is tiled prior to be written.</li>
     *   <li>If some special processing is needed for a given format, then the corresponding method
     *       is invoked. Example: {@link #forceIndexColorModelForGIF}.</li>
     * </ul>
     *
     * @return this {@link ImageWorker}.
     */
public final ImageWorker write(final File output) throws IOException {
    final String filename = output.getName();
    final int dot = filename.lastIndexOf('.');
    if (dot < 0) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final String extension = filename.substring(dot + 1).trim();
    write(output, ImageIO.getImageWritersBySuffix(extension));
    return this;
}
Example 46
Project: geotools_trunk-master  File: ImageWorker.java View source code
/**
     * Writes the {@linkplain #image} to the specified file. This method differs
     * from {@link ImageIO#write(String,File)} in a number of ways:
     * <p>
     * <ul>
     *   <li>The {@linkplain ImageWriter image writer} to use is inferred from the file
     *       extension.</li>
     *   <li>If the image writer accepts {@link File} objects as input, then the {@code file}
     *       argument is given directly without creating an {@link ImageOutputStream} object.
     *       This is important for some formats like HDF, which work <em>only</em> with files.</li>
     *   <li>If the {@linkplain #image} is not tiled, then it is tiled prior to be written.</li>
     *   <li>If some special processing is needed for a given format, then the corresponding method
     *       is invoked. Example: {@link #forceIndexColorModelForGIF}.</li>
     * </ul>
     *
     * @return this {@link ImageWorker}.
     */
public final ImageWorker write(final File output) throws IOException {
    final String filename = output.getName();
    final int dot = filename.lastIndexOf('.');
    if (dot < 0) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final String extension = filename.substring(dot + 1).trim();
    write(output, ImageIO.getImageWritersBySuffix(extension));
    return this;
}
Example 47
Project: pdfbox-master  File: DCTFilter.java View source code
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException {
    ImageReader reader = findImageReader("JPEG", "a suitable JAI I/O image filter is not installed");
    try (ImageInputStream iis = ImageIO.createImageInputStream(encoded)) {
        // skip one LF if there
        if (iis.read() != 0x0A) {
            iis.seek(0);
        }
        reader.setInput(iis);
        String numChannels = getNumChannels(reader);
        // get the raster using horrible JAI workarounds
        ImageIO.setUseCache(false);
        Raster raster;
        // after "can't get metadata" because "no meta" file was CMYK
        if ("3".equals(numChannels) || numChannels.isEmpty()) {
            try {
                // I'd like to use ImageReader#readRaster but it is buggy and can't read RGB correctly
                BufferedImage image = reader.read(0);
                raster = image.getRaster();
            } catch (IIOException e) {
                raster = reader.readRaster(0, null);
            }
        } else {
            // JAI can't read CMYK JPEGs using ImageReader#read or ImageIO.read but
            // fortunately ImageReader#readRaster isn't buggy when reading 4-channel files
            raster = reader.readRaster(0, null);
        }
        // special handling for 4-component images
        if (raster.getNumBands() == 4) {
            // get APP14 marker
            Integer transform;
            try {
                transform = getAdobeTransform(reader.getImageMetadata(0));
            } catch (IIOExceptionNegativeArraySizeException |  e) {
                transform = getAdobeTransformByBruteForce(iis);
            }
            int colorTransform = transform != null ? transform : 0;
            // 0 = Unknown (RGB or CMYK), 1 = YCbCr, 2 = YCCK
            switch(colorTransform) {
                case 0:
                    // already CMYK
                    break;
                case 1:
                    // TODO YCbCr
                    LOG.warn("YCbCr JPEGs not implemented");
                    break;
                case 2:
                    raster = fromYCCKtoCMYK(raster);
                    break;
                default:
                    throw new IllegalArgumentException("Unknown colorTransform");
            }
        } else if (raster.getNumBands() == 3) {
            // BGR to RGB
            raster = fromBGRtoRGB(raster);
        }
        DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
        decoded.write(dataBuffer.getData());
    } finally {
        reader.dispose();
    }
    return new DecodeResult(parameters);
}
Example 48
Project: udig-community-master  File: WorldWindTest.java View source code
public void testAccessorFailover() throws IOException {
    String good = "http://worldwind25.arc.nasa.gov/tile/tile.aspx?T=bmng.topo.bathy.200411&L=1&X=3&Y=7";
    String bad = "http://worldwind25.arc.nasa.gov/tile/tile.aspx?T=105&L=0&X=63&Y=22";
    ImageInputStream inputGood = Accessor.openImageInput(new URL(good));
    ImageInputStream inputBad = Accessor.openImageInput(new URL(bad));
    assertNotNull(inputGood);
    //assertNull( inputBad );
    ImageReader jpeg = ImageIO.getImageReadersByFormatName("jpeg").next();
    jpeg.setInput(inputGood);
    BufferedImage image = jpeg.read(0);
    assertNotNull(image);
    assertEquals(512, image.getWidth());
    assertEquals(512, image.getHeight());
    jpeg.dispose();
    jpeg = ImageIO.getImageReadersByFormatName("jpeg").next();
    jpeg.setInput(inputBad);
    try {
        image = jpeg.read(0);
        assertNotNull(image);
        assertEquals(512, image.getWidth());
        assertEquals(512, image.getHeight());
        fail("This was supposed to be a bad image");
    } catch (IIOException expected) {
    } finally {
        jpeg.dispose();
    }
}
Example 49
Project: UniversalMediaServer-master  File: ImagesUtil.java View source code
/**
	 * Converts and scales an image in one operation. Scaling can be with or
	 * without padding. Preserves aspect ratio and rotates/flips the image
	 * according to Exif orientation. Format support is limited to that of
	 * {@link ImageIO}. Only one of the three input arguments may be used in any
	 * given call. Note that {@code outputProfile} overrides
	 * {@code outputFormat}.
	 * <p>
	 * <b> This method consumes and closes {@code inputStream}. </b>
	 *
	 * @param inputByteArray the source image in a supported format.
	 * @param inputImage the source {@link Image}.
	 * @param inputStream the source image in a supported format.
	 * @param width the new width or 0 to disable scaling.
	 * @param height the new height or 0 to disable scaling.
	 * @param scaleType the {@link ScaleType} to use when scaling.
	 * @param outputFormat the {@link ImageFormat} to convert to or
	 *            {@link ImageFormat#SOURCE} to preserve source format.
	 *            Overridden by {@code outputProfile}.
	 * @param outputProfile the {@link DLNAImageProfile} to convert to. This
	 *            overrides {@code outputFormat}.
	 * @param dlnaCompliant whether or not the output image should be restricted
	 *            to DLNA compliance. This also means that the output can be
	 *            safely cast to {@link DLNAImage}.
	 * @param dlnaThumbnail whether or not the output image should be restricted
	 *            to DLNA thumbnail compliance. This also means that the output
	 *            can be safely cast to {@link DLNAThumbnail}.
	 * @param padToSize whether padding should be used if source aspect doesn't
	 *            match target aspect.
	 * @return The scaled and/or converted image or {@code null} if the source
	 *         is {@code null}.
	 * @throws IOException if the operation fails.
	 */
protected static Image transcodeImage(byte[] inputByteArray, Image inputImage, InputStream inputStream, int width, int height, ScaleType scaleType, ImageFormat outputFormat, DLNAImageProfile outputProfile, boolean dlnaCompliant, boolean dlnaThumbnail, boolean padToSize) throws IOException {
    if (inputByteArray == null && inputStream == null && inputImage == null) {
        return null;
    }
    if ((inputByteArray != null & inputImage != null) || (inputByteArray != null & inputStream != null) || (inputImage != null & inputStream != null)) {
        throw new IllegalArgumentException("Use either inputByteArray, inputImage or inputStream");
    }
    boolean trace = LOGGER.isTraceEnabled();
    if (trace) {
        StringBuilder sb = new StringBuilder();
        if (scaleType != null) {
            sb.append("ScaleType = ").append(scaleType);
        }
        if (width > 0 && height > 0) {
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append("Width = ").append(width).append(", Height = ").append(height);
        }
        if (sb.length() > 0) {
            sb.append(", ");
        }
        sb.append("PadToSize = ").append(padToSize ? "True" : "False");
        LOGGER.trace("Converting {} image source to {} format and type {} using the following parameters: {}", inputByteArray != null ? "byte array" : inputImage != null ? "Image" : "input stream", outputProfile != null ? outputProfile : outputFormat, dlnaThumbnail ? "DLNAThumbnail" : dlnaCompliant ? "DLNAImage" : "Image", sb);
    }
    ImageIO.setUseCache(false);
    dlnaCompliant = dlnaCompliant || dlnaThumbnail;
    if (inputImage != null) {
        inputByteArray = inputImage.getBytes(false);
    } else if (inputStream != null) {
        inputByteArray = ImagesUtil.toByteArray(inputStream);
    }
    // outputProfile overrides outputFormat
    if (outputProfile != null) {
        if (dlnaThumbnail && outputProfile.equals(DLNAImageProfile.GIF_LRG)) {
            outputProfile = DLNAImageProfile.JPEG_LRG;
        }
        // Default to correct ScaleType for the profile
        if (scaleType == null) {
            if (DLNAImageProfile.JPEG_RES_H_V.equals(outputProfile)) {
                scaleType = ScaleType.EXACT;
            } else {
                scaleType = ScaleType.MAX;
            }
        }
        outputFormat = ImageFormat.toImageFormat(outputProfile);
        width = width > 0 ? width : outputProfile.getMaxWidth();
        height = height > 0 ? height : outputProfile.getMaxHeight();
    } else if (scaleType == null) {
        scaleType = ScaleType.MAX;
    }
    ImageReaderResult inputResult;
    try {
        inputResult = ImageIOTools.read(new ByteArrayInputStream(inputByteArray));
    } catch (IIOException e) {
        throw new UnknownFormatException("Unable to read image format", e);
    }
    if (// ImageIO doesn't support the image format
    inputResult.bufferedImage == null || inputResult.imageFormat == null) {
        throw new UnknownFormatException("Failed to transform image because the source format is unknown");
    }
    if (outputFormat == null || outputFormat == ImageFormat.SOURCE) {
        outputFormat = inputResult.imageFormat;
    }
    BufferedImage bufferedImage = inputResult.bufferedImage;
    boolean reencode = false;
    if (outputProfile == null && dlnaCompliant) {
        // if the source image has alpha and JPEG if not.
        switch(outputFormat) {
            case GIF:
                if (dlnaThumbnail) {
                    outputFormat = ImageFormat.JPEG;
                }
                break;
            case JPEG:
            case PNG:
                break;
            default:
                if (bufferedImage.getColorModel().hasAlpha()) {
                    outputFormat = ImageFormat.PNG;
                } else {
                    outputFormat = ImageFormat.JPEG;
                }
        }
    }
    Metadata metadata = null;
    ExifOrientation orientation;
    if (inputImage != null && inputImage.getImageInfo() != null) {
        orientation = inputImage.getImageInfo().getExifOrientation();
    } else {
        try {
            metadata = getMetadata(inputByteArray, inputResult.imageFormat);
        } catch (IOExceptionImageProcessingException |  e) {
            LOGGER.error("Failed to read input image metadata: {}", e.getMessage());
            LOGGER.trace("", e);
            metadata = new Metadata();
        }
        if (metadata == null) {
            metadata = new Metadata();
        }
        orientation = parseExifOrientation(metadata);
    }
    if (orientation != ExifOrientation.TOP_LEFT) {
        // Rotate the image before doing all the other checks
        BufferedImage oldBufferedImage = bufferedImage;
        bufferedImage = Thumbnails.of(bufferedImage).scale(1.0d).addFilter(ExifFilterUtils.getFilterForOrientation(orientation.getThumbnailatorOrientation())).asBufferedImage();
        oldBufferedImage.flush();
        // Re-parse the metadata after rotation as these are newly generated.
        ByteArrayOutputStream tmpOutputStream = new ByteArrayOutputStream(inputByteArray.length);
        Thumbnails.of(bufferedImage).scale(1.0d).outputFormat(outputFormat.toString()).toOutputStream(tmpOutputStream);
        try {
            metadata = getMetadata(tmpOutputStream.toByteArray(), outputFormat);
        } catch (IOExceptionImageProcessingException |  e) {
            LOGGER.debug("Failed to read rotated image metadata: {}", e.getMessage());
            LOGGER.trace("", e);
            metadata = new Metadata();
        }
        if (metadata == null) {
            metadata = new Metadata();
        }
        reencode = true;
    }
    if (outputProfile == null && dlnaCompliant) {
        // Set a suitable output profile.
        if (width < 1 || height < 1) {
            outputProfile = DLNAImageProfile.getClosestDLNAProfile(bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, true);
            width = outputProfile.getMaxWidth();
            height = outputProfile.getMaxHeight();
        } else {
            outputProfile = DLNAImageProfile.getClosestDLNAProfile(calculateScaledResolution(bufferedImage.getWidth(), bufferedImage.getHeight(), scaleType, width, height), outputFormat, true);
            width = Math.min(width, outputProfile.getMaxWidth());
            height = Math.min(height, outputProfile.getMaxHeight());
        }
        if (DLNAImageProfile.JPEG_RES_H_V.equals(outputProfile)) {
            scaleType = ScaleType.EXACT;
        }
    }
    boolean convertColors = bufferedImage.getType() == BufferedImageType.TYPE_CUSTOM.getTypeId() || bufferedImage.getType() == BufferedImageType.TYPE_BYTE_BINARY.getTypeId() || bufferedImage.getColorModel().getColorSpace().getType() != ColorSpaceType.TYPE_RGB.getTypeId();
    // Impose DLNA format restrictions
    if (!reencode && outputFormat == inputResult.imageFormat && outputProfile != null) {
        DLNAComplianceResult complianceResult;
        switch(outputFormat) {
            case GIF:
            case JPEG:
            case PNG:
                ImageInfo imageInfo;
                // metadata is only null at this stage if inputImage != null and no rotation was necessary
                if (metadata == null) {
                    imageInfo = inputImage.getImageInfo();
                }
                imageInfo = ImageInfo.create(bufferedImage.getWidth(), bufferedImage.getHeight(), inputResult.imageFormat, ImageInfo.SIZE_UNKNOWN, bufferedImage.getColorModel(), metadata, false, true);
                complianceResult = DLNAImageProfile.checkCompliance(imageInfo, outputProfile);
                break;
            default:
                throw new IllegalStateException("Unexpected image format: " + outputFormat);
        }
        reencode = reencode || convertColors || !complianceResult.isFormatCorrect() || !complianceResult.isColorsCorrect();
        ;
        if (!complianceResult.isResolutionCorrect()) {
            width = width > 0 && complianceResult.getMaxWidth() > 0 ? Math.min(width, complianceResult.getMaxWidth()) : width > 0 ? width : complianceResult.getMaxWidth();
            height = height > 0 && complianceResult.getMaxHeight() > 0 ? Math.min(height, complianceResult.getMaxHeight()) : height > 0 ? height : complianceResult.getMaxHeight();
        }
        if (trace) {
            if (complianceResult.isAllCorrect()) {
                LOGGER.trace("Image conversion DLNA compliance check: The source image is compliant");
            } else {
                LOGGER.trace("Image conversion DLNA compliance check for {}: " + "The source image colors are {}, format is {} and resolution ({} x {}) is {}", outputProfile, complianceResult.isColorsCorrect() ? "compliant" : "non-compliant", complianceResult.isFormatCorrect() ? "compliant" : "non-compliant", bufferedImage.getWidth(), bufferedImage.getHeight(), complianceResult.isResolutionCorrect() ? "compliant" : "non-compliant");
            }
        }
    }
    if (convertColors) {
        // Preserve alpha channel if the output format supports it
        BufferedImageType outputImageType;
        if ((outputFormat == ImageFormat.PNG || outputFormat == ImageFormat.PSD) && bufferedImage.getColorModel().getNumComponents() == 4) {
            outputImageType = bufferedImage.isAlphaPremultiplied() ? BufferedImageType.TYPE_4BYTE_ABGR_PRE : BufferedImageType.TYPE_4BYTE_ABGR;
        } else {
            outputImageType = BufferedImageType.TYPE_3BYTE_BGR;
        }
        BufferedImage convertedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), outputImageType.getTypeId());
        ColorConvertOp colorConvertOp = new ColorConvertOp(null);
        colorConvertOp.filter(bufferedImage, convertedImage);
        bufferedImage.flush();
        bufferedImage = convertedImage;
        reencode = true;
    }
    if (width < 1 || height < 1 || (scaleType == ScaleType.MAX && bufferedImage.getWidth() <= width && bufferedImage.getHeight() <= height) || (scaleType == ScaleType.EXACT && bufferedImage.getWidth() == width && bufferedImage.getHeight() == height)) {
        //No resize, just convert
        if (!reencode && inputResult.imageFormat == outputFormat) {
            // Nothing to do, just return source
            // metadata is only null at this stage if inputImage != null
            Image result;
            if (dlnaThumbnail) {
                result = metadata == null ? new DLNAThumbnail(inputImage, outputProfile, false) : new DLNAThumbnail(inputByteArray, outputFormat, bufferedImage, metadata, outputProfile, false);
            } else if (dlnaCompliant) {
                result = metadata == null ? new DLNAImage(inputImage, outputProfile, false) : new DLNAImage(inputByteArray, outputFormat, bufferedImage, metadata, outputProfile, false);
            } else {
                result = metadata == null ? new Image(inputImage, false) : new Image(inputByteArray, outputFormat, bufferedImage, metadata, false);
            }
            bufferedImage.flush();
            if (trace) {
                LOGGER.trace("No conversion is needed, returning source image with width = {}, height = {} and output {}.", bufferedImage.getWidth(), bufferedImage.getHeight(), dlnaCompliant && outputProfile != null ? "profile: " + outputProfile : "format: " + outputFormat);
            }
            return result;
        }
    } else {
        boolean force = DLNAImageProfile.JPEG_RES_H_V.equals(outputProfile);
        BufferedImage oldBufferedImage = bufferedImage;
        if (padToSize && force) {
            bufferedImage = Thumbnails.of(bufferedImage).forceSize(width, height).addFilter(new Canvas(width, height, Positions.CENTER, Color.BLACK)).asBufferedImage();
        } else if (padToSize) {
            bufferedImage = Thumbnails.of(bufferedImage).size(width, height).addFilter(new Canvas(width, height, Positions.CENTER, Color.BLACK)).asBufferedImage();
        } else if (force) {
            bufferedImage = Thumbnails.of(bufferedImage).forceSize(width, height).asBufferedImage();
        } else {
            bufferedImage = Thumbnails.of(bufferedImage).size(width, height).asBufferedImage();
        }
        oldBufferedImage.flush();
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Thumbnails.of(bufferedImage).scale(1.0d).outputFormat(outputFormat.toString()).outputQuality(1.0f).toOutputStream(outputStream);
    byte[] outputByteArray = outputStream.toByteArray();
    Image result;
    if (dlnaThumbnail) {
        result = new DLNAThumbnail(outputByteArray, bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, null, null, outputProfile, false);
    } else if (dlnaCompliant) {
        result = new DLNAImage(outputByteArray, bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, null, null, outputProfile, false);
    } else {
        result = new Image(outputByteArray, bufferedImage.getWidth(), bufferedImage.getHeight(), outputFormat, null, null, true, false);
    }
    if (trace) {
        StringBuilder sb = new StringBuilder();
        sb.append("Convert colors = ").append(convertColors ? "True" : "False").append(", Re-encode = ").append(reencode ? "True" : "False");
        LOGGER.trace("Finished converting {} {} image{}. " + "Output image resolution: {}, {}. Flags: {}", inputResult.width + "×" + inputResult.height, inputResult.imageFormat, orientation != ExifOrientation.TOP_LEFT ? " with orientation " + orientation : "", bufferedImage.getWidth() + "×" + bufferedImage.getHeight(), dlnaCompliant && outputProfile != null ? "profile: " + outputProfile : "format: " + outputFormat, sb);
    }
    bufferedImage.flush();
    return result;
}
Example 50
Project: adore-djatoka-master  File: ImageServlet.java View source code
private int[] getHeightWidth(HttpServletRequest aRequest, HttpServletResponse aResponse) throws IOException, ServletException {
    String reqURI = aRequest.getRequestURI();
    String servletPath = aRequest.getServletPath();
    String path = reqURI.substring(servletPath.length());
    String id = getID(path);
    int width = 0, height = 0;
    if (myCache != null) {
        try {
            PairtreeRoot cacheDir = new PairtreeRoot(new File(myCache));
            PairtreeObject cacheObject = cacheDir.getObject(id);
            ServletContext context = getServletContext();
            String filename = PairtreeUtils.encodeID(id);
            File dziFile = new File(cacheObject, filename + ".dzi");
            if (dziFile.exists() && dziFile.length() > 0) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Reading dzi file: " + dziFile.getAbsolutePath());
                }
                Document dzi = new Builder().build(dziFile);
                Element root = dzi.getRootElement();
                Element size = root.getFirstChildElement("Size", DZI_NS);
                String wString = size.getAttributeValue("Width");
                String hString = size.getAttributeValue("Height");
                width = wString.equals("") ? 0 : Integer.parseInt(wString);
                height = hString.equals("") ? 0 : Integer.parseInt(hString);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Returning width/height: {}/{}", width, height);
                }
            } else {
                if (dziFile.exists()) {
                    dziFile.delete();
                }
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Creating new dzi file: " + dziFile.getAbsolutePath());
                }
                URL url = context.getResource("/WEB-INF/classes/dzi.xml");
                Document dzi = new Builder().build(url.openStream());
                FileOutputStream outStream = new FileOutputStream(dziFile);
                Serializer serializer = new Serializer(outStream);
                URL imageURL = new URL(getFullSizeImageURL(aRequest) + URLEncoder.encode(id, "UTF-8"));
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Writing DZI file for: {}", imageURL.toExternalForm());
                }
                try {
                    BufferedImage image = ImageIO.read(imageURL);
                    Element root = dzi.getRootElement();
                    Element size = root.getFirstChildElement("Size", DZI_NS);
                    Attribute wAttribute = size.getAttribute("Width");
                    Attribute hAttribute = size.getAttribute("Height");
                    // Return the width and height in response headers
                    height = image.getHeight();
                    width = image.getWidth();
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Returning width/height: {}/{}", width, height);
                    }
                    // Save it in our dzi file for easier access next time
                    wAttribute.setValue(Integer.toString(width));
                    hAttribute.setValue(Integer.toString(height));
                    serializer.write(dzi);
                } catch (IIOException details) {
                    Class<?> thrown = details.getCause().getClass();
                    String name = thrown.getSimpleName();
                    if (name.equals("FileNotFoundException")) {
                        throw new FileNotFoundException(id + " not found");
                    } else {
                        throw details;
                    }
                }
            }
        } catch (ValidityException details) {
            aResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, details.getMessage());
        } catch (ParsingException details) {
            aResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, details.getMessage());
        }
    } else {
        // TODO: work around rather than throwing an exception
        throw new ServletException("Cache not correctly configured");
    }
    return new int[] { height, width };
}
Example 51
Project: BigSemanticsJava-master  File: ImageParserAwt.java View source code
private void readMetadata(boolean reread) throws IOException {
    try {
        IIOMetadata metadata = imageReader.getImageMetadata(0);
        String name = metadata.getNativeMetadataFormatName();
        IIOMetadataNode node = (IIOMetadataNode) metadata.getAsTree(name);
        // printTree(node);
        extractMetadataFeatures(node);
    } catch (javax.imageio.IIOException iioex) {
        if (!reread && iioex.getMessage() != null && iioex.getMessage().endsWith("without prior JFIF!")) {
            warning("Trying workaround for java bug");
            closeImageInputStream();
            InputStream newInputSteam = reConnect();
            imageInputStream = patch(newInputSteam);
            imageReader.setInput(imageInputStream);
            readMetadata(true);
        } else
            warning("Couldn't extract metadata from image: " + iioex);
    }
// byte[] iptc =(byte[]) iptcNode.getUserObject();
}
Example 52
Project: constellation-master  File: WMTSService.java View source code
/**
     * Handle {@code GetTile request} in RESTFUL mode.
     *
     * @param layer The layer to request.
     * @param tileMatrixSet The matrix set of the tile.
     * @param tileMatrix The matrix tile.
     * @param tileRow The row of the tile in the matrix.
     * @param tileCol The column of the tile in the matrix.
     * @param format The format extension, like png.
     *
     * @return The response containing the tile.
     */
@GET
@Path("{layer}/{tileMatrixSet}/{tileMatrix}/{tileRow}/{tileCol}.{format}")
public Response processGetTileRestful(@PathParam("layer") final String layer, @PathParam("tileMatrixSet") final String tileMatrixSet, @PathParam("tileMatrix") final String tileMatrix, @PathParam("tileRow") final String tileRow, @PathParam("tileCol") final String tileCol, @PathParam("format") final String format) {
    try {
        final String mimeType;
        try {
            mimeType = ImageIOUtilities.formatNameToMimeType(format);
        } catch (IIOException ex) {
            throw new CstlServiceException(ex, NO_APPLICABLE_CODE);
        }
        final GetTile gt = createNewGetTileRequestRestful(layer, tileMatrixSet, tileMatrix, tileRow, tileCol, mimeType, null);
        return treatIncomingRequest(gt);
    } catch (CstlServiceException ex) {
        final Worker w = WSEngine.getInstance("WMTS", getSafeParameter("serviceId"));
        return processExceptionResponse(ex, null, w);
    }
}
Example 53
Project: geotools-2.7.x-master  File: ImageWorker.java View source code
/**
     * Writes the {@linkplain #image} to the specified file. This method differs
     * from {@link ImageIO#write(String,File)} in a number of ways:
     * <p>
     * <ul>
     *   <li>The {@linkplain ImageWriter image writer} to use is inferred from the file
     *       extension.</li>
     *   <li>If the image writer accepts {@link File} objects as input, then the {@code file}
     *       argument is given directly without creating an {@link ImageOutputStream} object.
     *       This is important for some formats like HDF, which work <em>only</em> with files.</li>
     *   <li>If the {@linkplain #image} is not tiled, then it is tiled prior to be written.</li>
     *   <li>If some special processing is needed for a given format, then the corresponding method
     *       is invoked. Example: {@link #forceIndexColorModelForGIF}.</li>
     * </ul>
     *
     * @return this {@link ImageWorker}.
     */
public final ImageWorker write(final File output) throws IOException {
    final String filename = output.getName();
    final int dot = filename.lastIndexOf('.');
    if (dot < 0) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final String extension = filename.substring(dot + 1).trim();
    write(output, ImageIO.getImageWritersBySuffix(extension));
    return this;
}
Example 54
Project: geotools-tike-master  File: ImageWorker.java View source code
/**
     * Writes the {@linkplain #image} to the specified file. This method differs
     * from {@link ImageIO#write(String,File)} in a number of ways:
     * <p>
     * <ul>
     *   <li>The {@linkplain ImageWriter image writer} to use is inferred from the file
     *       extension.</li>
     *   <li>If the image writer accepts {@link File} objects as input, then the {@code file}
     *       argument is given directly without creating an {@link ImageOutputStream} object.
     *       This is important for some formats like HDF, which work <em>only</em> with files.</li>
     *   <li>If the {@linkplain #image} is not tiled, then it is tiled prior to be written.</li>
     *   <li>If some special processing is needed for a given format, then the corresponding method
     *       is invoked. Example: {@link #forceIndexColorModelForGIF}.</li>
     * </ul>
     *
     * @return this {@link ImageWorker}.
     */
public final ImageWorker write(final File output) throws IOException {
    final String filename = output.getName();
    final int dot = filename.lastIndexOf('.');
    if (dot < 0) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final String extension = filename.substring(dot + 1).trim();
    write(output, ImageIO.getImageWritersBySuffix(extension));
    return this;
}
Example 55
Project: smartly-master  File: ImageIOUtils.java View source code
public BufferedImage readImage(final File file) throws IOException, ImageReadException {
    colorType = COLOR_TYPE_RGB;
    hasAdobeMarker = false;
    final ImageInputStream stream = ImageIO.createImageInputStream(file);
    final Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
    while (iter.hasNext()) {
        ImageReader reader = iter.next();
        reader.setInput(stream);
        BufferedImage image;
        ICC_Profile profile = null;
        try {
            image = reader.read(0);
        } catch (IIOException e) {
            colorType = COLOR_TYPE_CMYK;
            checkAdobeMarker(file);
            profile = Imaging.getICCProfile(file);
            WritableRaster raster = (WritableRaster) reader.readRaster(0, null);
            if (colorType == COLOR_TYPE_YCCK)
                convertYcckToCmyk(raster);
            if (hasAdobeMarker)
                convertInvertedColors(raster);
            image = convertCmykToRgb(raster, profile);
        }
        return image;
    }
    return null;
}
Example 56
Project: twiterra-master  File: GeotiffImageReader.java View source code
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    // TODO: more generally, the following test should reflect that more than one image is possible in a Tiff.
    if (imageIndex != 0)
        throw new IllegalArgumentException(this.getClass().getName() + ".read(): illegal imageIndex: " + imageIndex);
    readIFDs();
    // Extract the various IFD tags we need to read this image...
    TiffIFDEntry widthEntry = null;
    TiffIFDEntry lengthEntry = null;
    TiffIFDEntry bitsPerSampleEntry = null;
    TiffIFDEntry samplesPerPixelEntry = null;
    TiffIFDEntry photoInterpEntry = null;
    TiffIFDEntry stripOffsetsEntry = null;
    TiffIFDEntry stripCountsEntry = null;
    TiffIFDEntry rowsPerStripEntry = null;
    TiffIFDEntry planarConfigEntry = null;
    TiffIFDEntry[] ifd = ifds.get(imageIndex);
    for (int i = 0; i < ifd.length; i++) {
        TiffIFDEntry entry = ifd[i];
        switch(entry.tag) {
            case TiffTags.IMAGE_WIDTH:
                widthEntry = entry;
                break;
            case TiffTags.IMAGE_LENGTH:
                lengthEntry = entry;
                break;
            case TiffTags.BITS_PER_SAMPLE:
                bitsPerSampleEntry = entry;
                break;
            case TiffTags.SAMPLES_PER_PIXEL:
                samplesPerPixelEntry = entry;
                break;
            case TiffTags.PHOTO_INTERPRETATION:
                photoInterpEntry = entry;
                break;
            case TiffTags.STRIP_OFFSETS:
                stripOffsetsEntry = entry;
                break;
            case TiffTags.STRIP_BYTE_COUNTS:
                stripCountsEntry = entry;
                break;
            case TiffTags.ROWS_PER_STRIP:
                rowsPerStripEntry = entry;
                break;
            case TiffTags.PLANAR_CONFIGURATION:
                planarConfigEntry = entry;
                break;
        }
    }
    if (widthEntry == null || lengthEntry == null || samplesPerPixelEntry == null || photoInterpEntry == null || stripOffsetsEntry == null || stripCountsEntry == null || rowsPerStripEntry == null || planarConfigEntry == null)
        // note that bitsPerSample is an optional entry, so not checked above;  its default is "1".
        throw new IIOException(this.getClass().getName() + ".read(): unable to decipher image organization");
    int width = (int) widthEntry.asLong();
    int height = (int) lengthEntry.asLong();
    int samplesPerPixel = (int) samplesPerPixelEntry.asLong();
    long photoInterp = photoInterpEntry.asLong();
    long rowsPerStrip = rowsPerStripEntry.asLong();
    long planarConfig = planarConfigEntry.asLong();
    int[] bitsPerSample = getBitsPerSample(bitsPerSampleEntry);
    long[] stripOffsets = getStripsArray(stripOffsetsEntry);
    long[] stripCounts = getStripsArray(stripCountsEntry);
    // make sure a DataBufferByte is going to do the trick
    for (int i = 0; i < bitsPerSample.length; i++) {
        if (bitsPerSample[i] != 8)
            throw new IIOException(this.getClass().getName() + ".read(): only expecting 8 bits/sample; found " + bitsPerSample[i]);
    }
    ColorSpace colorSpace = (samplesPerPixel > 1) ? ColorSpace.getInstance(ColorSpace.CS_sRGB) : ColorSpace.getInstance(ColorSpace.CS_GRAY);
    int transparency = Transparency.OPAQUE;
    boolean hasAlpha = false;
    if (samplesPerPixel == 4) {
        transparency = Transparency.TRANSLUCENT;
        hasAlpha = true;
    }
    int[] bankOffsets = new int[samplesPerPixel];
    for (int i = 0; i < samplesPerPixel; i++) bankOffsets[i] = i;
    int[] offsets = new int[(planarConfig == TiffConstants.PLANARCONFIG_CHUNKY) ? 1 : samplesPerPixel];
    for (int i = 0; i < offsets.length; i++) offsets[i] = 0;
    ComponentColorModel colorModel = new ComponentColorModel(colorSpace, bitsPerSample, hasAlpha, false, transparency, DataBuffer.TYPE_BYTE);
    ComponentSampleModel sampleModel;
    if (samplesPerPixel == 1)
        sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, width, bankOffsets);
    else
        sampleModel = (planarConfig == TiffConstants.PLANARCONFIG_CHUNKY) ? new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, samplesPerPixel, width * samplesPerPixel, bankOffsets) : new BandedSampleModel(DataBuffer.TYPE_BYTE, width, height, width, bankOffsets, offsets);
    byte[][] imageData;
    if (planarConfig == TiffConstants.PLANARCONFIG_CHUNKY)
        imageData = readPixelInterleaved(width, height, samplesPerPixel, stripOffsets, stripCounts);
    else
        imageData = readPlanar(width, height, samplesPerPixel, stripOffsets, stripCounts, rowsPerStrip);
    DataBufferByte dataBuff = new DataBufferByte(imageData, width * height, offsets);
    WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuff, new Point(0, 0));
    return new BufferedImage(colorModel, raster, false, null);
}
Example 57
Project: xml-graphics-commons-master  File: ImageLoaderImageIO.java View source code
/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException {
    RenderedImage imageData = null;
    IIOException firstException = null;
    IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA);
    boolean ignoreMetadata = (iiometa != null);
    boolean providerIgnoresICC = false;
    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream imgStream = ImageUtil.needImageInputStream(src);
    try {
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                reader.setInput(imgStream, false, ignoreMetadata);
                ImageReadParam param = getParam(reader, hints);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    //                        if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                    imageData = reader.read(pageIndex, param);
                    //                        }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    //Quit early, we have the image
                    break;
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    throw new ImageException("Error loading image using ImageIO codec", iae);
                } catch (IIOException iioe) {
                    if (firstException == null) {
                        firstException = iioe;
                    } else {
                        log.debug("non-first error loading image: " + iioe.getMessage());
                    }
                }
                try {
                    //Try fallback for CMYK images
                    BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param);
                    imageData = bi;
                    //Clear exception after successful fallback attempt
                    firstException = null;
                    break;
                } catch (IIOException iioe) {
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        XmlSourceUtil.closeQuietly(src);
    //TODO Some codecs may do late reading.
    }
    if (firstException != null) {
        throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException);
    }
    if (imageData == null) {
        throw new ImageException("No ImageIO ImageReader found .");
    }
    ColorModel cm = imageData.getColorModel();
    Color transparentColor = null;
    if (cm instanceof IndexColorModel) {
    //transparent color will be extracted later from the image
    } else {
        if (providerIgnoresICC && cm instanceof ComponentColorModel) {
            // Apply ICC Profile to Image by creating a new image with a new
            // color model.
            ICC_Profile iccProf = tryToExctractICCProfile(iiometa);
            if (iccProf != null) {
                ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(), cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType());
                WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null);
                imageData.copyData(wr);
                try {
                    BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                    imageData = bi;
                    cm = cm2;
                } catch (IllegalArgumentException iae) {
                    String msg = "Image " + info.getOriginalURI() + " has an incompatible color profile." + " The color profile will be ignored." + "\nColor model of loaded bitmap: " + cm + "\nColor model of color profile: " + cm2;
                    if (info.getCustomObjects().get("warningincustomobject") != null) {
                        info.getCustomObjects().put("warning", msg);
                    } else {
                        log.warn(msg);
                    }
                }
            }
        }
        // Retrieve the transparent color from the metadata
        if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) {
            Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
            Element dim = ImageIOUtil.getChild(metanode, "Transparency");
            if (dim != null) {
                Element child;
                child = ImageIOUtil.getChild(dim, "TransparentColor");
                if (child != null) {
                    String value = child.getAttribute("value");
                    if (value.length() == 0) {
                    //ignore
                    } else if (cm.getNumColorComponents() == 1) {
                        int gray = Integer.parseInt(value);
                        transparentColor = new Color(gray, gray, gray);
                    } else {
                        StringTokenizer st = new StringTokenizer(value);
                        transparentColor = new Color(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                    }
                }
            }
        }
    }
    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
        return new ImageBuffered(info, (BufferedImage) imageData, transparentColor);
    } else {
        return new ImageRendered(info, imageData, transparentColor);
    }
}
Example 58
Project: AppWorkUtils-master  File: ImageProvider.java View source code
/**
     * @param absolutePath
     * @return
     * @throws IOException
     */
private static BufferedImage read(final URL absolutePath) throws IOException {
    if (absolutePath == null) {
        throw new IllegalArgumentException("input == null!");
    }
    final ImageInputStream stream = ImageIO.createImageInputStream(absolutePath.openStream());
    BufferedImage bi = null;
    try {
        if (stream == null) {
            throw new IIOException("Can't create an ImageInputStream!");
        }
        bi = ImageIO.read(stream);
    } finally {
        try {
            stream.close();
        } catch (final Throwable e) {
        }
    }
    return bi;
}
Example 59
Project: geoserver-master  File: GeoTiffKvpTest.java View source code
private void checkJpegTiff(byte[] tiffContents) throws IOException, FileNotFoundException, IIOException {
    File file = File.createTempFile("bm_gtiff", "bm_gtiff.tiff", new File("./target"));
    FileUtils.writeByteArrayToFile(file, tiffContents);
    // TODO: check the tiff structure is the one requested
    final TIFFImageReader reader = (TIFFImageReader) new TIFFImageReaderSpi().createReaderInstance();
    reader.setInput(new FileImageInputStream(file));
    // compression
    final TIFFImageMetadata metadata = (TIFFImageMetadata) reader.getImageMetadata(0);
    assertNotNull(metadata);
    IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(0).getAsTree(TIFFImageMetadata.nativeMetadataFormatName);
    IIOMetadataNode field = getTiffField(root, BaselineTIFFTagSet.TAG_COMPRESSION);
    assertNotNull(field);
    assertEquals("JPEG", field.getFirstChild().getFirstChild().getAttributes().item(1).getNodeValue());
    assertEquals("7", field.getFirstChild().getFirstChild().getAttributes().item(0).getNodeValue());
    IIOMetadataNode node = metadata.getStandardDataNode();
    assertNotNull(node);
    assertEquals("PlanarConfiguration", node.getFirstChild().getNodeName());
    assertEquals("PixelInterleaved", node.getFirstChild().getAttributes().item(0).getNodeValue());
    // clean up
    reader.dispose();
}
Example 60
Project: jdcbot-master  File: jDCBot.java View source code
/**
	 * <b>Note:</b> The given directories' must exist and should be empty, as
	 * already existing files in them will overwritten without warning.
	 * @param path2DirForMiscData In this directory own file list, hash data, etc. will be kept.
	 * @param path2IncompleteDir Where incomplete downloads will be kept.
	 * @throws FileNotFoundException If the directory paths are not found or 'fileListHash'
	 * doesn't exist.
	 * @throws IIOException If the given path are not directories.
	 * @throws InstantiationException The read object from 'fileListHash' is not instance of FLDir.
	 * @throws ClassNotFoundException Class of FLDir serialized object cannot be found.
	 * @throws IOException Error occurred while reading from 'fileListHash'.
	 */
public final void setDirs(String path2DirForMiscData, String path2IncompleteDir) throws IIOException, FileNotFoundException, IOException {
    File miscDir = new File(path2DirForMiscData);
    File incompleteDir = new File(path2IncompleteDir);
    if (!miscDir.exists() || !incompleteDir.exists())
        throw new FileNotFoundException();
    if (!miscDir.isDirectory())
        throw new IIOException("Given path '" + path2DirForMiscData + "' is not a directory.");
    if (!incompleteDir.isDirectory())
        throw new IIOException("Given path '" + path2IncompleteDir + "' is not a directory.");
    this.miscDir = miscDir.getCanonicalPath();
    this.incompleteDir = incompleteDir.getCanonicalPath();
}
Example 61
Project: poreid-master  File: ImageUtil.java View source code
/**
     * Gets the destination image type.
     */
// NOTE: Code shamelessly copied from ImageReader.getDestination().
public static final ImageTypeSpecifier getDestinationType(ImageReadParam param, Iterator imageTypes) throws IIOException {
    if (imageTypes == null || !imageTypes.hasNext()) {
        throw new IllegalArgumentException("imageTypes null or empty!");
    }
    ImageTypeSpecifier imageType = null;
    // If param is non-null, use it
    if (param != null) {
        imageType = param.getDestinationType();
    }
    // No info from param, use fallback image type
    if (imageType == null) {
        Object o = imageTypes.next();
        if (!(o instanceof ImageTypeSpecifier)) {
            throw new IllegalArgumentException("Non-ImageTypeSpecifier retrieved from imageTypes!");
        }
        imageType = (ImageTypeSpecifier) o;
    } else {
        boolean foundIt = false;
        while (imageTypes.hasNext()) {
            ImageTypeSpecifier type = (ImageTypeSpecifier) imageTypes.next();
            if (type.equals(imageType)) {
                foundIt = true;
                break;
            }
        }
        if (!foundIt) {
            throw new IIOException("Destination type from ImageReadParam does not match!");
        }
    }
    return imageType;
}
Example 62
Project: traffic-balance-master  File: MapPanel.java View source code
public Image getImageFor(int x, int y, int zoom, boolean loadIfNeeded) throws IOException {
    if (map == null) {
        return null;
    }
    String file = getFileForImage(x, y, zoom, map.getTileFormat());
    if (cache.get(file) == null) {
        File en = new File(tilesLocation, file);
        if (cache.size() > 100) {
            ArrayList<String> list = new ArrayList<String>(cache.keySet());
            for (int i = 0; i < list.size(); i += 2) {
                Image remove = cache.remove(list.get(i));
                remove.flush();
            }
            if (log.isInfoEnabled()) {
                log.info(//$NON-NLS-1$ //$NON-NLS-2$
                "Before running gc on map tiles. Total Memory : " + (Runtime.getRuntime().totalMemory() >> 20) + " Mb. Used memory : " + //$NON-NLS-1$
                ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + //$NON-NLS-1$
                " Mb");
            }
            System.gc();
            if (log.isInfoEnabled()) {
                log.info(//$NON-NLS-1$ //$NON-NLS-2$
                "After running gc on map tiles. Total Memory : " + (Runtime.getRuntime().totalMemory() >> 20) + " Mb. Used memory : " + //$NON-NLS-1$
                ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + //$NON-NLS-1$
                " Mb");
            }
        }
        if (!downloader.isFileCurrentlyDownloaded(en)) {
            if (en.exists()) {
                //					long time = System.currentTimeMillis();
                try {
                    cache.put(file, ImageIO.read(en));
                //						if (log.isDebugEnabled()) {
                //							log.debug("Loaded file : " + file + " " + (System.currentTimeMillis() - time) + " ms");
                //						}
                } catch (IIOException e) {
                    log.error("Eror reading png " + x + " " + y + " zoom : " + zoom, e);
                }
            }
            if (loadIfNeeded && cache.get(file) == null) {
                String urlToLoad = map.getUrlToLoad(x, y, zoom);
                if (urlToLoad != null) {
                    downloader.requestToDownload(new DownloadRequest(urlToLoad, en, x, y, zoom));
                }
            }
        }
    }
    return cache.get(file);
}
Example 63
Project: autopsy-master  File: ImageUtils.java View source code
/**
     * Private template method designed to be used as the implementation of
     * public methods that pull particular (usually meta-)data out of a image
     * file.
     *
     * @param file              the file to extract the data from
     * @param errorTemplate     a message template used to log errors. Should
     *                          take one parameter: the file's unique path or
     *                          name.
     * @param propertyExtractor an implementation of {@link PropertyExtractor}
     *                          used to retrieve the specific property.
     *
     * @return the the value of the property extracted by the given
     *         propertyExtractor
     *
     * @throws IOException if there was a problem reading the property from the
     *                     file.
     *
     * @see PropertyExtractor
     * @see #getImageHeight(org.sleuthkit.datamodel.AbstractFile)
     */
private static <T> T getImageProperty(AbstractFile file, final String errorTemplate, PropertyExtractor<T> propertyExtractor) throws IOException {
    try (InputStream inputStream = new BufferedInputStream(new ReadContentInputStream(file))) {
        try (ImageInputStream input = ImageIO.createImageInputStream(inputStream)) {
            if (input == null) {
                IIOException iioException = new IIOException("Could not create ImageInputStream.");
                LOGGER.log(Level.WARNING, errorTemplate + iioException.toString(), getContentPathSafe(file));
                throw iioException;
            }
            Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(input);
                try {
                    return propertyExtractor.extract(reader);
                } catch (IOException ex) {
                    LOGGER.log(Level.WARNING, errorTemplate + ex.toString(), getContentPathSafe(file));
                    throw ex;
                } finally {
                    reader.dispose();
                }
            } else {
                IIOException iioException = new IIOException("No ImageReader found.");
                LOGGER.log(Level.WARNING, errorTemplate + iioException.toString(), getContentPathSafe(file));
                throw iioException;
            }
        }
    }
}
Example 64
Project: junrar-android-master  File: ImageInputStreamImpl.java View source code
/**
     * Resets the current stream byte and bit positions from the stack
     * of marked positions.
     *
     * <p> An <code>IOException</code> will be thrown if the previous
     * marked position lies in the discarded portion of the stream.
     *
     * @exception IOException if an I/O error occurs.
     */
public void reset() throws IOException {
    if (markByteStack.empty()) {
        return;
    }
    long pos = ((Long) markByteStack.pop()).longValue();
    if (pos < flushedPos) {
        throw new IIOException("Previous marked position has been discarded!");
    }
    seek(pos);
    int offset = ((Integer) markBitStack.pop()).intValue();
    setBitOffset(offset);
}
Example 65
Project: property-db-master  File: ImageInputStreamImpl.java View source code
/** {@collect.stats}
     * Resets the current stream byte and bit positions from the stack
     * of marked positions.
     *
     * <p> An <code>IOException</code> will be thrown if the previous
     * marked position lies in the discarded portion of the stream.
     *
     * @exception IOException if an I/O error occurs.
     */
public void reset() throws IOException {
    if (markByteStack.empty()) {
        return;
    }
    long pos = ((Long) markByteStack.pop()).longValue();
    if (pos < flushedPos) {
        throw new IIOException("Previous marked position has been discarded!");
    }
    seek(pos);
    int offset = ((Integer) markBitStack.pop()).intValue();
    setBitOffset(offset);
}
Example 66
Project: teamengine-master  File: ImageParser.java View source code
private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger) throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }
    // 2011-09-08
    String formatName = reader.getFormatName().toLowerCase();
    // PwD
    BufferedImage image = reader.read(frame);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                // 2011-09-08 PwD was
                node.setTextContent(formatName);
            // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try {
                    // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        // Fortify Mod: prevent external entity injection
                        tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (// 2011--08-23 PwD
                javax.imageio.IIOException // 2011--08-23 PwD
                e) {
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    dbf.setExpandEntityReferences(false);
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) {
                // 2011-08-24
                // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch(transparency) {
                    case Transparency.OPAQUE:
                        {
                            transparencyName = "Opaque";
                            break;
                        }
                    case Transparency.BITMASK:
                        {
                            transparencyName = "Bitmask";
                            break;
                        }
                    case Transparency.TRANSLUCENT:
                        {
                            transparencyName = "Translucent";
                            break;
                        }
                    default:
                        {
                            transparencyName = "Unknown";
                        }
                }
                node.setTextContent(transparencyName);
            } else if (node.getLocalName().equals("base64Data")) {
                // 2011-09-08
                // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}
Example 67
Project: lenient-pdf-compare-master  File: PDFImage.java View source code
/**
         * Attempt to decode the jpeg data
         * @return the successfully decoded image
         * @throws IOException if the image couldn't be decoded due
         *  to a lack of support or some IO problem
         */
private BufferedImage decode() throws IOException {
    ImageReadParam readParam = null;
    if (getDecode() != null) {
        // we have to allocate our own buffered image so that we can
        // install our colour model which will do the desired decode
        readParam = new ImageReadParam();
        SampleModel sm = cm.createCompatibleSampleModel(getWidth(), getHeight());
        final WritableRaster raster = Raster.createWritableRaster(sm, new Point(0, 0));
        readParam.setDestination(new BufferedImage(cm, raster, true, null));
    }
    final Iterator<ImageReader> jpegReaderIt = ImageIO.getImageReadersByFormatName("jpeg");
    IIOException lastIioEx = null;
    while (jpegReaderIt.hasNext()) {
        try {
            final ImageReader jpegReader = jpegReaderIt.next();
            jpegReader.setInput(ImageIO.createImageInputStream(new ByteBufferInputStream(jpegData)), true, false);
            return readImage(jpegReader, readParam);
        } catch (IIOException e) {
            jpegData.reset();
            lastIioEx = e;
        }
    }
    throw lastIioEx;
}
Example 68
Project: PDFrenderer-master  File: PDFImage.java View source code
/**
		 * Attempt to decode the jpeg data
		 * 
		 * @return the successfully decoded image
		 * @throws IOException
		 *             if the image couldn't be decoded due to a lack of support
		 *             or some IO problem
		 */
private BufferedImage decode() throws IOException {
    ImageReadParam readParam = null;
    if (getDecode() != null) {
        // we have to allocate our own buffered image so that we can
        // install our colour model which will do the desired decode
        readParam = new ImageReadParam();
        SampleModel sm = cm.createCompatibleSampleModel(getWidth(), getHeight());
        final WritableRaster raster = Raster.createWritableRaster(sm, new Point(0, 0));
        readParam.setDestination(new BufferedImage(cm, raster, true, null));
    }
    Iterator<ImageReader> jpegReaderIt = ImageIO.getImageReadersByFormatName("jpeg");
    IIOException lastIioEx = null;
    while (jpegReaderIt.hasNext()) {
        try {
            final ImageReader jpegReader = jpegReaderIt.next();
            jpegReader.setInput(ImageIO.createImageInputStream(new ByteBufferInputStream(jpegData)), true, false);
            try {
                return readImage(jpegReader, readParam);
            } catch (Exception e) {
                if (e instanceof IIOException) {
                    throw (IIOException) e;
                }
                throw new IIOException("Internal reader error?", e);
            } finally {
                jpegReader.dispose();
            }
        } catch (IIOException e) {
            jpegData.reset();
            lastIioEx = e;
        }
    }
    throw lastIioEx;
}
Example 69
Project: multimedia-indexing-master  File: ImageIOGreyScale.java View source code
/**
	 * Returns an <code>ImageInputStream</code> that will take its input from the given <code>Object</code>.
	 * The set of <code>ImageInputStreamSpi</code>s registered with the <code>IIORegistry</code> class is
	 * queried and the first one that is able to take input from the supplied object is used to create the
	 * returned <code>ImageInputStream</code>. If no suitable <code>ImageInputStreamSpi</code> exists,
	 * <code>null</code> is returned.
	 * 
	 * <p>
	 * The current cache settings from <code>getUseCache</code>and <code>getCacheDirectory</code> will be used
	 * to control caching.
	 * 
	 * @param input
	 *            an <code>Object</code> to be used as an input source, such as a <code>File</code>, readable
	 *            <code>RandomAccessFile</code>, or <code>InputStream</code>.
	 * 
	 * @return an <code>ImageInputStream</code>, or <code>null</code>.
	 * 
	 * @exception IllegalArgumentException
	 *                if <code>input</code> is <code>null</code>.
	 * @exception IOException
	 *                if a cache file is needed but cannot be created.
	 * 
	 * @see javax.imageio.spi.ImageInputStreamSpi
	 */
public static ImageInputStream createImageInputStream(Object input) throws IOException {
    if (input == null) {
        throw new IllegalArgumentException("input == null!");
    }
    Iterator iter;
    // Ensure category is present
    try {
        iter = theRegistry.getServiceProviders(ImageInputStreamSpi.class, true);
    } catch (IllegalArgumentException e) {
        return null;
    }
    boolean usecache = getUseCache() && hasCachePermission();
    while (iter.hasNext()) {
        ImageInputStreamSpi spi = (ImageInputStreamSpi) iter.next();
        if (spi.getInputClass().isInstance(input)) {
            try {
                return spi.createInputStreamInstance(input, usecache, getCacheDirectory());
            } catch (IOException e) {
                throw new IIOException("Can't create cache file!", e);
            }
        }
    }
    return null;
}
Example 70
Project: ps3mediaserver-master  File: DLNAMediaInfo.java View source code
public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly) {
    int i = 0;
    while (isParsing()) {
        if (i == 5) {
            setMediaparsed(true);
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        i++;
    }
    if (isMediaparsed()) {
        return;
    }
    if (inputFile != null) {
        if (inputFile.getFile() != null) {
            setSize(inputFile.getFile().length());
        } else {
            setSize(inputFile.getSize());
        }
        ProcessWrapperImpl pw = null;
        boolean ffmpeg_parsing = true;
        if (type == Format.AUDIO || ext instanceof AudioAsVideo) {
            ffmpeg_parsing = false;
            DLNAMediaAudio audio = new DLNAMediaAudio();
            if (inputFile.getFile() != null) {
                try {
                    AudioFile af = AudioFileIO.read(inputFile.getFile());
                    AudioHeader ah = af.getAudioHeader();
                    if (ah != null && !thumbOnly) {
                        int length = ah.getTrackLength();
                        int rate = ah.getSampleRateAsNumber();
                        if (ah.getEncodingType().toLowerCase().contains("flac 24")) {
                            audio.setBitsperSample(24);
                        }
                        audio.setSampleFrequency("" + rate);
                        setDuration((double) length);
                        setBitrate((int) ah.getBitRateAsNumber());
                        audio.getAudioProperties().setNumberOfChannels(2);
                        if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("mono")) {
                            audio.getAudioProperties().setNumberOfChannels(1);
                        } else if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("stereo")) {
                            audio.getAudioProperties().setNumberOfChannels(2);
                        } else if (ah.getChannels() != null) {
                            audio.getAudioProperties().setNumberOfChannels(Integer.parseInt(ah.getChannels()));
                        }
                        audio.setCodecA(ah.getEncodingType().toLowerCase());
                        if (audio.getCodecA().contains("(windows media")) {
                            audio.setCodecA(audio.getCodecA().substring(0, audio.getCodecA().indexOf("(windows media")).trim());
                        }
                    }
                    Tag t = af.getTag();
                    if (t != null) {
                        if (t.getArtworkList().size() > 0) {
                            setThumb(t.getArtworkList().get(0).getBinaryData());
                        } else {
                            if (configuration.getAudioThumbnailMethod() > 0) {
                                setThumb(CoverUtil.get().getThumbnailFromArtistAlbum(configuration.getAudioThumbnailMethod() == 1 ? CoverUtil.AUDIO_AMAZON : CoverUtil.AUDIO_DISCOGS, audio.getArtist(), audio.getAlbum()));
                            }
                        }
                        if (!thumbOnly) {
                            audio.setAlbum(t.getFirst(FieldKey.ALBUM));
                            audio.setArtist(t.getFirst(FieldKey.ARTIST));
                            audio.setSongname(t.getFirst(FieldKey.TITLE));
                            String y = t.getFirst(FieldKey.YEAR);
                            try {
                                if (y.length() > 4) {
                                    y = y.substring(0, 4);
                                }
                                audio.setYear(Integer.parseInt(((y != null && y.length() > 0) ? y : "0")));
                                y = t.getFirst(FieldKey.TRACK);
                                audio.setTrack(Integer.parseInt(((y != null && y.length() > 0) ? y : "1")));
                                audio.setGenre(t.getFirst(FieldKey.GENRE));
                            } catch (Throwable e) {
                                logger.debug("Error parsing unimportant metadata: " + e.getMessage());
                            }
                        }
                    }
                } catch (Throwable e) {
                    logger.debug("Error parsing audio file: {} - {}", e.getMessage(), e.getCause() != null ? e.getCause().getMessage() : "");
                    ffmpeg_parsing = false;
                }
                if (audio.getSongname() == null || audio.getSongname().length() == 0) {
                    audio.setSongname(inputFile.getFile().getName());
                }
                if (!ffmpeg_parsing) {
                    getAudioTracksList().add(audio);
                }
            }
        }
        if (type == Format.IMAGE && inputFile.getFile() != null) {
            try {
                ffmpeg_parsing = false;
                ImageInfo info = Sanselan.getImageInfo(inputFile.getFile());
                setWidth(info.getWidth());
                setHeight(info.getHeight());
                setBitsPerPixel(info.getBitsPerPixel());
                String formatName = info.getFormatName();
                if (formatName.startsWith("JPEG")) {
                    setCodecV("jpg");
                    IImageMetadata meta = Sanselan.getMetadata(inputFile.getFile());
                    if (meta != null && meta instanceof JpegImageMetadata) {
                        JpegImageMetadata jpegmeta = (JpegImageMetadata) meta;
                        TiffField tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_MODEL);
                        if (tf != null) {
                            setModel(tf.getStringValue().trim());
                        }
                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_EXPOSURE_TIME);
                        if (tf != null) {
                            setExposure((int) (1000 * tf.getDoubleValue()));
                        }
                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ORIENTATION);
                        if (tf != null) {
                            setOrientation(tf.getIntValue());
                        }
                        tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ISO);
                        if (tf != null) {
                            // Galaxy Nexus jpg pictures may contain multiple values, take the first
                            int[] isoValues = tf.getIntArrayValue();
                            setIso(isoValues[0]);
                        }
                    }
                } else if (formatName.startsWith("PNG")) {
                    setCodecV("png");
                } else if (formatName.startsWith("GIF")) {
                    setCodecV("gif");
                } else if (formatName.startsWith("TIF")) {
                    setCodecV("tiff");
                }
                setContainer(getCodecV());
            } catch (Throwable e) {
                logger.info("Error parsing image ({}) with Sanselan, switching to FFmpeg.", inputFile.getFile().getAbsolutePath());
            }
        }
        if (configuration.getImageThumbnailsEnabled() && type != Format.VIDEO && type != Format.AUDIO) {
            try {
                File thumbDir = new File(configuration.getTempFolder(), THUMBNAIL_DIRECTORY_NAME);
                logger.trace("Generating thumbnail for: {}", inputFile.getFile().getAbsolutePath());
                if (!thumbDir.exists() && !thumbDir.mkdirs()) {
                    logger.warn("Could not create thumbnail directory: {}", thumbDir.getAbsolutePath());
                } else {
                    File thumbFile = new File(thumbDir, inputFile.getFile().getName() + ".jpg");
                    String thumbFilename = thumbFile.getAbsolutePath();
                    logger.trace("Creating (temporary) thumbnail: {}", thumbFilename);
                    // Create the thumbnail image using the Thumbnailator library
                    final Builder<File> thumbnail = Thumbnails.of(inputFile.getFile());
                    thumbnail.size(320, 180);
                    thumbnail.outputFormat("jpg");
                    thumbnail.outputQuality(1.0f);
                    try {
                        thumbnail.toFile(thumbFilename);
                    } catch (IIOException e) {
                        logger.debug("Error generating thumbnail for: " + inputFile.getFile().getName());
                        logger.debug("The full error was: " + e);
                    }
                    File jpg = new File(thumbFilename);
                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();
                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }
                        is.close();
                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }
                    }
                }
            } catch (UnsupportedFormatException ufe) {
                logger.debug("Thumbnailator does not support the format of {}: {}", inputFile.getFile().getAbsolutePath(), ufe.getMessage());
            } catch (Exception e) {
                logger.debug("Thumbnailator could not generate a thumbnail for: {}", inputFile.getFile().getAbsolutePath(), e);
            }
        }
        if (ffmpeg_parsing) {
            if (!thumbOnly || !configuration.isUseMplayerForVideoThumbs()) {
                pw = getFFmpegThumbnail(inputFile);
            }
            String input = "-";
            boolean dvrms = false;
            if (inputFile.getFile() != null) {
                input = ProcessUtil.getShortFileNameIfWideChars(inputFile.getFile().getAbsolutePath());
                dvrms = inputFile.getFile().getAbsolutePath().toLowerCase().endsWith("dvr-ms");
            }
            if (!ffmpeg_failure && !thumbOnly) {
                if (input.equals("-")) {
                    input = "pipe:";
                }
                boolean matchs = false;
                ArrayList<String> lines = (ArrayList<String>) pw.getResults();
                int langId = 0;
                int subId = 0;
                ListIterator<String> FFmpegMetaData = lines.listIterator();
                for (String line : lines) {
                    FFmpegMetaData.next();
                    line = line.trim();
                    if (line.startsWith("Output")) {
                        matchs = false;
                    } else if (line.startsWith("Input")) {
                        if (line.indexOf(input) > -1) {
                            matchs = true;
                            setContainer(line.substring(10, line.indexOf(",", 11)).trim());
                        } else {
                            matchs = false;
                        }
                    } else if (matchs) {
                        if (line.indexOf("Duration") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Duration: ")) {
                                    String durationStr = token.substring(10);
                                    int l = durationStr.substring(durationStr.indexOf(".") + 1).length();
                                    if (l < 4) {
                                        durationStr = durationStr + "00".substring(0, 3 - l);
                                    }
                                    if (durationStr.indexOf("N/A") > -1) {
                                        setDuration(null);
                                    } else {
                                        setDuration(parseDurationString(durationStr));
                                    }
                                } else if (token.startsWith("bitrate: ")) {
                                    String bitr = token.substring(9);
                                    int spacepos = bitr.indexOf(" ");
                                    if (spacepos > -1) {
                                        String value = bitr.substring(0, spacepos);
                                        String unit = bitr.substring(spacepos + 1);
                                        setBitrate(Integer.parseInt(value));
                                        if (unit.equals("kb/s")) {
                                            setBitrate(1024 * getBitrate());
                                        }
                                        if (unit.equals("mb/s")) {
                                            setBitrate(1048576 * getBitrate());
                                        }
                                    }
                                }
                            }
                        } else if (line.indexOf("Audio:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            DLNAMediaAudio audio = new DLNAMediaAudio();
                            audio.setId(langId++);
                            if (a > -1 && b > a) {
                                audio.setLang(line.substring(a + 1, b));
                            } else {
                                audio.setLang(DLNAMediaLang.UND);
                            }
                            // Get TS IDs
                            a = line.indexOf("[0x");
                            b = line.indexOf("]", a);
                            if (a > -1 && b > a + 3) {
                                String idString = line.substring(a + 3, b);
                                try {
                                    audio.setId(Integer.parseInt(idString, 16));
                                } catch (NumberFormatException nfe) {
                                    logger.debug("Error parsing Stream ID: " + idString);
                                }
                            }
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                Integer nChannels;
                                if (token.startsWith("Stream")) {
                                    audio.setCodecA(token.substring(token.indexOf("Audio: ") + 7));
                                } else if (token.endsWith("Hz")) {
                                    audio.setSampleFrequency(token.substring(0, token.indexOf("Hz")).trim());
                                } else if ((nChannels = audioChannelLayout.get(token)) != null) {
                                    audio.getAudioProperties().setNumberOfChannels(nChannels);
                                } else if (// implicitly anchored at both ends e.g. ^ ... $
                                token.matches("\\d+(?:\\s+channels?)")) {
                                    // setNumberOfChannels(String) parses the number out of the string
                                    audio.getAudioProperties().setNumberOfChannels(token);
                                } else if (token.equals("s32")) {
                                    audio.setBitsperSample(32);
                                } else if (token.equals("s24")) {
                                    audio.setBitsperSample(24);
                                } else if (token.equals("s16")) {
                                    audio.setBitsperSample(16);
                                }
                            }
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();
                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }
                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);
                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            audio.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }
                            getAudioTracksList().add(audio);
                        } else if (line.indexOf("Video:") > -1) {
                            StringTokenizer st = new StringTokenizer(line, ",");
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken().trim();
                                if (token.startsWith("Stream")) {
                                    setCodecV(token.substring(token.indexOf("Video: ") + 7));
                                } else if ((token.indexOf("tbc") > -1 || token.indexOf("tb(c)") > -1)) {
                                    // A/V sync issues with newest FFmpeg, due to the new tbr/tbn/tbc outputs
                                    // Priority to tb(c)
                                    String frameRateDoubleString = token.substring(0, token.indexOf("tb")).trim();
                                    try {
                                        if (// tbc taken into account only if different than tbr
                                        !frameRateDoubleString.equals(getFrameRate())) {
                                            Double frameRateDouble = Double.parseDouble(frameRateDoubleString);
                                            setFrameRate(String.format(Locale.ENGLISH, "%.2f", frameRateDouble / 2));
                                        }
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse frame rate \"" + frameRateDoubleString + "\"");
                                    }
                                } else if ((token.indexOf("tbr") > -1 || token.indexOf("tb(r)") > -1) && getFrameRate() == null) {
                                    setFrameRate(token.substring(0, token.indexOf("tb")).trim());
                                } else if (// dvr-ms ?
                                (token.indexOf("fps") > -1 || token.indexOf("fps(r)") > -1) && // dvr-ms ?
                                getFrameRate() == null) {
                                    setFrameRate(token.substring(0, token.indexOf("fps")).trim());
                                } else if (token.indexOf("x") > -1) {
                                    String resolution = token.trim();
                                    if (resolution.indexOf(" [") > -1) {
                                        resolution = resolution.substring(0, resolution.indexOf(" ["));
                                    }
                                    try {
                                        setWidth(Integer.parseInt(resolution.substring(0, resolution.indexOf("x"))));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse width from \"" + resolution.substring(0, resolution.indexOf("x")) + "\"");
                                    }
                                    try {
                                        setHeight(Integer.parseInt(resolution.substring(resolution.indexOf("x") + 1)));
                                    } catch (NumberFormatException nfe) {
                                        logger.debug("Could not parse height from \"" + resolution.substring(resolution.indexOf("x") + 1) + "\"");
                                    }
                                }
                            }
                        } else if (line.indexOf("Subtitle:") > -1 && !line.contains("tx3g")) {
                            DLNAMediaSubtitle lang = new DLNAMediaSubtitle();
                            lang.setType((line.contains("dvdsub") && Platform.isWindows() ? SubtitleType.VOBSUB : SubtitleType.UNKNOWN));
                            int a = line.indexOf("(");
                            int b = line.indexOf("):", a);
                            if (a > -1 && b > a) {
                                lang.setLang(line.substring(a + 1, b));
                            } else {
                                lang.setLang(DLNAMediaLang.UND);
                            }
                            lang.setId(subId++);
                            int FFmpegMetaDataNr = FFmpegMetaData.nextIndex();
                            if (FFmpegMetaDataNr > -1) {
                                line = lines.get(FFmpegMetaDataNr);
                            }
                            if (line.indexOf("Metadata:") > -1) {
                                FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                line = lines.get(FFmpegMetaDataNr);
                                while (line.indexOf("      ") == 0) {
                                    if (line.toLowerCase().indexOf("title           :") > -1) {
                                        int aa = line.indexOf(": ");
                                        int bb = line.length();
                                        if (aa > -1 && bb > aa) {
                                            lang.setFlavor(line.substring(aa + 2, bb));
                                            break;
                                        }
                                    } else {
                                        FFmpegMetaDataNr = FFmpegMetaDataNr + 1;
                                        line = lines.get(FFmpegMetaDataNr);
                                    }
                                }
                            }
                            getSubtitleTracksList().add(lang);
                        }
                    }
                }
            }
            if (!thumbOnly && getContainer() != null && inputFile.getFile() != null && getContainer().equals("mpegts") && isH264() && getDurationInSeconds() == 0) {
                // Parse the duration
                try {
                    int length = MpegUtil.getDurationFromMpeg(inputFile.getFile());
                    if (length > 0) {
                        setDuration((double) length);
                    }
                } catch (IOException e) {
                    logger.trace("Error retrieving length: " + e.getMessage());
                }
            }
            if (configuration.isUseMplayerForVideoThumbs() && type == Format.VIDEO && !dvrms) {
                try {
                    getMplayerThumbnail(inputFile);
                    String frameName = "" + inputFile.hashCode();
                    frameName = configuration.getTempFolder() + "/mplayer_thumbs/" + frameName + "00000001/00000001.jpg";
                    frameName = frameName.replace(',', '_');
                    File jpg = new File(frameName);
                    if (jpg.exists()) {
                        InputStream is = new FileInputStream(jpg);
                        int sz = is.available();
                        if (sz > 0) {
                            setThumb(new byte[sz]);
                            is.read(getThumb());
                        }
                        is.close();
                        if (!jpg.delete()) {
                            jpg.deleteOnExit();
                        }
                        // Try and retry
                        if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) {
                            logger.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\"");
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Caught exception", e);
                }
            }
            if (type == Format.VIDEO && pw != null && getThumb() == null) {
                InputStream is;
                try {
                    is = pw.getInputStream(0);
                    int sz = is.available();
                    if (sz > 0) {
                        setThumb(new byte[sz]);
                        is.read(getThumb());
                    }
                    is.close();
                    if (sz > 0 && !net.pms.PMS.isHeadless()) {
                        BufferedImage image = ImageIO.read(new ByteArrayInputStream(getThumb()));
                        if (image != null) {
                            Graphics g = image.getGraphics();
                            g.setColor(Color.WHITE);
                            g.setFont(new Font("Arial", Font.PLAIN, 14));
                            int low = 0;
                            if (getWidth() > 0) {
                                if (getWidth() == 1920 || getWidth() == 1440) {
                                    g.drawString("1080p", 0, low += 18);
                                } else if (getWidth() == 1280) {
                                    g.drawString("720p", 0, low += 18);
                                }
                            }
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            ImageIO.write(image, "jpeg", out);
                            setThumb(out.toByteArray());
                        }
                    }
                } catch (IOException e) {
                    logger.debug("Error while decoding thumbnail: " + e.getMessage());
                }
            }
        }
        finalize(type, inputFile);
        setMediaparsed(true);
    }
}
Example 71
Project: josm-master  File: ImageProvider.java View source code
/**
     * Returns a <code>BufferedImage</code> as the result of decoding
     * a supplied <code>File</code> with an <code>ImageReader</code>
     * chosen automatically from among those currently registered.
     * The <code>File</code> is wrapped in an
     * <code>ImageInputStream</code>.  If no registered
     * <code>ImageReader</code> claims to be able to read the
     * resulting stream, <code>null</code> is returned.
     *
     * <p> The current cache settings from <code>getUseCache</code>and
     * <code>getCacheDirectory</code> will be used to control caching in the
     * <code>ImageInputStream</code> that is created.
     *
     * <p> Note that there is no <code>read</code> method that takes a
     * filename as a <code>String</code>; use this method instead after
     * creating a <code>File</code> from the filename.
     *
     * <p> This method does not attempt to locate
     * <code>ImageReader</code>s that can read directly from a
     * <code>File</code>; that may be accomplished using
     * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
     *
     * @param input a <code>File</code> to read from.
     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color, if any.
     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
     *
     * @return a <code>BufferedImage</code> containing the decoded
     * contents of the input, or <code>null</code>.
     *
     * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
     * @throws IOException if an error occurs during reading.
     * @see BufferedImage#getProperty
     * @since 7132
     */
public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException {
    CheckParameterUtil.ensureParameterNotNull(input, "input");
    if (!input.canRead()) {
        throw new IIOException("Can't read input file!");
    }
    ImageInputStream stream = ImageIO.createImageInputStream(input);
    if (stream == null) {
        throw new IIOException("Can't create an ImageInputStream!");
    }
    BufferedImage bi = read(stream, readMetadata, enforceTransparency);
    if (bi == null) {
        stream.close();
    }
    return bi;
}
Example 72
Project: extract-master  File: JPXImageReaderSpi.java View source code
@Override
public ImageReader createReaderInstance(final Object extension) throws IIOException {
    return new J2KImageReader(this);
}
Example 73
Project: jnode-master  File: JPEGImageReader.java View source code
private void decodeStream() throws IOException, IIOException {
    if (decoder != null)
        return;
    checkStream();
    decoder = new JPEGDecoderAdapter((ImageInputStream) input);
    decoder.decode();
}
Example 74
Project: framework-master  File: CustomTestBenchCommandExecutor.java View source code
/**
     * Compares the screenshot of the given element with the reference.
     *
     * Copied from TestBenchCommandExecutor
     */
public boolean compareScreen(WebElement element, File reference) throws IOException {
    BufferedImage image = null;
    try {
        image = ImageIO.read(reference);
    } catch (IIOException e) {
    }
    return compareScreen(element, image, reference.getName());
}
Example 75
Project: vaadin-master  File: CustomTestBenchCommandExecutor.java View source code
/**
     * Compares the screenshot of the given element with the reference.
     *
     * Copied from TestBenchCommandExecutor
     */
public boolean compareScreen(WebElement element, File reference) throws IOException {
    BufferedImage image = null;
    try {
        image = ImageIO.read(reference);
    } catch (IIOException e) {
    }
    return compareScreen(element, image, reference.getName());
}