Example usage for java.awt.image IndexColorModel getReds

List of usage examples for java.awt.image IndexColorModel getReds

Introduction

In this page you can find the example usage for java.awt.image IndexColorModel getReds.

Prototype

public final void getReds(byte[] r) 

Source Link

Document

Copies the array of red color components into the specified array.

Usage

From source file:at.gv.egiz.pdfas.common.utils.ImageUtils.java

public static BufferedImage makeTransparent(BufferedImage image, int x, int y) {
    ColorModel cm = image.getColorModel();
    if (!(cm instanceof IndexColorModel))
        return image; // sorry...
    IndexColorModel icm = (IndexColorModel) cm;
    WritableRaster raster = image.getRaster();
    int pixel = raster.getSample(x, y, 0); // pixel is offset in ICM's
    // palette/*from  w  w w  .  j ava 2s  . c  om*/
    int size = icm.getMapSize();
    byte[] reds = new byte[size];
    byte[] greens = new byte[size];
    byte[] blues = new byte[size];
    icm.getReds(reds);
    icm.getGreens(greens);
    icm.getBlues(blues);
    IndexColorModel icm2 = new IndexColorModel(8, size, reds, greens, blues, pixel);
    return new BufferedImage(icm2, raster, image.isAlphaPremultiplied(), null);
}

From source file:net.d53dev.dslfy.web.service.GifService.java

public BufferedImage convertRGBAToGIF(BufferedImage src, int transColor) {
    BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
    Graphics g = dst.getGraphics();
    g.setColor(new Color(transColor));
    g.fillRect(0, 0, dst.getWidth(), dst.getHeight());
    {//from   www . ja v  a2  s . c o m
        IndexColorModel indexedModel = (IndexColorModel) dst.getColorModel();
        WritableRaster raster = dst.getRaster();
        int sample = raster.getSample(0, 0, 0);
        int size = indexedModel.getMapSize();
        byte[] rr = new byte[size];
        byte[] gg = new byte[size];
        byte[] bb = new byte[size];
        indexedModel.getReds(rr);
        indexedModel.getGreens(gg);
        indexedModel.getBlues(bb);
        IndexColorModel newModel = new IndexColorModel(8, size, rr, gg, bb, sample);
        dst = new BufferedImage(newModel, raster, dst.isAlphaPremultiplied(), null);
    }
    dst.createGraphics().drawImage(src, 0, 0, null);
    return dst;
}

From source file:GifEncoder.java

/** Constructs a new GifEncoder using an 8-bit AWT Image.
 The image is assumed to be fully loaded. */
public GifEncoder(Image img) {
    width = img.getWidth(null);/*w w  w  .j a v  a2s  .  c o  m*/
    height = img.getHeight(null);
    pixels = new byte[width * height];
    PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
        System.err.println(e);
    }
    ColorModel cm = pg.getColorModel();
    if (cm instanceof IndexColorModel) {
        pixels = (byte[]) (pg.getPixels());
        // hpm
        IndexColorModel icm = (IndexColorModel) cm;
        setTransparentPixel(icm.getTransparentPixel());
    } else
        throw new IllegalArgumentException("IMAGE_ERROR");
    IndexColorModel m = (IndexColorModel) cm;
    int mapSize = m.getMapSize();
    r = new byte[mapSize];
    g = new byte[mapSize];
    b = new byte[mapSize];
    m.getReds(r);
    m.getGreens(g);
    m.getBlues(b);
    interlace = false;
    pixelIndex = 0;
    numPixels = width * height;
}

From source file:PngEncoder.java

/**
 * Writes the PLTE (Palate) chunk to the output stream.
 *
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is written
 *             to the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 *//*  w w w . j ava 2s.c  om*/
private void writePlteChunk(OutputStream out, Checksum csum) throws IOException {
    IndexColorModel icm = (IndexColorModel) image.getColorModel();

    writeInt(out, 768); // Chunk Size
    csum.reset();
    out.write(PLTE);

    byte[] reds = new byte[256];
    icm.getReds(reds);

    byte[] greens = new byte[256];
    icm.getGreens(greens);

    byte[] blues = new byte[256];
    icm.getBlues(blues);

    for (int index = 0; index < 256; ++index) {
        out.write(reds[index]);
        out.write(greens[index]);
        out.write(blues[index]);
    }

    writeInt(out, (int) csum.getValue());
}

