List of usage examples for java.awt.image IndexColorModel getAlphas
public final void getAlphas(byte[] a)
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]); icm.getReds(data[0]);//from www. j a v a 2 s.c om icm.getGreens(data[1]); icm.getBlues(data[2]); LookupTableJAI rtable = new LookupTableJAI(data); return JAI.create("lookup", src, rtable).getAsBufferedImage(); }
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); icm.getReds(reds);/*w w w . java 2s. c o m*/ 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). * //w ww . j a v a 2s . c om * @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. *//*from www. j a v a2 s .co 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 } } }