Java Examples for javax.imageio.spi.ImageWriterSpi

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

Example 1
Project: Classeur-master  File: Engine.java View source code
public void metainf() {
    metainf("javax.imageio.spi.ImageReaderSpi", "uk.co.mmscomputing.imageio.bmp.BMPImageReaderSpi");
    metainf("javax.imageio.spi.ImageReaderSpi", "uk.co.mmscomputing.imageio.sff.SFFImageReaderSpi");
    metainf("javax.imageio.spi.ImageReaderSpi", "uk.co.mmscomputing.imageio.ppm.PPMImageReaderSpi");
    metainf("javax.imageio.spi.ImageReaderSpi", "uk.co.mmscomputing.imageio.tiff.TIFFImageReaderSpi");
    metainf("javax.imageio.spi.ImageWriterSpi", "uk.co.mmscomputing.imageio.bmp.BMPImageWriterSpi");
    metainf("javax.imageio.spi.ImageWriterSpi", "uk.co.mmscomputing.imageio.sff.SFFImageWriterSpi");
    metainf("javax.imageio.spi.ImageWriterSpi", "uk.co.mmscomputing.imageio.ppm.PBMImageWriterSpi");
    metainf("javax.imageio.spi.ImageWriterSpi", "uk.co.mmscomputing.imageio.ppm.PGMImageWriterSpi");
    metainf("javax.imageio.spi.ImageWriterSpi", "uk.co.mmscomputing.imageio.ppm.PPMImageWriterSpi");
    metainf("javax.imageio.spi.ImageWriterSpi", "uk.co.mmscomputing.imageio.tiff.TIFFImageWriterSpi");
    metainf("javax.sound.sampled.spi.MixerProvider", "uk.co.mmscomputing.sound.provider.MixerProvider");
}
Example 2
Project: imageio-ext-master  File: ImageIOUtilities.java View source code
// Method to return JDK core ImageReaderSPI/ImageWriterSPI for a 
// given formatName.
public static List<ImageReaderWriterSpi> getJDKImageReaderWriterSPI(ServiceRegistry registry, String formatName, boolean isReader) {
    IIORegistry iioRegistry = (IIORegistry) registry;
    final Class<? extends ImageReaderWriterSpi> spiClass;
    final String descPart;
    if (isReader) {
        spiClass = ImageReaderSpi.class;
        descPart = " image reader";
    } else {
        spiClass = ImageWriterSpi.class;
        descPart = " image writer";
    }
    // useOrdering
    final Iterator<? extends ImageReaderWriterSpi> iter = iioRegistry.getServiceProviders(spiClass, true);
    String formatNames[];
    ImageReaderWriterSpi provider;
    String desc = "standard " + formatName + descPart;
    String jiioPath = "com.sun.media.imageioimpl";
    Locale locale = Locale.getDefault();
    ArrayList<ImageReaderWriterSpi> list = new ArrayList<ImageReaderWriterSpi>();
    while (iter.hasNext()) {
        provider = (ImageReaderWriterSpi) iter.next();
        // Look for JDK core ImageWriterSpi's
        if (provider.getVendorName().startsWith("Sun Microsystems") && desc.equalsIgnoreCase(provider.getDescription(locale)) && // not JAI Image I/O plugins
        !provider.getPluginClassName().startsWith(jiioPath)) {
            // Get the formatNames supported by this Spi
            formatNames = provider.getFormatNames();
            for (int i = 0; i < formatNames.length; i++) {
                if (formatNames[i].equalsIgnoreCase(formatName)) {
                    // Must be a JDK provided ImageReader/ImageWriter
                    list.add(provider);
                    break;
                }
            }
        }
    }
    return list;
}
Example 3
Project: geotoolkit-master  File: MosaicImageWriter.java View source code
/**
     * Gets and initializes an {@link ImageWriter} that can encode the specified image. The
     * returned writer has its {@linkplain ImageWriter#setOutput output} already set. If the
     * output is different than the {@linkplain Tile#getInput tile input}, then it is probably
     * an {@link ImageOutputStream} and closing it is caller responsibility.
     * <p>
     * This method extracts an {@code ImageWriter} instance from the given cache, if possible.
     * If no suitable writer is available, then a new one is created but <strong>not</strong>
     * cached; it is caller responsibility to reset the writer and cache it after the write
     * operation has been completed.
     *
     * @param  tile  The tile to encode.
     * @param  image The image associated to the specified tile.
     * @param  cache An initially empty list of image writers created during the write process.
     * @return The image writer that seems to be the most appropriated (never {@code null}).
     * @throws IOException If no suitable image writer has been found or if an error occurred
     *         while creating an image writer or initializing it.
     */