From source file:lucee.runtime.img.Image.java

private static BufferedImage PaletteToARGB(BufferedImage src) {
    IndexColorModel icm = (IndexColorModel) src.getColorModel();
    int bands = icm.hasAlpha() ? 4 : 3;

    byte[][] data = new byte[bands][icm.getMapSize()];
    if (icm.hasAlpha())
        icm.getAlphas(data[3]);//  w  ww .j a  va2 s . c  om
    icm.getReds(data[0]);
    icm.getGreens(data[1]);
    icm.getBlues(data[2]);
    LookupTableJAI rtable = new LookupTableJAI(data);
    return JAI.create("lookup", src, rtable).getAsBufferedImage();
}

From source file:gdsc.utils.Cell_Outliner.java

private void applyColorModel(ImagePlus imp) {
    // Load the spectrum LUT 
    WindowManager.setTempCurrentImage(imp);
    LutLoader lut = new LutLoader();
    lut.run("spectrum");
    WindowManager.setTempCurrentImage(null);

    // Set zero to black
    ImageProcessor ip = imp.getProcessor();
    IndexColorModel cm = (IndexColorModel) ip.getColorModel();
    byte[] r = new byte[256];
    byte[] b = new byte[256];
    byte[] g = new byte[256];
    cm.getReds(r);
    cm.getBlues(b);//from   ww  w  .j  av a  2s . c  o  m
    cm.getGreens(g);
    r[0] = 0;
    b[0] = 0;
    g[0] = 0;
    cm = new IndexColorModel(8, 256, r, g, b);
    ip.setColorModel(cm);
}

From source file:org.apache.fop.render.pdf.AbstractImageAdapter.java

private static Integer getIndexOfFirstTransparentColorInPalette(IndexColorModel icm) {
    byte[] alphas = new byte[icm.getMapSize()];
    byte[] reds = new byte[icm.getMapSize()];
    byte[] greens = new byte[icm.getMapSize()];
    byte[] blues = new byte[icm.getMapSize()];
    icm.getAlphas(alphas);/*from   w  ww .j  a v a 2  s.  c  o m*/
    icm.getReds(reds);
    icm.getGreens(greens);
    icm.getBlues(blues);
    for (int i = 0; i < icm.getMapSize(); i++) {
        if ((alphas[i] & 0xFF) == 0) {
            return Integer.valueOf(i);
        }
    }
    return null;
}

From source file:org.geotools.gce.imagemosaic.ImageMosaicConfigHandler.java

/**
 * Use the passed coverageReader to create or update the all the needed configurations<br/>
 * It not responsible of the passed coverageReader which should be disposed outside (in the caller).
 * /*from w w  w. j  a va 2  s  .c o m*/
 * @param coverageReader
 * @param inputCoverageName
 * @param fileBeingProcessed
 * @param fileIndex
 * @param numFiles
 * @param transaction
 * @throws IOException
 */
public void updateConfiguration(GridCoverage2DReader coverageReader, final String inputCoverageName,
        File fileBeingProcessed, int fileIndex, double numFiles, DefaultTransaction transaction)
        throws IOException {

    final String indexName = getRunConfiguration().getParameter(Prop.INDEX_NAME);
    final String coverageName = coverageReader instanceof StructuredGridCoverage2DReader ? inputCoverageName
            : indexName;

    final Indexer indexer = getRunConfiguration().getIndexer();

    // checking whether the coverage already exists
    final boolean coverageExists = coverageExists(coverageName);
    MosaicConfigurationBean mosaicConfiguration = null;
    MosaicConfigurationBean currentConfigurationBean = null;
    RasterManager rasterManager = null;
    if (coverageExists) {

        // Get the manager for this coverage so it can be updated
        rasterManager = getParentReader().getRasterManager(coverageName);
        mosaicConfiguration = rasterManager.getConfiguration();
    }

    // STEP 2
    // Collecting all Coverage properties to setup a MosaicConfigurationBean through
    // the builder
    final MosaicBeanBuilder configBuilder = new MosaicBeanBuilder();

    final GeneralEnvelope envelope = (GeneralEnvelope) coverageReader.getOriginalEnvelope(inputCoverageName);
    final CoordinateReferenceSystem actualCRS = coverageReader.getCoordinateReferenceSystem(inputCoverageName);

    SampleModel sm = null;
    ColorModel cm = null;
    int numberOfLevels = 1;
    double[][] resolutionLevels = null;
    CatalogBuilderConfiguration catalogConfig;
    if (mosaicConfiguration == null) {
        catalogConfig = getRunConfiguration();
        // We don't have a configuration for this configuration

        // Get the type specifier for this image and the check that the
        // image has the correct sample model and color model.
        // If this is the first cycle of the loop we initialize everything.
        //
        ImageLayout layout = coverageReader.getImageLayout(inputCoverageName);
        cm = layout.getColorModel(null);
        sm = layout.getSampleModel(null);
        numberOfLevels = coverageReader.getNumOverviews(inputCoverageName) + 1;
        resolutionLevels = coverageReader.getResolutionLevels(inputCoverageName);

        // at the first step we initialize everything that we will
        // reuse afterwards starting with color models, sample
        // models, crs, etc....

        configBuilder.setSampleModel(sm);
        configBuilder.setColorModel(cm);
        ColorModel defaultCM = cm;

        // Checking palette
        if (defaultCM instanceof IndexColorModel) {
            IndexColorModel icm = (IndexColorModel) defaultCM;
            int numBands = defaultCM.getNumColorComponents();
            byte[][] defaultPalette = new byte[3][icm.getMapSize()];
            icm.getReds(defaultPalette[0]);
            icm.getGreens(defaultPalette[0]);
            icm.getBlues(defaultPalette[0]);
            if (numBands == 4) {
                icm.getAlphas(defaultPalette[0]);
            }
            configBuilder.setPalette(defaultPalette);
        }

        // STEP 2.A
        // Preparing configuration
        configBuilder.setCrs(actualCRS);
        configBuilder.setLevels(resolutionLevels);
        configBuilder.setLevelsNum(numberOfLevels);
        configBuilder.setName(coverageName);
        configBuilder.setTimeAttribute(IndexerUtils.getAttribute(coverageName, Utils.TIME_DOMAIN, indexer));
        configBuilder.setElevationAttribute(
                IndexerUtils.getAttribute(coverageName, Utils.ELEVATION_DOMAIN, indexer));
        configBuilder.setAdditionalDomainAttributes(
                IndexerUtils.getAttribute(coverageName, Utils.ADDITIONAL_DOMAIN, indexer));

        final Hints runHints = getRunConfiguration().getHints();
        if (runHints != null && runHints.containsKey(Utils.AUXILIARY_FILES_PATH)) {
            String auxiliaryFilePath = (String) runHints.get(Utils.AUXILIARY_FILES_PATH);
            if (auxiliaryFilePath != null && auxiliaryFilePath.trim().length() > 0) {
                configBuilder.setAuxiliaryFilePath(auxiliaryFilePath);
            }
        }

        final CatalogConfigurationBean catalogConfigurationBean = new CatalogConfigurationBean();
        catalogConfigurationBean.setCaching(IndexerUtils.getParameterAsBoolean(Prop.CACHING, indexer));
        catalogConfigurationBean
                .setAbsolutePath(IndexerUtils.getParameterAsBoolean(Prop.ABSOLUTE_PATH, indexer));

        catalogConfigurationBean
                .setLocationAttribute(IndexerUtils.getParameter(Prop.LOCATION_ATTRIBUTE, indexer));

        catalogConfigurationBean.setTypeName(coverageName);

        configBuilder.setCatalogConfigurationBean(catalogConfigurationBean);
        configBuilder.setCheckAuxiliaryMetadata(
                IndexerUtils.getParameterAsBoolean(Prop.CHECK_AUXILIARY_METADATA, indexer));

        currentConfigurationBean = configBuilder.getMosaicConfigurationBean();

        // Creating a rasterManager which will be initialized after populating the catalog
        rasterManager = getParentReader().addRasterManager(currentConfigurationBean, false);

        // Creating a granuleStore
        if (!useExistingSchema) {
            // creating the schema
            SimpleFeatureType indexSchema = CatalogManager.createSchema(getRunConfiguration(),
                    currentConfigurationBean.getName(), actualCRS);
            getParentReader().createCoverage(coverageName, indexSchema);
            //            } else {
            //                rasterManager.typeName = coverageName;
        }
        getConfigurations().put(currentConfigurationBean.getName(), currentConfigurationBean);

    } else {
        catalogConfig = new CatalogBuilderConfiguration();
        CatalogConfigurationBean bean = mosaicConfiguration.getCatalogConfigurationBean();
        catalogConfig.setParameter(Prop.LOCATION_ATTRIBUTE, (bean.getLocationAttribute()));
        catalogConfig.setParameter(Prop.ABSOLUTE_PATH, Boolean.toString(bean.isAbsolutePath()));
        catalogConfig.setParameter(Prop.ROOT_MOSAIC_DIR/* setRootMosaicDirectory( */,
                getRunConfiguration().getParameter(Prop.ROOT_MOSAIC_DIR));

        // We already have a Configuration for this coverage.
        // Check its properties are compatible with the existing coverage.

        CatalogConfigurationBean catalogConfigurationBean = bean;
        if (!catalogConfigurationBean.isHeterogeneous()) {

            // There is no need to check resolutions if the mosaic
            // has been already marked as heterogeneous

            numberOfLevels = coverageReader.getNumOverviews(inputCoverageName) + 1;
            boolean needUpdate = false;

            //
            // Heterogeneousity check
            //
            if (numberOfLevels != mosaicConfiguration.getLevelsNum()) {
                catalogConfigurationBean.setHeterogeneous(true);
                if (numberOfLevels > mosaicConfiguration.getLevelsNum()) {
                    resolutionLevels = coverageReader.getResolutionLevels(inputCoverageName);
                    mosaicConfiguration.setLevels(resolutionLevels);
                    mosaicConfiguration.setLevelsNum(numberOfLevels);
                    needUpdate = true;
                }
            } else {
                final double[][] mosaicLevels = mosaicConfiguration.getLevels();
                resolutionLevels = coverageReader.getResolutionLevels(inputCoverageName);
                final boolean homogeneousLevels = Utils.homogeneousCheck(numberOfLevels, resolutionLevels,
                        mosaicLevels);
                if (!homogeneousLevels) {
                    catalogConfigurationBean.setHeterogeneous(true);
                    needUpdate = true;
                }
            }
            // configuration need to be updated
            if (needUpdate) {
                getConfigurations().put(mosaicConfiguration.getName(), mosaicConfiguration);
            }
        }
        ImageLayout layout = coverageReader.getImageLayout(inputCoverageName);
        cm = layout.getColorModel(null);
        sm = layout.getSampleModel(null);

        // comparing ColorModel
        // comparing SampeModel
        // comparing CRSs
        ColorModel actualCM = cm;
        CoordinateReferenceSystem expectedCRS;
        if (mosaicConfiguration.getCrs() != null) {
            expectedCRS = mosaicConfiguration.getCrs();
        } else {
            expectedCRS = rasterManager.spatialDomainManager.coverageCRS;
        }
        if (!(CRS.equalsIgnoreMetadata(expectedCRS, actualCRS))) {
            // if ((fileIndex > 0 ? !(CRS.equalsIgnoreMetadata(defaultCRS, actualCRS)) : false)) {
            eventHandler.fireFileEvent(Level.INFO, fileBeingProcessed, false,
                    "Skipping image " + fileBeingProcessed + " because CRSs do not match.",
                    (((fileIndex + 1) * 99.0) / numFiles));
            return;
        }

        byte[][] palette = mosaicConfiguration.getPalette();
        ColorModel colorModel = mosaicConfiguration.getColorModel();
        if (colorModel == null) {
            palette = rasterManager.getConfiguration().getPalette();
            colorModel = rasterManager.defaultCM;
        }
        if (Utils.checkColorModels(colorModel, palette, mosaicConfiguration, actualCM)) {
            // if (checkColorModels(defaultCM, defaultPalette, actualCM)) {
            eventHandler.fireFileEvent(Level.INFO, fileBeingProcessed, false,
                    "Skipping image " + fileBeingProcessed + " because color models do not match.",
                    (((fileIndex + 1) * 99.0) / numFiles));
            return;
        }

    }
    // STEP 3
    if (!useExistingSchema) {
        // create and store features
        CatalogManager.updateCatalog(coverageName, fileBeingProcessed, coverageReader, getParentReader(),
                catalogConfig, envelope, transaction, getPropertiesCollectors());
    }
}