private ReaderInputPair.WithWriter getImageWriter(final Tile tile, final RenderedImage image, final Queue<ReaderInputPair.WithWriter> cache) throws IOException {
    // Note: we rename "Tile.input" as "output" because we want to write in it.
    final Object output = tile.getInput();
    final Class<?> outputType = output.getClass();
    final ImageReaderSpi readerSpi = tile.getImageReaderSpi();
    // Created only if needed.
    ImageOutputStream stream = null;
    /*
         * The result of this method is determined entirely by the (readerSpi, outputType)
         * pair and by implementation of the user-overrideable filter(ImageWriter) method.
         * We will search iteratively for the first suitable entry.
         *
         * Note: Using Map<ReaderInputPair, Queue<ImageWriter>> could be more performant than
         * the iteration performed below, but the queue is usually very short since its length
         * is approximatively the number of processors. In addition, in the typical case where
         * all tiles use the same format, the iterator will stop at the first item in the queue.
         * So a Map would really bring no performance benefit for the "normal" case at the cost
         * of more complex code (harder to count the total number of ImageWriters and to dispose
         * the oldest ones).
         */
    final ReaderInputPair.WithWriter cacheEntry = new ReaderInputPair.WithWriter(readerSpi, outputType);
    if (cache != null) {
        ReaderInputPair.WithWriter candidate = null;
        synchronized (cache) {
            for (final Iterator<ReaderInputPair.WithWriter> it = cache.iterator(); it.hasNext(); ) {
                final ReaderInputPair.WithWriter c = it.next();
                if (cacheEntry.equals(c)) {
                    candidate = c;
                    it.remove();
                    break;
                }
            }
        }
        /*
             * If we have found a candidate, define its output and check if filter(ImageWriter)
             * accepts it. If the image writer is not accepted, the remaining of this method will
             * try to get an other instance from the IIORegistry.
             *
             * Note that the remaining of this method basically perform the same check 4 times,
             * each time using a different way to get the ImageWriter instances to test.
             */
        if (candidate != null) {
            final ImageWriter writer = candidate.writer;
            if (candidate.needStream) {
                stream = ImageIO.createImageOutputStream(output);
                writer.setOutput(stream);
            } else {
                writer.setOutput(output);
            }
            if (filter(writer)) {
                return candidate;
            }
            writer.dispose();
        }
    }
    /*
         * The search will be performed using two different strategies:
         *
         *  1) Check the plugins specified in 'spiNames' since we assume that they
         *     will encode the image in the best suited format for the reader.
         *  2) (to be run if the above strategy did not found a suitable writer),
         *     look for providers by their format name.
         */
    int spiNameIndex = 0;
    final String[] spiNames = readerSpi.getImageWriterSpiNames();
    final String[] formatNames = readerSpi.getFormatNames();
    final IIORegistry registry = IIORegistry.getDefaultInstance();
    final Set<ImageWriterSpi> providers = new LinkedHashSet<>();
    // To be initialized when first needed.
    List<ImageWriterSpi> ignored = null;
    // To be initialized when first needed.
    Iterator<ImageWriterSpi> it = null;
    boolean canIgnore = true;
    while (true) {
        // The exit point is in the middle of the loop, after "if (!it.hasNext())".
        final ImageWriterSpi spi;
        if (spiNames != null && spiNameIndex < spiNames.length) {
            /*
                 * ---- First strategy (see above comment) --------
                 */
            final String spiName = spiNames[spiNameIndex++];
            final Class<?> spiType;
            try {
                spiType = Class.forName(spiName);
            } catch (ClassNotFoundException e) {
                Logging.recoverableException(LOGGER, MosaicImageWriter.class, "getImageWriter", e);
                continue;
            }
            final Object candidate = registry.getServiceProviderByClass(spiType);
            if (!(candidate instanceof ImageWriterSpi)) {
                // No instance is registered for the given class. Search an other writer.
                continue;
            }
            spi = (ImageWriterSpi) candidate;
        } else {
            /*
                 * ---- Second strategy (see above comment) --------
                 *      To be run only after every providers
                 *      listed in 'spiNames' have been tried.
                 */
            if (it == null) {
                // Executed the first time that the second strategy is run.
                it = registry.getServiceProviders(ImageWriterSpi.class, true);
            }
            /*
                 * If we have examined every pertinent providers listed by IIORegistry but some
                 * of those providers have been ignored, and if we found no "normal" provider,
                 * then take a second look to the providers that we have ignored.
                 *
                 * The ignored providers are considered only if we found no "normal" providers,
                 * because the "normal" providers are examined again after this loop and should
                 * have precedence over the ignored providers.
                 */
            if (!it.hasNext()) {
                if (ignored == null || !providers.isEmpty()) {
                    // This is the only exit point of the while(true) loop.
                    break;
                }
                it = ignored.iterator();
                ignored = null;
                canIgnore = false;
            }
            spi = it.next();
            if (!ArraysExt.intersects(formatNames, spi.getFormatNames())) {
                // Not a provider for the format we are looking for.
                continue;
            }
            /*
                 * Ignore the providers that are wrappers around "native" providers, because we
                 * don't want to write metadata like ".prj" or ".tfw" files for every tiles.
                 * However keep trace of the ignored providers, so we can give a second look
                 * at them later if we find no "normal" provider.
                 */
            if (canIgnore && Tile.ignore(spi)) {
                if (ignored == null) {
                    ignored = new ArrayList<>(4);
                }
                ignored.add(spi);
                continue;
            }
        }
        /*
             * If a suitable writer is found and is capable to encode the output, returns
             * it immediately. Otherwise the writers are stored in an Set as we found them,
             * in order to try them again with an ImageOutputStream after this loop.
             */
        if (spi.canEncodeImage(image) && providers.add(spi)) {
            for (final Class<?> legalType : spi.getOutputTypes()) {
                if (legalType.isAssignableFrom(outputType)) {
                    final ImageWriter writer = spi.createWriterInstance();
                    writer.setOutput(output);
                    if (filter(writer)) {
                        if (stream != null) {
                            stream.close();
                        }
                        cacheEntry.writer = writer;
                        return cacheEntry;
                    }
                    writer.dispose();
                    break;
                }
            }
        }
    }
    /*
         * No provider accept the output directly. This output is typically a File or URL.
         * Creates an image output stream from it and try again.
         */
    if (!providers.isEmpty()) {
        if (stream == null) {
            stream = ImageIO.createImageOutputStream(output);
        }
        if (stream != null) {
            final Class<? extends ImageOutputStream> streamType = stream.getClass();
            for (final ImageWriterSpi spi : providers) {
                for (final Class<?> legalType : spi.getOutputTypes()) {
                    if (legalType.isAssignableFrom(streamType)) {
                        final ImageWriter writer = spi.createWriterInstance();
                        writer.setOutput(stream);
                        if (filter(writer)) {
                            cacheEntry.writer = writer;
                            cacheEntry.needStream = true;
                            return cacheEntry;
                        }
                        writer.dispose();
                        break;
                    }
                }
            }
        }
    }
    if (stream != null) {
        stream.close();
    }
    throw new UnsupportedImageFormatException(Errors.format(Errors.Keys.NoImageWriter));
}
Example 4
Project: openjdk-master  File: DataTransferer.java View source code
byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator<ImageWriter> writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            try (ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos)) {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 5
Project: PSD-master  File: ServiceRegistry.java View source code
@SuppressWarnings({ "UnnecessaryFullyQualifiedName" })
public static void main(String[] pArgs) {
    abstract class Spi {
    }
    class One extends Spi {
    }
    class Two extends Spi {
    }
    ServiceRegistry testRegistry = new ServiceRegistry(Arrays.<Class<?>>asList(java.nio.charset.spi.CharsetProvider.class, java.nio.channels.spi.SelectorProvider.class, javax.imageio.spi.ImageReaderSpi.class, javax.imageio.spi.ImageWriterSpi.class, Spi.class).iterator());
    testRegistry.registerApplicationClasspathSPIs();
    One one = new One();
    Two two = new Two();
    testRegistry.register(one, Spi.class);
    testRegistry.register(two, Spi.class);
    testRegistry.deregister(one);
    testRegistry.deregister(one, Spi.class);
    testRegistry.deregister(two, Spi.class);
    testRegistry.deregister(two);
    Iterator<Class<?>> categories = testRegistry.categories();
    System.out.println("Categories: ");
    while (categories.hasNext()) {
        Class<?> category = categories.next();
        System.out.println("  " + category.getName() + ":");
        Iterator<?> providers = testRegistry.providers(category);
        Object provider = null;
        while (providers.hasNext()) {
            provider = providers.next();
            System.out.println("    " + provider);
            if (provider instanceof javax.imageio.spi.ImageReaderWriterSpi) {
                System.out.println("    - " + ((javax.imageio.spi.ImageReaderWriterSpi) provider).getDescription(null));
            }
            // Don't remove last one, it's removed later to exercise more code :-)
            if (providers.hasNext()) {
                providers.remove();
            }
        }
        // Remove the last item from all categories
        if (provider != null) {
            Iterator containers = testRegistry.containingCategories(provider);
            int count = 0;
            while (containers.hasNext()) {
                if (category == containers.next()) {
                    containers.remove();
                    count++;
                }
            }
            if (count != 1) {
                System.err.println("Removed " + provider + " from " + count + " categories");
            }
        }
        // Remove all using providers iterator
        providers = testRegistry.providers(category);
        if (!providers.hasNext()) {
            System.out.println("All providers successfully deregistered");
        }
        while (providers.hasNext()) {
            System.err.println("Not removed: " + providers.next());
        }
    }
}
Example 6
Project: TwelveMonkeys-master  File: ServiceRegistry.java View source code
@SuppressWarnings({ "UnnecessaryFullyQualifiedName" })
public static void main(String[] pArgs) {
    abstract class Spi {
    }
    class One extends Spi {
    }
    class Two extends Spi {
    }
    ServiceRegistry testRegistry = new ServiceRegistry(Arrays.<Class<?>>asList(java.nio.charset.spi.CharsetProvider.class, java.nio.channels.spi.SelectorProvider.class, javax.imageio.spi.ImageReaderSpi.class, javax.imageio.spi.ImageWriterSpi.class, Spi.class).iterator());
    testRegistry.registerApplicationClasspathSPIs();
    One one = new One();
    Two two = new Two();
    testRegistry.register(one, Spi.class);
    testRegistry.register(two, Spi.class);
    testRegistry.deregister(one);
    testRegistry.deregister(one, Spi.class);
    testRegistry.deregister(two, Spi.class);
    testRegistry.deregister(two);
    Iterator<Class<?>> categories = testRegistry.categories();
    System.out.println("Categories: ");
    while (categories.hasNext()) {
        Class<?> category = categories.next();
        System.out.println("  " + category.getName() + ":");
        Iterator<?> providers = testRegistry.providers(category);
        Object provider = null;
        while (providers.hasNext()) {
            provider = providers.next();
            System.out.println("    " + provider);
            if (provider instanceof javax.imageio.spi.ImageReaderWriterSpi) {
                System.out.println("    - " + ((javax.imageio.spi.ImageReaderWriterSpi) provider).getDescription(null));
            }
            // Don't remove last one, it's removed later to exercise more code :-)
            if (providers.hasNext()) {
                providers.remove();
            }
        }
        // Remove the last item from all categories
        if (provider != null) {
            Iterator containers = testRegistry.containingCategories(provider);
            int count = 0;
            while (containers.hasNext()) {
                if (category == containers.next()) {
                    containers.remove();
                    count++;
                }
            }
            if (count != 1) {
                System.err.println("Removed " + provider + " from " + count + " categories");
            }
        }
        // Remove all using providers iterator
        providers = testRegistry.providers(category);
        if (!providers.hasNext()) {
            System.out.println("All providers successfully deregistered");
        }
        while (providers.hasNext()) {
            System.err.println("Not removed: " + providers.next());
        }
    }
}
Example 7
Project: freehep-ncolor-pdf-master  File: ImageIOExportFileType.java View source code
public void onRegistration(ServiceRegistry registry, Class category) {
    // run over all ImageWriterSpis and store their formats Alphabetically
    IIORegistry imageRegistry = IIORegistry.getDefaultInstance();
    Iterator providers = imageRegistry.getServiceProviders(ImageWriterSpi.class, false);
    ExportFileTypeRegistry exportRegistry = ExportFileTypeRegistry.getDefaultInstance(null);
    while (providers.hasNext()) {
        ImageWriterSpi writerSpi = (ImageWriterSpi) providers.next();
        String[] formats = writerSpi.getFileSuffixes();
        if ((formats != null) && (formats[0] != null)) {
            exportRegistry.add(new ImageExportFileType(writerSpi));
        } else {
            System.err.println(getClass() + ": Cannot register " + writerSpi + " because it has no filesuffixes.");
        }
    }
    /*
        // Look for the last ExportFileType so that these ImageExportFileTypes
        // are registered neatly behind that one.
        ExportFileType previous = null;
        Iterator exportTypes = registry.getServiceProviders(
                ExportFileType.class, true);
        while (exportTypes.hasNext()) {
            previous = (ExportFileType) exportTypes.next();
        }

        // run over all formats and book them as ExportFileTypes
        Iterator formats = formatSet.iterator();
        while (formats.hasNext()) {
            String format = (String) formats.next();
            ExportFileType export = ImageExportFileType.getInstance(format);
            if (export != null) {
                registry.registerServiceProvider(export, ExportFileType.class);
                if (previous != null) {
                    registry.unsetOrdering(ExportFileType.class, previous,
                            export);
                    registry.setOrdering(ExportFileType.class,
                            previous, export);
                    // System.out.println("Ordering set : "+result);
                }
                previous = export;
            } else {
                System.err.println(getClass() + ": Invalid format: " + format
                        + ".");
            }
        }
*/
    registry.deregisterServiceProvider(this, category);
}
Example 8
Project: freehep-vectorgraphics-master  File: ImageIOExportFileType.java View source code
@SuppressWarnings("unchecked")
public void onRegistration(ServiceRegistry registry, Class<?> category) {
    // run over all ImageWriterSpis and store their formats Alphabetically
    Iterator<ImageWriterSpi> providers = providerList.iterator();
    ExportFileTypeRegistry exportRegistry = ExportFileTypeRegistry.getDefaultInstance(null);
    while (providers.hasNext()) {
        ImageWriterSpi writerSpi = (ImageWriterSpi) providers.next();
        String[] formats = writerSpi.getFileSuffixes();
        if ((formats != null) && (formats[0] != null)) {
            exportRegistry.add(new ImageExportFileType(writerSpi));
        } else {
            System.err.println(getClass() + ": Cannot register " + writerSpi + " because it has no filesuffixes.");
        }
    }
    registry.deregisterServiceProvider(this, (Class<ImageIOExportFileType>) category);
}
Example 9
Project: jdk7u-jdk-master  File: DataTransferer.java View source code
protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 10
Project: ManagedRuntimeInitiative-master  File: DataTransferer.java View source code
protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 11
Project: openjdk8-jdk-master  File: DataTransferer.java View source code
protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 12
Project: JCGO-master  File: DataTransferer.java View source code
/**
     * Translates a Java Image into a byte array which contains
     * an image data in the given standard format.
     *
     * @param mimeType image MIME type, such as: image/png, image/jpeg
     */
protected byte[] imageToStandardBytes(Image image, String mimeType) throws IOException {
    RenderedImage renderedImage = null;
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    if (!writerIterator.hasNext()) {
        throw new IOException("No registered service provider can encode " + " an image to " + mimeType);
    }
    if (image instanceof RenderedImage) {
        renderedImage = (RenderedImage) image;
    } else {
        int width = 0;
        int height = 0;
        if (image instanceof sun.awt.image.Image) {
            ImageRepresentation ir = ((sun.awt.image.Image) image).getImageRep();
            ir.reconstruct(ImageObserver.ALLBITS);
            width = ir.getWidth();
            height = ir.getHeight();
        } else {
            width = image.getWidth(null);
            height = image.getHeight(null);
        }
        ColorModel model = ColorModel.getRGBdefault();
        WritableRaster raster = model.createCompatibleWritableRaster(width, height);
        BufferedImage bufferedImage = new BufferedImage(model, raster, model.isAlphaPremultiplied(), null);
        Graphics g = bufferedImage.getGraphics();
        try {
            g.drawImage(image, 0, 0, width, height, null);
        } finally {
            g.dispose();
        }
        renderedImage = bufferedImage;
    }
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 13
Project: cocoon-master  File: ImageOpReader.java View source code
private void write(BufferedImage image) throws ProcessingException, IOException {
    ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(image);
    Iterator writers = ImageIO.getImageWriters(its, format);
    ImageWriter writer = null;
    if (writers.hasNext()) {
        writer = (ImageWriter) writers.next();
    }
    if (writer == null) {
        throw new ProcessingException("Unable to find a ImageWriter: " + format);
    }
    ImageWriterSpi spi = writer.getOriginatingProvider();
    String[] mimetypes = spi.getMIMETypes();
    if (getLogger().isInfoEnabled()) {
        getLogger().info("Setting content-type: " + mimetypes[0]);
    }
    response.setHeader("Content-Type", mimetypes[0]);
    ImageOutputStream output = ImageIO.createImageOutputStream(out);
    try {
        writer.setOutput(output);
        writer.write(image);
    } finally {
        writer.dispose();
        output.close();
        out.flush();
    // Niclas Hedhman: Stream is closed in superclass.
    }
}
Example 14
Project: rrd4j-master  File: ImageWorker.java View source code
void saveImage(OutputStream stream, String type, float quality, boolean interlaced) throws IOException {
    //The first writer is arbitratry choosen
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(type);
    ImageWriter writer = iter.next();
    BufferedImage outputImage = img;
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    ImageWriterSpi imgProvider = writer.getOriginatingProvider();
    img.coerceData(false);
    // JPEG don't like transparency
    if (!imgProvider.canEncodeImage(outputImage) || "image/jpeg".equals(imgProvider.getMIMETypes()[0].toLowerCase())) {
        int w = img.getWidth();
        int h = img.getHeight();
        outputImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        outputImage.getGraphics().drawImage(img, 0, 0, w, h, null);
        if (!imgProvider.canEncodeImage(outputImage)) {
            throw new RuntimeException("Invalid image type");
        }
    }
    //If lossy compression, use the quality
    if (!imgProvider.isFormatLossless()) {
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(quality);
    }
    if (iwp.canWriteProgressive()) {
        iwp.setProgressiveMode(interlaced ? ImageWriteParam.MODE_DEFAULT : ImageWriteParam.MODE_DISABLED);
    }
    if (!imgProvider.canEncodeImage(outputImage)) {
        throw new RuntimeException("Invalid image type");
    }
    ImageOutputStream imageStream = ImageIO.createImageOutputStream(stream);
    writer.setOutput(imageStream);
    try {
        writer.write(null, new IIOImage(outputImage, null, null), iwp);
        imageStream.flush();
    } catch (IOException e) {
        writer.abort();
        throw e;
    } finally {
        try {
            imageStream.close();
        } catch (Exception inner) {
        }
        writer.dispose();
    }
}
Example 15
Project: Weasis-master  File: ImageioCodec.java View source code
// ================================================================================
// OSGI service implementation
// ================================================================================
@Activate
protected void activate(ComponentContext context) {
    // Do not use cache. Images must be download locally before reading them.
    ImageIO.setUseCache(false);
    // SPI Issue Resolution
    // Register imageio SPI with the classloader of this bundle
    // and unregister imageio SPI if imageio.jar is also in the jre/lib/ext folder
    Class[] jaiCodecs = { ChannelImageInputStreamSpi.class, ChannelImageOutputStreamSpi.class, J2KImageReaderSpi.class, J2KImageReaderCodecLibSpi.class, WBMPImageReaderSpi.class, BMPImageReaderSpi.class, PNMImageReaderSpi.class, RawImageReaderSpi.class, TIFFImageReaderSpi.class, J2KImageWriterSpi.class, J2KImageWriterCodecLibSpi.class, WBMPImageWriterSpi.class, BMPImageWriterSpi.class, GIFImageWriterSpi.class, PNMImageWriterSpi.class, RawImageWriterSpi.class, TIFFImageWriterSpi.class };
    for (Class c : jaiCodecs) {
        ImageioUtil.registerServiceProvider(c);
    }
    // Set priority to these codec which have better performance to the one in JRE
    ImageioUtil.registerServiceProviderInHighestPriority(CLibJPEGImageReaderSpi.class, ImageReaderSpi.class, //$NON-NLS-1$
    "jpeg");
    ImageioUtil.registerServiceProviderInHighestPriority(CLibJPEGImageWriterSpi.class, ImageWriterSpi.class, //$NON-NLS-1$
    "jpeg");
    //$NON-NLS-1$
    ImageioUtil.registerServiceProviderInHighestPriority(CLibPNGImageReaderSpi.class, ImageReaderSpi.class, "png");
    //$NON-NLS-1$
    ImageioUtil.registerServiceProviderInHighestPriority(CLibPNGImageWriterSpi.class, ImageWriterSpi.class, "png");
    // TODO Should be in properties?
    // Unregister sun native jpeg codec
    // ImageioUtil.unRegisterServiceProvider(registry, CLibJPEGImageReaderSpi.class);
    // Register the ImageRead and ImageWrite operation for JAI
    new ImageReadWriteSpi().updateRegistry(JAIUtil.getOperationRegistry());
}
Example 16
Project: ae-awt-master  File: DataTransferer.java View source code
protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 17
Project: ikvm-openjdk-master  File: DataTransferer.java View source code
protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 18
Project: JDK-master  File: BMPImageWriter.java View source code
protected boolean canEncodeImage(int compression, ImageTypeSpecifier imgType) {
    ImageWriterSpi spi = this.getOriginatingProvider();
    if (!spi.canEncodeImage(imgType)) {
        return false;
    }
    int biType = imgType.getBufferedImageType();
    int bpp = imgType.getColorModel().getPixelSize();
    if (compressionType == BI_RLE4 && bpp != 4) {
        // only 4bpp images can be encoded as BI_RLE4
        return false;
    }
    if (compressionType == BI_RLE8 && bpp != 8) {
        // only 8bpp images can be encoded as BI_RLE8
        return false;
    }
    if (bpp == 16) {
        /*
             * Technically we expect that we may be able to
             * encode only some of SinglePixelPackedSampleModel
             * images here.
             *
             * In addition we should take into account following:
             *
             * 1. BI_RGB case, according to the MSDN description:
             *
             *     The bitmap has a maximum of 2^16 colors. If the
             *     biCompression member of the BITMAPINFOHEADER is BI_RGB,
             *     the bmiColors member of BITMAPINFO is NULL. Each WORD
             *     in the bitmap array represents a single pixel. The
             *     relative intensities of red, green, and blue are
             *     represented with five bits for each color component.
             *
             * 2. BI_BITFIELDS case, according ot the MSDN description:
             *
             *     Windows 95/98/Me: When the biCompression member is
             *     BI_BITFIELDS, the system supports only the following
             *     16bpp color masks: A 5-5-5 16-bit image, where the blue
             *     mask is 0x001F, the green mask is 0x03E0, and the red mask
             *     is 0x7C00; and a 5-6-5 16-bit image, where the blue mask
             *     is 0x001F, the green mask is 0x07E0, and the red mask is
             *     0xF800.
             */
        boolean canUseRGB = false;
        boolean canUseBITFIELDS = false;
        SampleModel sm = imgType.getSampleModel();
        if (sm instanceof SinglePixelPackedSampleModel) {
            int[] sizes = ((SinglePixelPackedSampleModel) sm).getSampleSize();
            canUseRGB = true;
            canUseBITFIELDS = true;
            for (int i = 0; i < sizes.length; i++) {
                canUseRGB &= (sizes[i] == 5);
                canUseBITFIELDS &= ((sizes[i] == 5) || (i == 1 && sizes[i] == 6));
            }
        }
        return (((compressionType == BI_RGB) && canUseRGB) || ((compressionType == BI_BITFIELDS) && canUseBITFIELDS));
    }
    return true;
}
Example 19
Project: multimedia-indexing-master  File: ImageIOGreyScale.java View source code
/**
	 * Returns an <code>Iterator</code> containing all currently registered <code>ImageWriter</code>s that
	 * claim to be able to encode the named format.
	 * 
	 * @param formatName
	 *            a <code>String</code> containing the informal name of a format (<i>e.g.</i>, "jpeg" or
	 *            "tiff".
	 * 
	 * @return an <code>Iterator</code> containing <code>ImageWriter</code>s.
	 * 
	 * @exception IllegalArgumentException
	 *                if <code>formatName</code> is <code>null</code>.
	 * 
	 * @see javax.imageio.spi.ImageWriterSpi#getFormatNames
	 */
public static Iterator<ImageWriter> getImageWritersByFormatName(String formatName) {
    if (formatName == null) {
        throw new IllegalArgumentException("formatName == null!");
    }
    Iterator iter;
    // Ensure category is present
    try {
        iter = theRegistry.getServiceProviders(ImageWriterSpi.class, new ContainsFilter(writerFormatNamesMethod, formatName), true);
    } catch (IllegalArgumentException e) {
        return new HashSet().iterator();
    }
    return new ImageWriterIterator(iter);
}
Example 20
Project: property-db-master  File: ImageWriter.java View source code
/** {@collect.stats}
     * Sets the destination to the given
     * <code>ImageOutputStream</code> or other <code>Object</code>.
     * The destination is assumed to be ready to accept data, and will
     * not be closed at the end of each write. This allows distributed
     * imaging applications to transmit a series of images over a
     * single network connection.  If <code>output</code> is
     * <code>null</code>, any currently set output will be removed.
     *
     * <p> If <code>output</code> is an
     * <code>ImageOutputStream</code>, calls to the
     * <code>write</code>, <code>writeToSequence</code>, and
     * <code>prepareWriteEmpty</code>/<code>endWriteEmpty</code>
     * methods will preserve the existing contents of the stream.
     * Other write methods, such as <code>writeInsert</code>,
     * <code>replaceStreamMetadata</code>,
     * <code>replaceImageMetadata</code>, <code>replacePixels</code>,
     * <code>prepareInsertEmpty</code>/<code>endInsertEmpty</code>,
     * and <code>endWriteSequence</code>, require the full contents
     * of the stream to be readable and writable, and may alter any
     * portion of the stream.
     *
     * <p> Use of a general <code>Object</code> other than an
     * <code>ImageOutputStream</code> is intended for writers that
     * interact directly with an output device or imaging protocol.
     * The set of legal classes is advertised by the writer's service
     * provider's <code>getOutputTypes</code> method; most writers
     * will return a single-element array containing only
     * <code>ImageOutputStream.class</code> to indicate that they
     * accept only an <code>ImageOutputStream</code>.
     *
     * <p> The default implementation sets the <code>output</code>
     * instance variable to the value of <code>output</code> after
     * checking <code>output</code> against the set of classes
     * advertised by the originating provider, if there is one.
     *
     * @param output the <code>ImageOutputStream</code> or other
     * <code>Object</code> to use for future writing.
     *
     * @exception IllegalArgumentException if <code>output</code> is
     * not an instance of one of the classes returned by the
     * originating service provider's <code>getOutputTypes</code>
     * method.
     *
     * @see #getOutput
     */
public void setOutput(Object output) {
    if (output != null) {
        ImageWriterSpi provider = getOriginatingProvider();
        if (provider != null) {
            Class[] classes = provider.getOutputTypes();
            boolean found = false;
            for (int i = 0; i < classes.length; i++) {
                if (classes[i].isInstance(output)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new IllegalArgumentException("Illegal output type!");
            }
        }
    }
    this.output = output;
}
Example 21
Project: geowebcache-master  File: ImageEncoderImpl.java View source code
/**
     * Encodes the selected image with the defined output object. The user can set the aggressive outputStream if supported.
     * 
     * @param image Image to write.
     * @param destination Destination object where the image is written.
     * @param aggressiveOutputStreamOptimization Parameter used if aggressive outputStream optimization must be used.
     * @throws IOException
     */
public void encode(RenderedImage image, Object destination, boolean aggressiveOutputStreamOptimization, MimeType type, Map<String, ?> map) throws Exception {
    if (!isAggressiveOutputStreamSupported() && aggressiveOutputStreamOptimization) {
        throw new UnsupportedOperationException(OPERATION_NOT_SUPPORTED);
    }
    // Selection of the first priority writerSpi
    ImageWriterSpi newSpi = getWriterSpi();
    if (newSpi != null) {
        // Creation of the associated Writer
        ImageWriter writer = null;
        ImageOutputStream stream = null;
        try {
            writer = newSpi.createWriterInstance();
            // Check if the input object is an OutputStream
            if (destination instanceof OutputStream) {
                // Use of the ImageOutputStreamAdapter
                if (isAggressiveOutputStreamSupported()) {
                    stream = new ImageOutputStreamAdapter((OutputStream) destination);
                } else {
                    stream = new MemoryCacheImageOutputStream((OutputStream) destination);
                }
                // Preparation of the ImageWriteParams
                ImageWriteParam params = null;
                RenderedImage finalImage = image;
                if (helper != null) {
                    params = helper.prepareParams(inputParams, writer);
                    finalImage = helper.prepareImage(image, type);
                }
                // Image writing
                writer.setOutput(stream);
                writer.write(null, new IIOImage(finalImage, null, null), params);
            } else {
                throw new IllegalArgumentException("Wrong output object");
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } finally {
            // Writer disposal
            if (writer != null) {
                writer.dispose();
            }
            // Stream closure
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
                stream = null;
            }
        }
    }
}
Example 22
Project: haskell-java-parser-master  File: ImageIO.java View source code
public boolean filter(Object provider) {
    if (provider instanceof ImageReaderSpi) {
        ImageWriterSpi spi = (ImageWriterSpi) provider;
        String[] formatNames = spi.getFormatNames();
        for (int i = formatNames.length - 1; i >= 0; --i) if (formatName.equals(formatNames[i]))
            return true;
    }
    return false;
}
Example 23
Project: constellation-master  File: WMSRequestsTest.java View source code
/**
     * Initialize the list of layers from the defined providers in Constellation's configuration.
     */
@PostConstruct
public void initLayerList() {
    SpringHelper.setApplicationContext(applicationContext);
    if (!initialized) {
        try {
            try {
                layerBusiness.removeAll();
                serviceBusiness.deleteAll();
                dataBusiness.deleteAll();
                providerBusiness.removeAll();
            } catch (Exception ex) {
            }
            // coverage-file datastore
            final File rootDir = AbstractGrizzlyServer.initDataDirectory();
            final ProviderFactory covFilefactory = DataProviders.getInstance().getFactory("coverage-store");
            final ParameterValueGroup sourceCF = covFilefactory.getProviderDescriptor().createValue();
            getOrCreateValue(sourceCF, "id").setValue("coverageTestSrc");
            getOrCreateValue(sourceCF, "load_all").setValue(true);
            final ParameterValueGroup choice3 = getOrCreateGroup(sourceCF, "choice");
            final ParameterValueGroup srcCFConfig = getOrCreateGroup(choice3, "FileCoverageStoreParameters");
            getOrCreateValue(srcCFConfig, "path").setValue(new URL("file:" + rootDir.getAbsolutePath() + "/org/constellation/data/SSTMDE200305.png"));
            getOrCreateValue(srcCFConfig, "type").setValue("AUTO");
            getOrCreateValue(srcCFConfig, "namespace").setValue("no namespace");
            providerBusiness.storeProvider("coverageTestSrc", null, ProviderType.LAYER, "coverage-store", sourceCF);
            dataBusiness.create(new QName("SSTMDE200305"), "coverageTestSrc", "COVERAGE", false, true, null, null);
            final ProviderFactory ffactory = DataProviders.getInstance().getFactory("feature-store");
            final File outputDir = initDataDirectory();
            final ParameterValueGroup sourcef = ffactory.getProviderDescriptor().createValue();
            getOrCreateValue(sourcef, "id").setValue("shapeSrc");
            getOrCreateValue(sourcef, "load_all").setValue(true);
            final ParameterValueGroup choice = getOrCreateGroup(sourcef, "choice");
            final ParameterValueGroup shpconfig = createGroup(choice, "ShapefileParametersFolder");
            String path;
            if (outputDir.getAbsolutePath().endsWith("org/constellation/ws/embedded/wms111/styles")) {
                path = outputDir.getAbsolutePath().substring(0, outputDir.getAbsolutePath().indexOf("org/constellation/ws/embedded/wms111/styles"));
            } else {
                path = outputDir.getAbsolutePath();
            }
            getOrCreateValue(shpconfig, "url").setValue(new URL("file:" + path + "/org/constellation/ws/embedded/wms111/shapefiles"));
            getOrCreateValue(shpconfig, "namespace").setValue("http://www.opengis.net/gml");
            final ParameterValueGroup layer = getOrCreateGroup(sourcef, "Layer");
            getOrCreateValue(layer, "name").setValue("NamedPlaces");
            getOrCreateValue(layer, "style").setValue("cite_style_NamedPlaces");
            providerBusiness.storeProvider("shapeSrc", null, ProviderType.LAYER, "feature-store", sourcef);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "BuildingCenters"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "BasicPolygons"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "Bridges"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "Streams"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "Lakes"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "NamedPlaces"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "Buildings"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "RoadSegments"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "DividedRoutes"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "Forests"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "MapNeatline"), "shapeSrc", "VECTOR", false, true, null, null);
            dataBusiness.create(new QName("http://www.opengis.net/gml", "Ponds"), "shapeSrc", "VECTOR", false, true, null, null);
            final LayerContext config = new LayerContext();
            config.getCustomParameters().put("shiroAccessible", "false");
            config.setGetFeatureInfoCfgs(FeatureInfoUtilities.createGenericConfiguration());
            serviceBusiness.create("wms", "default", config, null);
            final Details details = serviceBusiness.getInstanceDetails("wms", "default", "eng");
            details.getServiceConstraints().setLayerLimit(100);
            serviceBusiness.setInstanceDetails("wms", "default", details, "eng", true);
            layerBusiness.add("SSTMDE200305", null, "coverageTestSrc", null, "default", "wms", null);
            layerBusiness.add("BuildingCenters", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("BasicPolygons", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("Bridges", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("Streams", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("Lakes", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("NamedPlaces", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("Buildings", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("RoadSegments", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("DividedRoutes", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("Forests", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("MapNeatline", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            layerBusiness.add("Ponds", "http://www.opengis.net/gml", "shapeSrc", null, "default", "wms", null);
            final LayerContext config2 = new LayerContext();
            config2.setSupportedLanguages(new Languages(Arrays.asList(new Language("fre"), new Language("eng", true))));
            config2.getCustomParameters().put("shiroAccessible", "false");
            config2.setGetFeatureInfoCfgs(FeatureInfoUtilities.createGenericConfiguration());
            serviceBusiness.create("wms", "wms1", config2, null);
            layerBusiness.add("Lakes", "http://www.opengis.net/gml", "shapeSrc", null, "wms1", "wms", null);
            final Details serviceEng = new Details();
            serviceEng.setDescription("Serveur Cartographique.  Contact: someone@geomatys.fr.  Carte haute qualité.");
            serviceEng.setIdentifier("wms1");
            serviceEng.setKeywords(Arrays.asList("WMS"));
            serviceEng.setName("this is the default english capabilities");
            final AccessConstraint cstr = new AccessConstraint("NONE", "NONE", 20, 1024, 1024);
            serviceEng.setServiceConstraints(cstr);
            final Contact ct = new Contact();
            serviceEng.setServiceContact(ct);
            serviceEng.setVersions(Arrays.asList("1.1.1", "1.3.0"));
            serviceBusiness.setInstanceDetails("wms", "wms1", serviceEng, "eng", true);
            //ConfigDirectory.writeServiceMetadata("wms1", "wms", serviceEng, "eng");
            final Details serviceFre = new Details();
            serviceFre.setDescription("Serveur Cartographique.  Contact: someone@geomatys.fr.  Carte haute qualité.");
            serviceFre.setIdentifier("wms1");
            serviceFre.setKeywords(Arrays.asList("WMS"));
            serviceFre.setName("Ceci est le document capabilities français");
            serviceFre.setServiceConstraints(cstr);
            serviceFre.setServiceContact(ct);
            serviceFre.setVersions(Arrays.asList("1.1.1", "1.3.0"));
            serviceBusiness.setInstanceDetails("wms", "wms1", serviceFre, "fre", false);
            final LayerContext config3 = new LayerContext();
            config3.getCustomParameters().put("shiroAccessible", "false");
            config3.getCustomParameters().put("supported_versions", "1.3.0");
            config3.setGetFeatureInfoCfgs(FeatureInfoUtilities.createGenericConfiguration());
            final Details details3 = new Details();
            details3.setIdentifier("wms2");
            details3.setName("wms2");
            details3.setVersions(Arrays.asList("1.3.0"));
            serviceBusiness.create("wms", "wms2", config3, details3);
            layerBusiness.add("SSTMDE200305", null, "coverageTestSrc", null, "wms2", "wms", null);
            layerBusiness.add("BuildingCenters", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("BasicPolygons", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("Bridges", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("Streams", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("Lakes", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("NamedPlaces", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("Buildings", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("RoadSegments", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("DividedRoutes", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("Forests", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("MapNeatline", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            layerBusiness.add("Ponds", "http://www.opengis.net/gml", "shapeSrc", null, "wms2", "wms", null);
            initServer(null, null);
            pool = WMSMarshallerPool.getInstance();
            WorldFileImageReader.Spi.registerDefaults(null);
            WMSPortrayal.setEmptyExtension(true);
            //reset values, only allow pure java readers
            for (String jn : ImageIO.getReaderFormatNames()) {
                Registry.setNativeCodecAllowed(jn, ImageReaderSpi.class, false);
            }
            //reset values, only allow pure java writers
            for (String jn : ImageIO.getWriterFormatNames()) {
                Registry.setNativeCodecAllowed(jn, ImageWriterSpi.class, false);
            }
            DataProviders.getInstance().reload();
            initialized = true;
        } catch (Exception ex) {
            Logging.getLogger("org.constellation.ws.embedded").log(Level.SEVERE, null, ex);
        }
    }
}
Example 24
Project: geoserver-master  File: GeoserverInitStartupListener.java View source code
public void contextInitialized(ServletContextEvent sce) {
    // start up tctool - remove it before committing!!!!
    // new tilecachetool.TCTool().setVisible(true);
    // Register logging, and bridge to JAI logging
    GeoTools.init((Hints) null);
    // Custom GeoTools ImagingListener used to ignore common warnings 
    JAI.getDefaultInstance().setImagingListener(new ImagingListener() {

        final Logger LOGGER = Logging.getLogger("javax.media.jai");

        @Override
        public boolean errorOccurred(String message, Throwable thrown, Object where, boolean isRetryable) throws RuntimeException {
            if (isSerializableRenderedImageFinalization(where, thrown)) {
                LOGGER.log(Level.FINEST, message, thrown);
            } else if (message.contains("Continuing in pure Java mode")) {
                LOGGER.log(Level.FINE, message, thrown);
            } else {
                LOGGER.log(Level.INFO, message, thrown);
            }
            // we are not trying to recover
            return false;
        }

        private boolean isSerializableRenderedImageFinalization(Object where, Throwable t) {
            if (!(where instanceof SerializableRenderedImage)) {
                return false;
            }
            // check if it's the finalizer
            StackTraceElement[] elements = t.getStackTrace();
            for (StackTraceElement element : elements) {
                if (element.getMethodName().equals("finalize") && element.getClassName().endsWith("SerializableRenderedImage"))
                    return true;
            }
            return false;
        }
    });
    // setup concurrent operation registry
    JAI jaiDef = JAI.getDefaultInstance();
    if (!(jaiDef.getOperationRegistry() instanceof ConcurrentOperationRegistry || jaiDef.getOperationRegistry() instanceof it.geosolutions.jaiext.ConcurrentOperationRegistry)) {
        jaiDef.setOperationRegistry(ConcurrentOperationRegistry.initializeRegistry());
    }
    // setup the concurrent tile cache (has proper memory limit handling also for small tiles)
    if (!(jaiDef.getTileCache() instanceof ConcurrentTileCacheMultiMap)) {
        jaiDef.setTileCache(new ConcurrentTileCacheMultiMap());
    }
    // make sure we remember if GeoServer controls logging or not
    String strValue = GeoServerExtensions.getProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL, sce.getServletContext());
    relinquishLoggingControl = Boolean.valueOf(strValue);
    // subsystem
    if (System.getProperty("org.geotools.referencing.forceXY") == null) {
        System.setProperty("org.geotools.referencing.forceXY", "true");
    }
    if (Boolean.TRUE.equals(Hints.getSystemDefault(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER))) {
        Hints.putSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING, "http");
    }
    Hints.putSystemDefault(Hints.LENIENT_DATUM_SHIFT, true);
    // setup the referencing tolerance to make it more tolerant to tiny differences
    // between projections (increases the chance of matching a random prj file content
    // to an actual EPSG code
    String comparisonToleranceProperty = GeoServerExtensions.getProperty(COMPARISON_TOLERANCE_PROPERTY);
    double comparisonTolerance = DEFAULT_COMPARISON_TOLERANCE;
    if (comparisonToleranceProperty != null) {
        try {
            comparisonTolerance = Double.parseDouble(comparisonToleranceProperty);
        } catch (NumberFormatException nfe) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.warning("Unable to parse the specified COMPARISON_TOLERANCE " + "system property: " + comparisonToleranceProperty + " which should be a number. Using Default: " + DEFAULT_COMPARISON_TOLERANCE);
            }
        }
    }
    Hints.putSystemDefault(Hints.COMPARISON_TOLERANCE, comparisonTolerance);
    final Hints defHints = GeoTools.getDefaultHints();
    // Initialize GridCoverageFactory so that we don't make a lookup every time a factory is needed
    Hints.putSystemDefault(Hints.GRID_COVERAGE_FACTORY, CoverageFactoryFinder.getGridCoverageFactory(defHints));
    // don't allow the connection to the EPSG database to time out. This is a server app,
    // we can afford keeping the EPSG db always on
    System.setProperty("org.geotools.epsg.factory.timeout", "-1");
    // HACK: java.util.prefs are awful. See
    // http://www.allaboutbalance.com/disableprefs. When the site comes
    // back up we should implement their better way of fixing the problem.
    System.setProperty("java.util.prefs.syncInterval", "5000000");
    // Fix issue with tomcat and JreMemoryLeakPreventionListener causing issues with 
    // IIORegistry leading to imageio plugins not being properly initialized
    ImageIO.scanForPlugins();
    // in any case, the native png reader is worse than the pure java ones, so
    // let's disable it (the native png writer is on the other side faster)...
    ImageIOExt.allowNativeCodec("png", ImageReaderSpi.class, false);
    ImageIOExt.allowNativeCodec("png", ImageWriterSpi.class, true);
    // initialize GeoTools factories so that we don't make a SPI lookup every time a factory is needed
    Hints.putSystemDefault(Hints.FILTER_FACTORY, CommonFactoryFinder.getFilterFactory2(null));
    Hints.putSystemDefault(Hints.STYLE_FACTORY, CommonFactoryFinder.getStyleFactory(null));
    Hints.putSystemDefault(Hints.FEATURE_FACTORY, CommonFactoryFinder.getFeatureFactory(null));
    // initialize the default executor service
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(CoverageAccessInfoImpl.DEFAULT_CorePoolSize, CoverageAccessInfoImpl.DEFAULT_MaxPoolSize, CoverageAccessInfoImpl.DEFAULT_KeepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    Hints.putSystemDefault(Hints.EXECUTOR_SERVICE, executor);
}
Example 25
Project: jai-imageio-core-master  File: BMPImageWriter.java View source code
protected boolean canEncodeImage(int compression, ImageTypeSpecifier imgType) {
    ImageWriterSpi spi = this.getOriginatingProvider();
    if (!spi.canEncodeImage(imgType)) {
        return false;
    }
    int bpp = imgType.getColorModel().getPixelSize();
    if (compressionType == BI_RLE4 && bpp != 4) {
        // only 4bpp images can be encoded as BI_RLE4
        return false;
    }
    if (compressionType == BI_RLE8 && bpp != 8) {
        // only 8bpp images can be encoded as BI_RLE8
        return false;
    }
    if (bpp == 16) {
        /*
             * Technically we expect that we may be able to
             * encode only some of SinglePixelPackedSampleModel
             * images here.
             *
             * In addition we should take into account following:
             *
             * 1. BI_RGB case, according to the MSDN description:
             *
             *     The bitmap has a maximum of 2^16 colors. If the
             *     biCompression member of the BITMAPINFOHEADER is BI_RGB,
             *     the bmiColors member of BITMAPINFO is NULL. Each WORD
             *     in the bitmap array represents a single pixel. The
             *     relative intensities of red, green, and blue are
             *     represented with five bits for each color component.
             *
             * 2. BI_BITFIELDS case, according ot the MSDN description:
             *
             *     Windows 95/98/Me: When the biCompression member is
             *     BI_BITFIELDS, the system supports only the following
             *     16bpp color masks: A 5-5-5 16-bit image, where the blue
             *     mask is 0x001F, the green mask is 0x03E0, and the red mask
             *     is 0x7C00; and a 5-6-5 16-bit image, where the blue mask
             *     is 0x001F, the green mask is 0x07E0, and the red mask is
             *     0xF800.
             */
        boolean canUseRGB = false;
        boolean canUseBITFIELDS = false;
        SampleModel sm = imgType.getSampleModel();
        if (sm instanceof SinglePixelPackedSampleModel) {
            int[] sizes = ((SinglePixelPackedSampleModel) sm).getSampleSize();
            canUseRGB = true;
            canUseBITFIELDS = true;
            for (int i = 0; i < sizes.length; i++) {
                canUseRGB &= (sizes[i] == 5);
                canUseBITFIELDS &= ((sizes[i] == 5) || (i == 1 && sizes[i] == 6));
            }
        }
        return (((compressionType == BI_RGB) && canUseRGB) || ((compressionType == BI_BITFIELDS) && canUseBITFIELDS));
    }
    return true;
}
Example 26
Project: libbio-formats-java-master  File: BMPImageWriter.java View source code
protected boolean canEncodeImage(int compression, ImageTypeSpecifier imgType) {
    ImageWriterSpi spi = this.getOriginatingProvider();
    if (!spi.canEncodeImage(imgType)) {
        return false;
    }
    int bpp = imgType.getColorModel().getPixelSize();
    if (compressionType == BI_RLE4 && bpp != 4) {
        // only 4bpp images can be encoded as BI_RLE4
        return false;
    }
    if (compressionType == BI_RLE8 && bpp != 8) {
        // only 8bpp images can be encoded as BI_RLE8
        return false;
    }
    if (bpp == 16) {
        /*
             * Technically we expect that we may be able to
             * encode only some of SinglePixelPackedSampleModel
             * images here.
             *
             * In addition we should take into account following:
             *
             * 1. BI_RGB case, according to the MSDN description:
             *
             *     The bitmap has a maximum of 2^16 colors. If the
             *     biCompression member of the BITMAPINFOHEADER is BI_RGB,
             *     the bmiColors member of BITMAPINFO is NULL. Each WORD
             *     in the bitmap array represents a single pixel. The
             *     relative intensities of red, green, and blue are
             *     represented with five bits for each color component.
             *
             * 2. BI_BITFIELDS case, according ot the MSDN description:
             *
             *     Windows 95/98/Me: When the biCompression member is
             *     BI_BITFIELDS, the system supports only the following
             *     16bpp color masks: A 5-5-5 16-bit image, where the blue
             *     mask is 0x001F, the green mask is 0x03E0, and the red mask
             *     is 0x7C00; and a 5-6-5 16-bit image, where the blue mask
             *     is 0x001F, the green mask is 0x07E0, and the red mask is
             *     0xF800.
             */
        boolean canUseRGB = false;
        boolean canUseBITFIELDS = false;
        SampleModel sm = imgType.getSampleModel();
        if (sm instanceof SinglePixelPackedSampleModel) {
            int[] sizes = ((SinglePixelPackedSampleModel) sm).getSampleSize();
            canUseRGB = true;
            canUseBITFIELDS = true;
            for (int i = 0; i < sizes.length; i++) {
                canUseRGB &= (sizes[i] == 5);
                canUseBITFIELDS &= ((sizes[i] == 5) || (i == 1 && sizes[i] == 6));
            }
        }
        return (((compressionType == BI_RGB) && canUseRGB) || ((compressionType == BI_BITFIELDS) && canUseBITFIELDS));
    }
    return true;
}
Example 27
Project: bioformats-master  File: BMPImageWriter.java View source code
protected boolean canEncodeImage(int compression, ImageTypeSpecifier imgType) {
    ImageWriterSpi spi = this.getOriginatingProvider();
    if (!spi.canEncodeImage(imgType)) {
        return false;
    }
    int bpp = imgType.getColorModel().getPixelSize();
    if (compressionType == BI_RLE4 && bpp != 4) {
        // only 4bpp images can be encoded as BI_RLE4
        return false;
    }
    if (compressionType == BI_RLE8 && bpp != 8) {
        // only 8bpp images can be encoded as BI_RLE8
        return false;
    }
    if (bpp == 16) {
        /*
             * Technically we expect that we may be able to
             * encode only some of SinglePixelPackedSampleModel
             * images here.
             *
             * In addition we should take into account following:
             *
             * 1. BI_RGB case, according to the MSDN description:
             *
             *     The bitmap has a maximum of 2^16 colors. If the
             *     biCompression member of the BITMAPINFOHEADER is BI_RGB,
             *     the bmiColors member of BITMAPINFO is NULL. Each WORD
             *     in the bitmap array represents a single pixel. The
             *     relative intensities of red, green, and blue are
             *     represented with five bits for each color component.
             *
             * 2. BI_BITFIELDS case, according ot the MSDN description:
             *
             *     Windows 95/98/Me: When the biCompression member is
             *     BI_BITFIELDS, the system supports only the following
             *     16bpp color masks: A 5-5-5 16-bit image, where the blue
             *     mask is 0x001F, the green mask is 0x03E0, and the red mask
             *     is 0x7C00; and a 5-6-5 16-bit image, where the blue mask
             *     is 0x001F, the green mask is 0x07E0, and the red mask is
             *     0xF800.
             */
        boolean canUseRGB = false;
        boolean canUseBITFIELDS = false;
        SampleModel sm = imgType.getSampleModel();
        if (sm instanceof SinglePixelPackedSampleModel) {
            int[] sizes = ((SinglePixelPackedSampleModel) sm).getSampleSize();
            canUseRGB = true;
            canUseBITFIELDS = true;
            for (int i = 0; i < sizes.length; i++) {
                canUseRGB &= (sizes[i] == 5);
                canUseBITFIELDS &= ((sizes[i] == 5) || (i == 1 && sizes[i] == 6));
            }
        }
        return (((compressionType == BI_RGB) && canUseRGB) || ((compressionType == BI_BITFIELDS) && canUseBITFIELDS));
    }
    return true;
}
Example 28
Project: classlib6-master  File: DataTransferer.java View source code
protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Example 29
Project: folio100_frameworks_base-master  File: ImageWriter.java View source code
/**
     * Sets the specified Object to the output of this ImageWriter.
     * 
     * @param output
     *            the Object which represents destination, it can be
     *            ImageOutputStream or other objects.
     */
public void setOutput(Object output) {
    if (output != null) {
        ImageWriterSpi spi = getOriginatingProvider();
        if (null != spi) {
            Class[] outTypes = spi.getOutputTypes();
            boolean supported = false;
            for (Class<?> element : outTypes) {
                if (element.isInstance(output)) {
                    supported = true;
                    break;
                }
            }
            if (!supported) {
                throw new IllegalArgumentException("output " + output + " is not supported");
            }
        }
    }
    this.output = output;
}
Example 30
Project: JamVM-PH-master  File: ImageIO.java View source code
public boolean filter(Object provider) {
    if (provider instanceof ImageWriterSpi) {
        ImageWriterSpi spi = (ImageWriterSpi) provider;
        String[] formatNames = spi.getFormatNames();
        for (int i = formatNames.length - 1; i >= 0; --i) if (formatName.equals(formatNames[i]))
            return true;
    }
    return false;
}
Example 31
Project: open-mika-master  File: ImageWriter.java View source code
/**
     * Sets the specified Object to the output of this ImageWriter.
     * 
     * @param output
     *            the Object which represents destination, it can be
     *            ImageOutputStream or other objects.
     */
public void setOutput(Object output) {
    if (output != null) {
        ImageWriterSpi spi = getOriginatingProvider();
        if (null != spi) {
            Class[] outTypes = spi.getOutputTypes();
            boolean supported = false;
            for (Class<?> element : outTypes) {
                if (element.isInstance(output)) {
                    supported = true;
                    break;
                }
            }
            if (!supported) {
                throw new IllegalArgumentException("output " + output + " is not supported");
            }
        }
    }
    this.output = output;
}
Example 32
Project: snap-desktop-master  File: SnapApp.java View source code
private static void initImageIO() {
    // todo - actually this should be done in the activator of ceres-jai which does not exist yet
    Lookup.Result<ModuleInfo> moduleInfos = Lookup.getDefault().lookupResult(ModuleInfo.class);
    String ceresJaiCodeName = "org.esa.snap.ceres.jai";
    Optional<? extends ModuleInfo> info = moduleInfos.allInstances().stream().filter( moduleInfo -> ceresJaiCodeName.equals(moduleInfo.getCodeName())).findFirst();
    if (info.isPresent()) {
        ClassLoader classLoader = info.get().getClassLoader();
        IIORegistry iioRegistry = IIORegistry.getDefaultInstance();
        iioRegistry.registerServiceProviders(IIORegistry.lookupProviders(ImageReaderSpi.class, classLoader));
        iioRegistry.registerServiceProviders(IIORegistry.lookupProviders(ImageWriterSpi.class, classLoader));
    } else {
        LOG.warning(String.format("Module '%s' not found. Not able to load image-IO services.", ceresJaiCodeName));
    }
}
Example 33
Project: WS171-frameworks-base-master  File: ImageWriter.java View source code
/**
     * Sets the specified Object to the output of this ImageWriter.
     * 
     * @param output
     *            the Object which represents destination, it can be
     *            ImageOutputStream or other objects.
     */
public void setOutput(Object output) {
    if (output != null) {
        ImageWriterSpi spi = getOriginatingProvider();
        if (null != spi) {
            Class[] outTypes = spi.getOutputTypes();
            boolean supported = false;
            for (Class<?> element : outTypes) {
                if (element.isInstance(output)) {
                    supported = true;
                    break;
                }
            }
            if (!supported) {
                throw new IllegalArgumentException("output " + output + " is not supported");
            }
        }
    }
    this.output = output;
}
Example 34
Project: geotools-2.7.x-master  File: ImageWorker.java View source code
/**
     * Writes outs the image contained into this {@link ImageWorker} as a GIF
     * using the provided destination, compression and compression rate.
     * <p>
     * It is worth to point out that the only compressions algorithm availaible
     * with the jdk {@link GIFImageWriter} is "LZW" while the compression rates
     * have to be confined between 0 and 1. AN acceptable values is usally 0.75f.
     * <p>
     * The destination object can be anything providing that we have an
     * {@link ImageOutputStreamSpi} that recognizes it.
     *
     * @param destination
     *            where to write the internal {@link #image} as a gif.
     * @param compression
     *            The name of compression algorithm.
     * @param compressionRate
     *            percentage of compression, as a number between 0 and 1.
     * @return this {@link ImageWorker}.
     * @throws IOException
     *             In case an error occurs during the search for an
     *             {@link ImageOutputStream} or during the eoncding process.
     *
     * @see #forceIndexColorModelForGIF(boolean)
     */
public final ImageWorker writeGIF(final Object destination, final String compression, final float compressionRate) throws IOException {
    forceIndexColorModelForGIF(true);
    final IIORegistry registry = IIORegistry.getDefaultInstance();
    Iterator<ImageWriterSpi> it = registry.getServiceProviders(ImageWriterSpi.class, true);
    ImageWriterSpi spi = null;
    while (it.hasNext()) {
        final ImageWriterSpi candidate = it.next();
        if (containsFormatName(candidate.getFormatNames(), "gif")) {
            if (spi == null) {
                spi = candidate;
            } else {
                final String name = candidate.getClass().getName();
                if (name.equals("com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi")) {
                    spi = candidate;
                    break;
                }
            }
        }
    }
    if (spi == null) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final ImageOutputStream stream = ImageIOExt.createImageOutputStream(image, destination);
    if (stream == null)
        throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1, "stream"));
    final ImageWriter writer = spi.createWriterInstance();
    final ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setCompressionQuality(compressionRate);
    try {
        writer.setOutput(stream);
        writer.write(null, new IIOImage(image, null, null), param);
    } finally {
        try {
            stream.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
        try {
            writer.dispose();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
    }
    return this;
}
Example 35
Project: geotools-tike-master  File: ImageWorker.java View source code
/**
     * Writes outs the image contained into this {@link ImageWorker} as a GIF
     * using the provided destination, compression and compression rate.
     * <p>
     * It is worth to point out that the only compressions algorithm availaible
     * with the jdk {@link GIFImageWriter} is "LZW" while the compression rates
     * have to be confined between 0 and 1. AN acceptable values is usally 0.75f.
     * <p>
     * The destination object can be anything providing that we have an
     * {@link ImageOutputStreamSpi} that recognizes it.
     *
     * @param destination
     *            where to write the internal {@link #image} as a gif.
     * @param compression
     *            The name of compression algorithm.
     * @param compressionRate
     *            percentage of compression, as a number between 0 and 1.
     * @return this {@link ImageWorker}.
     * @throws IOException
     *             In case an error occurs during the search for an
     *             {@link ImageOutputStream} or during the eoncding process.
     *
     * @see #forceIndexColorModelForGIF(boolean)
     */
public final ImageWorker writeGIF(final Object destination, final String compression, final float compressionRate) throws IOException {
    forceIndexColorModelForGIF(true);
    final IIORegistry registry = IIORegistry.getDefaultInstance();
    Iterator<ImageWriterSpi> it = registry.getServiceProviders(ImageWriterSpi.class, true);
    ImageWriterSpi spi = null;
    while (it.hasNext()) {
        final ImageWriterSpi candidate = it.next();
        if (containsFormatName(candidate.getFormatNames(), "gif")) {
            if (spi == null) {
                spi = candidate;
            } else {
                final String name = candidate.getClass().getName();
                if (name.equals("com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi")) {
                    spi = candidate;
                    break;
                }
            }
        }
    }
    if (spi == null) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final ImageOutputStream stream = ImageIO.createImageOutputStream(destination);
    if (stream == null)
        throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1, "stream"));
    final ImageWriter writer = spi.createWriterInstance();
    final ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setCompressionQuality(compressionRate);
    try {
        writer.setOutput(stream);
        writer.write(null, new IIOImage(image, null, null), param);
    } finally {
        try {
            stream.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
        try {
            writer.dispose();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
    }
    return this;
}
Example 36
Project: junrar-android-master  File: BMPImageWriter.java View source code
protected boolean canEncodeImage(int compression, ImageTypeSpecifier imgType) {
    ImageWriterSpi spi = this.getOriginatingProvider();
    if (!spi.canEncodeImage(imgType)) {
        return false;
    }
    int biType = imgType.getBufferedImageType();
    int bpp = imgType.getColorModel().getPixelSize();
    if (compressionType == BI_RLE4 && bpp != 4) {
        // only 4bpp images can be encoded as BI_RLE4
        return false;
    }
    if (compressionType == BI_RLE8 && bpp != 8) {
        // only 8bpp images can be encoded as BI_RLE8
        return false;
    }
    if (bpp == 16) {
        /*
             * Technically we expect that we may be able to
             * encode only some of SinglePixelPackedSampleModel
             * images here.
             *
             * In addition we should take into account following:
             *
             * 1. BI_RGB case, according to the MSDN description:
             *
             *     The bitmap has a maximum of 2^16 colors. If the
             *     biCompression member of the BITMAPINFOHEADER is BI_RGB,
             *     the bmiColors member of BITMAPINFO is NULL. Each WORD
             *     in the bitmap array represents a single pixel. The
             *     relative intensities of red, green, and blue are
             *     represented with five bits for each color component.
             *
             * 2. BI_BITFIELDS case, according ot the MSDN description:
             *
             *     Windows 95/98/Me: When the biCompression member is
             *     BI_BITFIELDS, the system supports only the following
             *     16bpp color masks: A 5-5-5 16-bit image, where the blue
             *     mask is 0x001F, the green mask is 0x03E0, and the red mask
             *     is 0x7C00; and a 5-6-5 16-bit image, where the blue mask
             *     is 0x001F, the green mask is 0x07E0, and the red mask is
             *     0xF800.
             */
        boolean canUseRGB = false;
        boolean canUseBITFIELDS = false;
        SampleModel sm = imgType.getSampleModel();
        if (sm instanceof SinglePixelPackedSampleModel) {
            int[] sizes = ((SinglePixelPackedSampleModel) sm).getSampleSize();
            canUseRGB = true;
            canUseBITFIELDS = true;
            for (int i = 0; i < sizes.length; i++) {
                canUseRGB &= (sizes[i] == 5);
                canUseBITFIELDS &= ((sizes[i] == 5) || (i == 1 && sizes[i] == 6));
            }
        }
        return (((compressionType == BI_RGB) && canUseRGB) || ((compressionType == BI_BITFIELDS) && canUseBITFIELDS));
    }
    return true;
}
Example 37
Project: poreid-master  File: ImageUtil.java View source code
// Method to return JDK core ImageReaderSPI/ImageWriterSPI for a 
// given formatName.
public static List getJDKImageReaderWriterSPI(ServiceRegistry registry, String formatName, boolean isReader) {
    IIORegistry iioRegistry = (IIORegistry) registry;
    Class spiClass;
    String descPart;
    if (isReader) {
        spiClass = ImageReaderSpi.class;
        descPart = " image reader";
    } else {
        spiClass = ImageWriterSpi.class;
        descPart = " image writer";
    }
    Iterator iter = iioRegistry.getServiceProviders(spiClass, // useOrdering
    true);
    String formatNames[];
    ImageReaderWriterSpi provider;
    String desc = "standard " + formatName + descPart;
    String jiioPath = "com.sun.media.imageioimpl";
    Locale locale = Locale.getDefault();
    ArrayList list = new ArrayList();
    while (iter.hasNext()) {
        provider = (ImageReaderWriterSpi) iter.next();
        // Look for JDK core ImageWriterSpi's
        if (provider.getVendorName().startsWith("Sun Microsystems") && desc.equalsIgnoreCase(provider.getDescription(locale)) && // not JAI Image I/O plugins
        !provider.getPluginClassName().startsWith(jiioPath)) {
            // Get the formatNames supported by this Spi
            formatNames = provider.getFormatNames();
            for (int i = 0; i < formatNames.length; i++) {
                if (formatNames[i].equalsIgnoreCase(formatName)) {
                    // Must be a JDK provided ImageReader/ImageWriter
                    list.add(provider);
                    break;
                }
            }
        }
    }
    return list;
}
Example 38
Project: UniversalMediaServer-master  File: PMS.java View source code
/**
	 * Initialization procedure for UMS.
	 *
	 * @return <code>true</code> if the server has been initialized correctly.
	 *         <code>false</code> if initialization was aborted.
	 * @throws Exception
	 */
private boolean init() throws Exception {
    // Show the language selection dialog before displayBanner();
    if (!isHeadless() && (configuration.getLanguageRawString() == null || !Languages.isValid(configuration.getLanguageRawString()))) {
        LanguageSelection languageDialog = new LanguageSelection(null, PMS.getLocale(), false);
        if (languageDialog != null) {
            languageDialog.show();
            if (languageDialog.isAborted()) {
                return false;
            }
        }
    }
    // Call this as early as possible
    displayBanner();
    // Initialize database
    Tables.checkTables();
    // Log registered ImageIO plugins
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("");
        LOGGER.trace("Registered ImageIO reader classes:");
        Iterator<ImageReaderSpi> readerIterator = IIORegistry.getDefaultInstance().getServiceProviders(ImageReaderSpi.class, true);
        while (readerIterator.hasNext()) {
            ImageReaderSpi reader = readerIterator.next();
            LOGGER.trace("Reader class: {}", reader.getPluginClassName());
        }
        LOGGER.trace("");
        LOGGER.trace("Registered ImageIO writer classes:");
        Iterator<ImageWriterSpi> writerIterator = IIORegistry.getDefaultInstance().getServiceProviders(ImageWriterSpi.class, true);
        while (writerIterator.hasNext()) {
            ImageWriterSpi writer = writerIterator.next();
            LOGGER.trace("Writer class: {}", writer.getPluginClassName());
        }
        LOGGER.trace("");
    }
    // Wizard
    if (configuration.isRunWizard() && !isHeadless()) {
        // Ask the user if they want to run the wizard
        int whetherToRunWizard = JOptionPane.showConfirmDialog(null, Messages.getString("Wizard.1"), Messages.getString("Dialog.Question"), JOptionPane.YES_NO_OPTION);
        if (whetherToRunWizard == JOptionPane.YES_OPTION) {
            // The user has chosen to run the wizard
            // Total number of questions
            int numberOfQuestions = 3;
            // The current question number
            int currentQuestionNumber = 1;
            // Ask if they want UMS to start minimized
            int whetherToStartMinimized = JOptionPane.showConfirmDialog(null, Messages.getString("Wizard.3"), Messages.getString("Wizard.2") + " " + (currentQuestionNumber++) + " " + Messages.getString("Wizard.4") + " " + numberOfQuestions, JOptionPane.YES_NO_OPTION);
            if (whetherToStartMinimized == JOptionPane.YES_OPTION) {
                configuration.setMinimized(true);
                save();
            } else if (whetherToStartMinimized == JOptionPane.NO_OPTION) {
                configuration.setMinimized(false);
                save();
            }
            // Ask if their network is wired, etc.
            Object[] options = { Messages.getString("Wizard.8"), Messages.getString("Wizard.9"), Messages.getString("Wizard.10") };
            int networkType = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.7"), Messages.getString("Wizard.2") + " " + (currentQuestionNumber++) + " " + Messages.getString("Wizard.4") + " " + numberOfQuestions, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            switch(networkType) {
                case JOptionPane.YES_OPTION:
                    // Wired (Gigabit)
                    configuration.setMaximumBitrate("0");
                    configuration.setMPEG2MainSettings("Automatic (Wired)");
                    configuration.setx264ConstantRateFactor("Automatic (Wired)");
                    save();
                    break;
                case JOptionPane.NO_OPTION:
                    // Wired (100 Megabit)
                    configuration.setMaximumBitrate("90");
                    configuration.setMPEG2MainSettings("Automatic (Wired)");
                    configuration.setx264ConstantRateFactor("Automatic (Wired)");
                    save();
                    break;
                case JOptionPane.CANCEL_OPTION:
                    // Wireless
                    configuration.setMaximumBitrate("30");
                    configuration.setMPEG2MainSettings("Automatic (Wireless)");
                    configuration.setx264ConstantRateFactor("Automatic (Wireless)");
                    save();
                    break;
                default:
                    break;
            }
            // Ask if they want to hide advanced options
            int whetherToHideAdvancedOptions = JOptionPane.showConfirmDialog(null, Messages.getString("Wizard.11"), Messages.getString("Wizard.2") + " " + (currentQuestionNumber++) + " " + Messages.getString("Wizard.4") + " " + numberOfQuestions, JOptionPane.YES_NO_OPTION);
            if (whetherToHideAdvancedOptions == JOptionPane.YES_OPTION) {
                configuration.setHideAdvancedOptions(true);
                save();
            } else if (whetherToHideAdvancedOptions == JOptionPane.NO_OPTION) {
                configuration.setHideAdvancedOptions(false);
                save();
            }
            JOptionPane.showMessageDialog(null, Messages.getString("Wizard.13"), Messages.getString("Wizard.12"), JOptionPane.INFORMATION_MESSAGE);
            configuration.setRunWizard(false);
            save();
        } else if (whetherToRunWizard == JOptionPane.NO_OPTION) {
            // The user has chosen to not run the wizard
            // Do not ask them again
            configuration.setRunWizard(false);
            save();
        }
    }
    // Splash
    Splash splash = null;
    if (!isHeadless()) {
        splash = new Splash(configuration);
    }
    // The public VERSION field is deprecated.
    // This is a temporary fix for backwards compatibility
    VERSION = getVersion();
    fileWatcher = new FileWatcher();
    globalRepo = new GlobalIdRepo();
    AutoUpdater autoUpdater = null;
    if (Build.isUpdatable()) {
        String serverURL = Build.getUpdateServerURL();
        autoUpdater = new AutoUpdater(serverURL, getVersion());
    }
    registry = createSystemUtils();
    if (!isHeadless()) {
        frame = new LooksFrame(autoUpdater, configuration);
    } else {
        LOGGER.info("Graphics environment not available or headless mode is forced");
        LOGGER.info("Switching to console mode");
        frame = new DummyFrame();
    }
    if (splash != null) {
        splash.dispose();
    }
    /*
		 * we're here:
		 *
		 *     main() -> createInstance() -> init()
		 *
		 * which means we haven't created the instance returned by get()
		 * yet, so the frame appender can't access the frame in the
		 * standard way i.e. PMS.get().getFrame(). we solve it by
		 * inverting control ("don't call us; we'll call you") i.e.
		 * we notify the appender when the frame is ready rather than
		 * e.g. making getFrame() static and requiring the frame
		 * appender to poll it.
		 *
		 * XXX an event bus (e.g. MBassador or Guava EventBus
		 * (if they fix the memory-leak issue)) notification
		 * would be cleaner and could support other lifecycle
		 * notifications (see above).
		 */
    FrameAppender.setFrame(frame);
    configuration.addConfigurationListener(new ConfigurationListener() {

        @Override
        public void configurationChanged(ConfigurationEvent event) {
            if ((!event.isBeforeUpdate()) && PmsConfiguration.NEED_RELOAD_FLAGS.contains(event.getPropertyName())) {
                frame.setReloadable(true);
            }
        }
    });
    // Web stuff
    if (configuration.useWebInterface()) {
        web = new RemoteWeb(configuration.getWebPort());
    }
    // init Credentials
    credMgr = new CredMgr(configuration.getCredFile());
    // init dbs
    keysDb = new UmsKeysDb();
    infoDb = new InfoDb();
    codes = new CodeDb();
    masterCode = null;
    RendererConfiguration.loadRendererConfigurations(configuration);
    // Now that renderer confs are all loaded, we can start searching for renderers
    UPNPHelper.getInstance().init();
    // launch ChromecastMgr
    jmDNS = null;
    launchJmDNSRenderers();
    OutputParams outputParams = new OutputParams(configuration);
    // Prevent unwanted GUI buffer artifacts (and runaway timers)
    outputParams.hidebuffer = true;
    // Make sure buffer is destroyed
    outputParams.cleanup = true;
    // Initialize MPlayer and FFmpeg to let them generate fontconfig cache/s
    if (!configuration.isDisableSubtitles()) {
        LOGGER.info("Checking the fontconfig cache in the background, this can take two minutes or so.");
        ProcessWrapperImpl mplayer = new ProcessWrapperImpl(new String[] { configuration.getMplayerPath(), "dummy" }, outputParams);
        mplayer.runInNewThread();
        /**
			 * Note: Different versions of fontconfig and bitness require
			 * different caches, which is why here we ask FFmpeg (64-bit
			 * if possible) to create a cache.
			 * This should result in all of the necessary caches being built.
			 */
        if (!Platform.isWindows() || Platform.is64Bit()) {
            ProcessWrapperImpl ffmpeg = new ProcessWrapperImpl(new String[] { configuration.getFfmpegPath(), "-y", "-f", "lavfi", "-i", "nullsrc=s=720x480:d=1:r=1", "-vf", "ass=DummyInput.ass", "-target", "ntsc-dvd", "-" }, outputParams);
            ffmpeg.runInNewThread();
        }
    }
    frame.setStatusCode(0, Messages.getString("PMS.130"), "icon-status-connecting.png");
    // Check the existence of VSFilter / DirectVobSub
    if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
        LOGGER.debug("AviSynth plugins directory: " + registry.getAvsPluginsDir().getAbsolutePath());
        File vsFilterDLL = new File(registry.getAvsPluginsDir(), "VSFilter.dll");
        if (vsFilterDLL.exists()) {
            LOGGER.debug("VSFilter / DirectVobSub was found in the AviSynth plugins directory.");
        } else {
            File vsFilterDLL2 = new File(registry.getKLiteFiltersDir(), "vsfilter.dll");
            if (vsFilterDLL2.exists()) {
                LOGGER.debug("VSFilter / DirectVobSub was found in the K-Lite Codec Pack filters directory.");
            } else {
                LOGGER.info("VSFilter / DirectVobSub was not found. This can cause problems when trying to play subtitled videos with AviSynth.");
            }
        }
    }
    // Check if VLC is found
    String vlcVersion = registry.getVlcVersion();
    String vlcPath = registry.getVlcPath();
    if (vlcVersion != null && vlcPath != null) {
        LOGGER.info("Found VLC version " + vlcVersion + " at: " + vlcPath);
        Version vlc = new Version(vlcVersion);
        Version requiredVersion = new Version("2.0.2");
        if (vlc.compareTo(requiredVersion) <= 0) {
            LOGGER.error("Only VLC versions 2.0.2 and above are supported");
        }
    }
    // Check if Kerio is installed
    if (registry.isKerioFirewall()) {
        LOGGER.info("Detected Kerio firewall");
    }
    // Force use of specific DVR-MS muxer when it's installed in the right place
    File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe");
    if (dvrsMsffmpegmuxer.exists()) {
        configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
    }
    // Disable jaudiotagger logging
    LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes(StandardCharsets.US_ASCII)));
    // Wrap System.err
    System.setErr(new PrintStream(new SystemErrWrapper(), true, StandardCharsets.UTF_8.name()));
    server = new HTTPServer(configuration.getServerPort());
    /*
		 * XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
		 * can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
		 *
		 * XXX: if a plugin requires initialization/notification even earlier than
		 * this, then a new external listener implementing a new callback should be added
		 * e.g. StartupListener.registeredExtensions()
		 */
    try {
        ExternalFactory.lookup();
    } catch (Exception e) {
        LOGGER.error("Error loading plugins", e);
    }
    // Initialize a player factory to register all players
    PlayerFactory.initialize();
    // Instantiate listeners that require registered players.
    ExternalFactory.instantiateLateListeners();
    // a static block in Player doesn't work (i.e. is called too late).
    // this must always be called *after* the plugins have loaded.
    // here's as good a place as any
    Player.initializeFinalizeTranscoderArgsListeners();
    // Any plugin-defined players are now registered, create the gui view.
    frame.addEngines();
    // file AFTER plugins are started
    if (!isHeadless()) {
        // but only if we got a GUI of course
        ((LooksFrame) frame).getPt().init();
    }
    boolean binding = false;
    try {
        binding = server.start();
    } catch (BindException b) {
        LOGGER.error("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: " + b.getMessage());
        LOGGER.info("Maybe another process is running or the hostname is wrong.");
    }
    new Thread("Connection Checker") {

        @Override
        public void run() {
            try {
                Thread.sleep(7000);
            } catch (InterruptedException e) {
            }
            if (foundRenderers.isEmpty()) {
                frame.setStatusCode(0, Messages.getString("PMS.0"), "icon-status-notconnected.png");
            } else {
                frame.setStatusCode(0, Messages.getString("PMS.18"), "icon-status-connected.png");
            }
        }
    }.start();
    if (!binding) {
        return false;
    }
    if (web != null && web.getServer() != null) {
        LOGGER.info("WEB interface is available at: " + web.getUrl());
    }
    // initialize the cache
    if (configuration.getUseCache()) {
        mediaLibrary = new MediaLibrary();
        LOGGER.info("A tiny cache admin interface is available at: http://" + server.getHost() + ":" + server.getPort() + "/console/home");
    }
    // XXX: this must be called:
    //     a) *after* loading plugins i.e. plugins register root folders then RootFolder.discoverChildren adds them
    //     b) *after* mediaLibrary is initialized, if enabled (above)
    getRootFolder(RendererConfiguration.getDefaultConf());
    frame.serverReady();
    ready = true;
    // UPNPHelper.sendByeBye();
    Runtime.getRuntime().addShutdownHook(new Thread("UMS Shutdown") {

        @Override
        public void run() {
            try {
                for (ExternalListener l : ExternalFactory.getExternalListeners()) {
                    l.shutdown();
                }
                UPNPHelper.shutDownListener();
                UPNPHelper.sendByeBye();
                LOGGER.debug("Forcing shutdown of all active processes");
                for (Process p : currentProcesses) {
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ise) {
                        LOGGER.trace("Forcing shutdown of process: " + p);
                        ProcessUtil.destroy(p);
                    }
                }
                get().getServer().stop();
                Thread.sleep(500);
            } catch (InterruptedException e) {
                LOGGER.debug("Caught exception", e);
            }
            LOGGER.info("Stopping " + PropertiesUtil.getProjectProperties().get("project.name") + " " + getVersion());
            /**
				 * Stopping logging gracefully (flushing logs)
				 * No logging is available after this point
				 */
            ILoggerFactory iLoggerContext = LoggerFactory.getILoggerFactory();
            if (iLoggerContext instanceof LoggerContext) {
                ((LoggerContext) iLoggerContext).stop();
            } else {
                LOGGER.error("Unable to shut down logging gracefully");
            }
        }
    });
    configuration.setAutoSave();
    UPNPHelper.sendByeBye();
    LOGGER.trace("Waiting 250 milliseconds...");
    Thread.sleep(250);
    UPNPHelper.sendAlive();
    LOGGER.trace("Waiting 250 milliseconds...");
    Thread.sleep(250);
    UPNPHelper.listen();
    return true;
}
Example 39
Project: geotools-master  File: ImageWorker.java View source code
/**
     * Writes outs the image contained into this {@link ImageWorker} as a PNG using the provided destination, compression and compression rate.
     * <p>
     * The destination object can be anything providing that we have an {@link ImageOutputStreamSpi} that recognizes it.
     * 
     * @param destination where to write the internal {@link #image} as a PNG.
     * @param compression algorithm.
     * @param compressionRate percentage of compression.
     * @param nativeAcc should we use native acceleration.
     * @param paletted should we write the png as 8 bits?
     * @return this {@link ImageWorker}.
     * @throws IOException In case an error occurs during the search for an {@link ImageOutputStream} or during the eoncding process.
     * 
     * @todo Current code doesn't check if the writer already accepts the provided destination. It wraps it in a {@link ImageOutputStream}
     *       inconditionnaly.
     */
public final void writePNG(final Object destination, final String compression, final float compressionRate, final boolean nativeAcc, final boolean paletted) throws IOException {
    // Reformatting this image for PNG.
    final boolean hasPalette = image.getColorModel() instanceof IndexColorModel;
    final boolean hasColorModel = hasPalette ? false : image.getColorModel() instanceof ComponentColorModel;
    if (paletted && !hasPalette) {
        // we have to reduce colors
        forceIndexColorModelForGIF(true);
    } else {
        if (!hasColorModel && !hasPalette) {
            if (LOGGER.isLoggable(Level.FINER)) {
                LOGGER.fine("Forcing input image to be compatible with PNG: No palette, no component color model");
            }
            // png supports gray, rgb, rgba and paletted 8 bit, but not, for example, double and float values, or 16 bits palettes
            forceComponentColorModel();
        }
    }
    // PNG does not support all kinds of index color models
    if (hasPalette) {
        IndexColorModel icm = (IndexColorModel) image.getColorModel();
        // PNG supports palettes with up to 256 colors, beyond that we have to expand to RGB
        if (icm.getMapSize() > 256) {
            if (LOGGER.isLoggable(Level.FINER)) {
                LOGGER.fine("Forcing input image to be compatible with PNG: Palette with > 256 color is not supported.");
            }
            rescaleToBytes();
            if (paletted) {
                forceIndexColorModelForGIF(true);
            }
        }
    }
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Encoded input image for png writer");
    }
    // Getting a writer.
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Getting a writer");
    }
    ImageWriter writer = null;
    ImageWriterSpi originatingProvider = null;
    // ImageIO
    if (nativeAcc) {
        if (CLIB_PNG_IMAGE_WRITER_SPI != null) {
            // let me check if the native writer can encode this image
            if (CLIB_PNG_IMAGE_WRITER_SPI.canEncodeImage(new ImageTypeSpecifier(image))) {
                writer = CLIB_PNG_IMAGE_WRITER_SPI.createWriterInstance();
                originatingProvider = CLIB_PNG_IMAGE_WRITER_SPI;
            } else {
                LOGGER.fine("The ImageIO PNG native encode cannot encode this image!");
                writer = null;
                originatingProvider = null;
            }
        } else {
            LOGGER.fine("Unable to use Native ImageIO PNG writer.");
        }
    }
    // move on with the writer quest
    if (!nativeAcc || writer == null) {
        final Iterator<ImageWriter> it = ImageIO.getImageWriters(new ImageTypeSpecifier(image), "PNG");
        if (!it.hasNext()) {
            throw new IllegalStateException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
        }
        while (it.hasNext()) {
            writer = it.next();
            originatingProvider = writer.getOriginatingProvider();
            // check that this is not the native one
            if (CLIB_PNG_IMAGE_WRITER_SPI != null && originatingProvider.getClass().equals(CLIB_PNG_IMAGE_WRITER_SPI.getClass())) {
                if (it.hasNext()) {
                    writer = it.next();
                    originatingProvider = writer.getOriginatingProvider();
                } else {
                    LOGGER.fine("Unable to use PNG writer different than ImageIO CLib one");
                }
            }
            // let me check if the native writer can encode this image (paranoiac checks this was already performed by the ImageIO search
            if (originatingProvider.canEncodeImage(new ImageTypeSpecifier(image))) {
                // leave loop
                break;
            }
            // clean
            writer = null;
            originatingProvider = null;
        }
    }
    // ok, last resort use the JDK one and reformat the image
    if (writer == null) {
        List providers = com.sun.media.imageioimpl.common.ImageUtil.getJDKImageReaderWriterSPI(IIORegistry.getDefaultInstance(), "PNG", false);
        if (providers == null || providers.isEmpty()) {
            throw new IllegalStateException("Unable to find JDK Png encoder!");
        }
        originatingProvider = (ImageWriterSpi) providers.get(0);
        writer = originatingProvider.createWriterInstance();
        // kk, last resort reformat the image
        forceComponentColorModel(true, true);
        rescaleToBytes();
        if (!originatingProvider.canEncodeImage(image)) {
            throw new IllegalArgumentException("Unable to find a valid PNG Encoder! And believe me, we tried hard!");
        }
    }
    LOGGER.fine("Using ImageIO Writer with SPI: " + originatingProvider.getClass().getCanonicalName());
    // Getting a stream.
    LOGGER.fine("Setting write parameters for this writer");
    ImageWriteParam iwp = null;
    final ImageOutputStream memOutStream = ImageIOExt.createImageOutputStream(image, destination);
    if (memOutStream == null) {
        throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1, "stream"));
    }
    if (CLIB_PNG_IMAGE_WRITER_SPI != null && originatingProvider.getClass().equals(CLIB_PNG_IMAGE_WRITER_SPI.getClass())) {
        // Compressing with native.
        LOGGER.fine("Writer is native");
        iwp = writer.getDefaultWriteParam();
        // Define compression mode
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        // best compression
        iwp.setCompressionType(compression);
        // we can control quality here
        iwp.setCompressionQuality(compressionRate);
        // destination image type
        iwp.setDestinationType(new ImageTypeSpecifier(image.getColorModel(), image.getSampleModel()));
    } else {
        // Compressing with pure Java.
        LOGGER.fine("Writer is NOT native");
        // Instantiating PNGImageWriteParam
        iwp = new PNGImageWriteParam();
        // Define compression mode
        iwp.setCompressionMode(ImageWriteParam.MODE_DEFAULT);
    }
    LOGGER.fine("About to write png image");
    try {
        writer.setOutput(memOutStream);
        writer.write(null, new IIOImage(image, null, null), iwp);
    } finally {
        try {
            writer.dispose();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
        try {
            memOutStream.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
    }
}
Example 40
Project: geotools-old-master  File: ImageWorker.java View source code
/**
     * Writes outs the image contained into this {@link ImageWorker} as a GIF
     * using the provided destination, compression and compression rate.
     * <p>
     * It is worth to point out that the only compressions algorithm availaible
     * with the jdk {@link GIFImageWriter} is "LZW" while the compression rates
     * have to be confined between 0 and 1. AN acceptable values is usally 0.75f.
     * <p>
     * The destination object can be anything providing that we have an
     * {@link ImageOutputStreamSpi} that recognizes it.
     *
     * @param destination
     *            where to write the internal {@link #image} as a gif.
     * @param compression
     *            The name of compression algorithm.
     * @param compressionRate
     *            percentage of compression, as a number between 0 and 1.
     * @return this {@link ImageWorker}.
     * @throws IOException
     *             In case an error occurs during the search for an
     *             {@link ImageOutputStream} or during the eoncding process.
     *
     * @see #forceIndexColorModelForGIF(boolean)
     */
public final ImageWorker writeGIF(final Object destination, final String compression, final float compressionRate) throws IOException {
    forceIndexColorModelForGIF(true);
    final IIORegistry registry = IIORegistry.getDefaultInstance();
    Iterator<ImageWriterSpi> it = registry.getServiceProviders(ImageWriterSpi.class, true);
    ImageWriterSpi spi = null;
    while (it.hasNext()) {
        final ImageWriterSpi candidate = it.next();
        if (containsFormatName(candidate.getFormatNames(), "gif")) {
            if (spi == null) {
                spi = candidate;
            } else {
                final String name = candidate.getClass().getName();
                if (name.equals("com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi")) {
                    spi = candidate;
                    break;
                }
            }
        }
    }
    if (spi == null) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final ImageOutputStream stream = ImageIOExt.createImageOutputStream(image, destination);
    if (stream == null)
        throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1, "stream"));
    final ImageWriter writer = spi.createWriterInstance();
    final ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setCompressionQuality(compressionRate);
    try {
        writer.setOutput(stream);
        writer.write(null, new IIOImage(image, null, null), param);
    } finally {
        try {
            stream.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
        try {
            writer.dispose();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
    }
    return this;
}
Example 41
Project: geotools_trunk-master  File: ImageWorker.java View source code
/**
     * Writes outs the image contained into this {@link ImageWorker} as a GIF
     * using the provided destination, compression and compression rate.
     * <p>
     * It is worth to point out that the only compressions algorithm availaible
     * with the jdk {@link GIFImageWriter} is "LZW" while the compression rates
     * have to be confined between 0 and 1. AN acceptable values is usally 0.75f.
     * <p>
     * The destination object can be anything providing that we have an
     * {@link ImageOutputStreamSpi} that recognizes it.
     *
     * @param destination
     *            where to write the internal {@link #image} as a gif.
     * @param compression
     *            The name of compression algorithm.
     * @param compressionRate
     *            percentage of compression, as a number between 0 and 1.
     * @return this {@link ImageWorker}.
     * @throws IOException
     *             In case an error occurs during the search for an
     *             {@link ImageOutputStream} or during the eoncding process.
     *
     * @see #forceIndexColorModelForGIF(boolean)
     */
public final ImageWorker writeGIF(final Object destination, final String compression, final float compressionRate) throws IOException {
    forceIndexColorModelForGIF(true);
    final IIORegistry registry = IIORegistry.getDefaultInstance();
    Iterator<ImageWriterSpi> it = registry.getServiceProviders(ImageWriterSpi.class, true);
    ImageWriterSpi spi = null;
    while (it.hasNext()) {
        final ImageWriterSpi candidate = it.next();
        if (containsFormatName(candidate.getFormatNames(), "gif")) {
            if (spi == null) {
                spi = candidate;
            } else {
                final String name = candidate.getClass().getName();
                if (name.equals("com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi")) {
                    spi = candidate;
                    break;
                }
            }
        }
    }
    if (spi == null) {
        throw new IIOException(Errors.format(ErrorKeys.NO_IMAGE_WRITER));
    }
    final ImageOutputStream stream = ImageIOExt.createImageOutputStream(image, destination);
    if (stream == null)
        throw new IIOException(Errors.format(ErrorKeys.NULL_ARGUMENT_$1, "stream"));
    final ImageWriter writer = spi.createWriterInstance();
    final ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setCompressionQuality(compressionRate);
    try {
        writer.setOutput(stream);
        writer.write(null, new IIOImage(image, null, null), param);
    } finally {
        try {
            stream.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
        try {
            writer.dispose();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
    }
    return this;
}