From source file:org.geotools.utils.imagemosaic.MosaicIndexBuilder.java

/**
 * Main thread for the mosaic index builder.
 *///w w  w  .  java 2  s. c  o m
public void run() {

    // /////////////////////////////////////////////////////////////////////
    //
    // CREATING INDEX FILE
    //
    // /////////////////////////////////////////////////////////////////////

    // /////////////////////////////////////////////////////////////////////
    //
    // Create a file handler that write log record to a file called
    // my.log
    //
    // /////////////////////////////////////////////////////////////////////
    FileHandler handler = null;
    try {
        boolean append = true;
        handler = new FileHandler(new StringBuffer(locationPath).append("/error.txt").toString(), append);
        handler.setLevel(Level.SEVERE);
        // Add to the desired logger
        LOGGER.addHandler(handler);

        // /////////////////////////////////////////////////////////////////////
        //
        // Create a set of file names that have to be skipped since these are
        // our metadata files
        //
        // /////////////////////////////////////////////////////////////////////
        final Set<String> skipFiles = new HashSet<String>(
                Arrays.asList(new String[] { indexName + ".shp", indexName + ".dbf", indexName + ".shx",
                        indexName + ".prj", "error.txt", "error.txt.lck", indexName + ".properties" }));

        // /////////////////////////////////////////////////////////////////////
        //
        // Creating temp vars
        //
        // /////////////////////////////////////////////////////////////////////
        ShapefileDataStore index = null;
        Transaction t = new DefaultTransaction();
        // declaring a preciosion model to adhere the java double type
        // precision
        PrecisionModel precMod = new PrecisionModel(PrecisionModel.FLOATING);
        GeometryFactory geomFactory = new GeometryFactory(precMod);
        try {
            index = new ShapefileDataStore(
                    new File(locationPath + File.separator + indexName + ".shp").toURI().toURL());
        } catch (MalformedURLException ex) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            fireException(ex);
            return;
        }

        final List<File> files = new ArrayList<File>();
        recurse(files, locationPath);

        // /////////////////////////////////////////////////////////////////////
        //
        // Cycling over the files that have filtered out
        //
        // /////////////////////////////////////////////////////////////////////
        numFiles = files.size();
        String validFileName = null;
        final Iterator<File> filesIt = files.iterator();
        FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null;
        boolean doneSomething = false;
        for (int i = 0; i < numFiles; i++) {

            StringBuffer message;
            // //
            //
            // Check that this file is actually good to go
            //
            // //         
            final File fileBeingProcessed = ((File) filesIt.next());
            if (!fileBeingProcessed.exists() || !fileBeingProcessed.canRead() || !fileBeingProcessed.isFile()) {
                // send a message
                message = new StringBuffer("Skipped file ").append(files.get(i))
                        .append(" snce it seems invalid.");
                if (LOGGER.isLoggable(Level.INFO))
                    LOGGER.info(message.toString());
                fireEvent(message.toString(), ((i * 99.0) / numFiles));
                continue;
            }

            // //
            //
            // Anyone has asked us to stop?
            //
            // //
            if (getStopThread()) {
                message = new StringBuffer("Stopping requested at file  ").append(i).append(" of ")
                        .append(numFiles).append(" files");
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), ((i * 100.0) / numFiles));
                return;
            } // replacing chars on input path
            try {
                validFileName = fileBeingProcessed.getCanonicalPath();
            } catch (IOException e1) {
                fireException(e1);
                return;
            }
            validFileName = validFileName.replace('\\', '/');
            validFileName = validFileName.substring(locationPath.length() + 1,
                    fileBeingProcessed.getAbsolutePath().length());
            if (skipFiles.contains(validFileName))
                continue;
            message = new StringBuffer("Now indexing file ").append(validFileName);

            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), ((i * 100.0) / numFiles));
            try {
                // ////////////////////////////////////////////////////////
                //
                //
                // STEP 1
                // Getting an ImageIO reader for this coverage.
                //
                //
                // ////////////////////////////////////////////////////////
                ImageInputStream inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                if (inStream == null) {
                    if (LOGGER.isLoggable(Level.SEVERE))
                        LOGGER.severe(fileBeingProcessed
                                + " has been skipped since we could not get a stream for it");
                    continue;
                }
                inStream.mark();
                final Iterator<ImageReader> it = ImageIO.getImageReaders(inStream);
                ImageReader r = null;
                if (it.hasNext()) {
                    r = (ImageReader) it.next();
                    r.setInput(inStream);
                } else {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    //               try {
                    //                  r.dispose();
                    //               } catch (Exception e) {
                    //                  // ignore exception
                    //               }

                    // send a message
                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(":No ImageIO readeres avalaible.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 2
                // Getting a coverage reader for this coverage.
                //
                // ////////////////////////////////////////////////////////
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(new StringBuffer("Getting a reader").toString());
                final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder
                        .findFormat(files.get(i));
                if (format == null || !format.accepts(files.get(i))) {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    try {
                        r.dispose();
                    } catch (Exception e) {
                        // ignore exception
                    }

                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(": File format is not supported.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }
                final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format
                        .getReader(files.get(i));
                envelope = (GeneralEnvelope) reader.getOriginalEnvelope();
                actualCRS = reader.getCrs();

                // /////////////////////////////////////////////////////////////////////
                //
                // STEP 3
                // Get the type specifier for this image and the check that the
                // image has the correct sample model and color model.
                // If this is the first cycle of the loop we initialize
                // eveything.
                //
                // /////////////////////////////////////////////////////////////////////
                final ImageTypeSpecifier its = ((ImageTypeSpecifier) r.getImageTypes(0).next());
                boolean skipFeature = false;
                if (globEnvelope == null) {
                    // /////////////////////////////////////////////////////////////////////
                    //
                    // at the first step we initialize everything that we will
                    // reuse afterwards starting with color models, sample
                    // models, crs, etc....
                    //
                    // /////////////////////////////////////////////////////////////////////
                    defaultCM = its.getColorModel();
                    if (defaultCM instanceof IndexColorModel) {
                        IndexColorModel icm = (IndexColorModel) defaultCM;
                        int numBands = defaultCM.getNumColorComponents();
                        defaultPalette = new byte[3][icm.getMapSize()];
                        icm.getReds(defaultPalette[0]);
                        icm.getGreens(defaultPalette[0]);
                        icm.getBlues(defaultPalette[0]);
                        if (numBands == 4)
                            icm.getAlphas(defaultPalette[0]);

                    }
                    defaultSM = its.getSampleModel();
                    defaultCRS = actualCRS;
                    globEnvelope = new GeneralEnvelope(envelope);

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // getting information about resolution
                    //
                    // /////////////////////////////////////////////////////////////////////

                    // //
                    //
                    // get the dimension of the hr image and build the model
                    // as well as
                    // computing the resolution
                    // //
                    // resetting reader and recreating stream, turnaround for a
                    // strange imageio bug
                    r.reset();
                    try {
                        inStream.reset();
                    } catch (IOException e) {
                        inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                    }
                    //let's check if we got something now
                    if (inStream == null) {
                        //skip file
                        if (LOGGER.isLoggable(Level.WARNING))
                            LOGGER.warning("Skipping file " + fileBeingProcessed.toString());
                        continue;
                    }
                    r.setInput(inStream);
                    numberOfLevels = r.getNumImages(true);
                    resolutionLevels = new double[2][numberOfLevels];
                    double[] res = getResolution(envelope, new Rectangle(r.getWidth(0), r.getHeight(0)),
                            defaultCRS);
                    resolutionLevels[0][0] = res[0];
                    resolutionLevels[1][0] = res[1];

                    // resolutions levels
                    if (numberOfLevels > 1) {

                        for (int k = 0; k < numberOfLevels; k++) {
                            res = getResolution(envelope, new Rectangle(r.getWidth(k), r.getHeight(k)),
                                    defaultCRS);
                            resolutionLevels[0][k] = res[0];
                            resolutionLevels[1][k] = res[1];
                        }
                    }

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // creating the schema
                    //
                    // /////////////////////////////////////////////////////////////////////
                    final SimpleFeatureTypeBuilder featureBuilder = new SimpleFeatureTypeBuilder();
                    featureBuilder.setName("Flag");
                    featureBuilder.setNamespaceURI("http://www.geo-solutions.it/");
                    featureBuilder.add("location", String.class);
                    featureBuilder.add("the_geom", Polygon.class, this.actualCRS);
                    featureBuilder.setDefaultGeometry("the_geom");
                    final SimpleFeatureType simpleFeatureType = featureBuilder.buildFeatureType();
                    // create the schema for the new shape file
                    index.createSchema(simpleFeatureType);

                    // get a feature writer
                    fw = index.getFeatureWriter(t);
                } else {
                    // ////////////////////////////////////////////////////////
                    // 
                    // comparing ColorModel
                    // comparing SampeModel
                    // comparing CRSs
                    // ////////////////////////////////////////////////////////
                    globEnvelope.add(envelope);
                    actualCM = its.getColorModel();
                    actualSM = its.getSampleModel();
                    skipFeature = (i > 0 ? !(CRS.equalsIgnoreMetadata(defaultCRS, actualCRS)) : false);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because CRSs do not match.").toString());
                    skipFeature = checkColorModels(defaultCM, defaultPalette, actualCM);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because color models do not match.").toString());
                    // defaultCM.getNumComponents()==actualCM.getNumComponents()&&
                    // defaultCM.getClass().equals(actualCM.getClass())
                    // && defaultSM.getNumBands() == actualSM
                    // .getNumBands()
                    // && defaultSM.getDataType() == actualSM
                    // .getDataType() &&
                    //
                    // if (skipFeature)
                    // LOGGER
                    // .warning(new StringBuffer("Skipping image ")
                    // .append(files.get(i))
                    // .append(
                    // " because cm or sm does not match.")
                    // .toString());
                    // res = getResolution(envelope, new
                    // Rectangle(r.getWidth(0),
                    // r.getHeight(0)), defaultCRS);
                    // if (Math.abs((resX - res[0]) / resX) > EPS
                    // || Math.abs(resY - res[1]) > EPS) {
                    // LOGGER.warning(new StringBuffer("Skipping image
                    // ").append(
                    // files.get(i)).append(
                    // " because resolutions does not match.")
                    // .toString());
                    // skipFeature = true;
                    // }
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 4
                //
                // create and store features
                //
                // ////////////////////////////////////////////////////////
                if (!skipFeature) {

                    final SimpleFeature feature = fw.next();
                    feature.setAttribute(1,
                            geomFactory.toGeometry(new ReferencedEnvelope((Envelope) envelope)));
                    feature.setAttribute(
                            0, absolute
                                    ? new StringBuilder(this.locationPath).append(File.separatorChar)
                                            .append(validFileName).toString()
                                    : validFileName);
                    fw.write();

                    message = new StringBuffer("Done with file ").append(files.get(i));
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.fine(message.toString());
                    }
                    message.append('\n');
                    fireEvent(message.toString(), (((i + 1) * 99.0) / numFiles));
                    doneSomething = true;
                } else
                    skipFeature = false;

                // ////////////////////////////////////////////////////////
                //
                // STEP 5
                //
                // release resources
                //
                // ////////////////////////////////////////////////////////
                try {
                    inStream.close();
                } catch (Exception e) {
                    // ignore exception
                }
                try {
                    r.dispose();
                } catch (Exception e) {
                    // ignore exception
                }
                // release resources
                reader.dispose();

            } catch (IOException e) {
                fireException(e);
                break;
            } catch (ArrayIndexOutOfBoundsException e) {
                fireException(e);
                break;
            }

        }
        try {
            if (fw != null)
                fw.close();
            t.commit();
            t.close();
            index.dispose();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
        createPropertiesFiles(globEnvelope, doneSomething);
    } catch (SecurityException el) {
        fireException(el);
        return;
    } catch (IOException el) {
        fireException(el);
        return;
    } finally {
        try {
            if (handler != null)
                handler.close();
        } catch (Throwable e) {
            // ignore
        }

    }

}

From source file:util.ImgJaiTool.java

protected static RenderedOp removeAlphaTransparency(RenderedOp image) {
    ColorModel cm = image.getColorModel();
    if (cm.hasAlpha() || cm.getNumColorComponents() == 4) {
        if (cm instanceof IndexColorModel) {
            // band combine doesn't work on IndexColorModel
            // http://java.sun.com/products/java-media/jai/jai-bugs-1_0_2.html
            IndexColorModel icm = (IndexColorModel) cm;
            byte[][] data = new byte[3][icm.getMapSize()];
            icm.getReds(data[0]);
            icm.getGreens(data[1]);// w w  w .ja va2  s .  c  om
            icm.getBlues(data[2]);
            LookupTableJAI lut = new LookupTableJAI(data);
            image = JAI.create("lookup", image, lut);
        } else {
            image = BandCombineDescriptor.create(image, strip_alpha_matrix, null);
        }
    }
    return image;
}