Example usage for java.awt.image ColorModel getNumColorComponents

List of usage examples for java.awt.image ColorModel getNumColorComponents

Introduction

In this page you can find the example usage for java.awt.image ColorModel getNumColorComponents.

Prototype

public int getNumColorComponents() 

Source Link

Document

Returns the number of color components in this ColorModel .

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    Image image = new ImageIcon("a.png").getImage();
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        System.out.println(bimage.getColorModel().getNumColorComponents());
    }/*  w w  w . ja va  2  s  .com*/

    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
    }
    ColorModel cm = pg.getColorModel();
    System.out.println(cm.getNumColorComponents());
}

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

public Struct info() throws ExpressionException {
    if (sctInfo != null)
        return sctInfo;

    Struct sctInfo = new StructImpl(), sct;

    sctInfo.setEL("height", new Double(getHeight()));
    sctInfo.setEL("width", new Double(getWidth()));
    sctInfo.setEL("source", source == null ? "" : source.getAbsolutePath());
    //sct.setEL("mime_type",getMimeType());

    ColorModel cm = image().getColorModel();
    sct = new StructImpl();
    sctInfo.setEL("colormodel", sct);

    sct.setEL("alpha_channel_support", Caster.toBoolean(cm.hasAlpha()));
    sct.setEL("alpha_premultiplied", Caster.toBoolean(cm.isAlphaPremultiplied()));
    sct.setEL("transparency", toStringTransparency(cm.getTransparency()));
    sct.setEL("pixel_size", Caster.toDouble(cm.getPixelSize()));
    sct.setEL("num_components", Caster.toDouble(cm.getNumComponents()));
    sct.setEL("num_color_components", Caster.toDouble(cm.getNumColorComponents()));
    sct.setEL("colorspace", toStringColorSpace(cm.getColorSpace()));

    //bits_component
    int[] bitspercomponent = cm.getComponentSize();
    Array arr = new ArrayImpl();
    Double value;/*  ww w . j  a v a2 s .  c  om*/
    for (int i = 0; i < bitspercomponent.length; i++) {
        sct.setEL("bits_component_" + (i + 1), value = new Double(bitspercomponent[i]));
        arr.appendEL(value);
    }
    sct.setEL("bits_component", arr);

    // colormodel_type
    if (cm instanceof ComponentColorModel)
        sct.setEL("colormodel_type", "ComponentColorModel");
    else if (cm instanceof IndexColorModel)
        sct.setEL("colormodel_type", "IndexColorModel");
    else if (cm instanceof PackedColorModel)
        sct.setEL("colormodel_type", "PackedColorModel");
    else
        sct.setEL("colormodel_type", ListUtil.last(cm.getClass().getName(), '.'));

    getMetaData(sctInfo);

    ImageMeta.addInfo(format, source, sctInfo);

    this.sctInfo = sctInfo;
    return sctInfo;
}

From source file:org.apache.fop.render.pcl.PCLGenerator.java

private RenderedImage getMask(RenderedImage img, Dimension targetDim) {
    ColorModel cm = img.getColorModel();
    if (cm.hasAlpha()) {
        BufferedImage alpha = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Raster raster = img.getData();
        GraphicsUtil.copyBand(raster, cm.getNumColorComponents(), alpha.getRaster(), 0);

        BufferedImageOp op1 = new LookupOp(new ByteLookupTable(0, THRESHOLD_TABLE), null);
        BufferedImage alphat = op1.filter(alpha, null);

        BufferedImage mask;/*  ww w .j a  va 2  s.  c o m*/
        if (true) {
            mask = new BufferedImage(targetDim.width, targetDim.height, BufferedImage.TYPE_BYTE_BINARY);
        } else {
            byte[] arr = { (byte) 0, (byte) 0xff };
            ColorModel colorModel = new IndexColorModel(1, 2, arr, arr, arr);
            WritableRaster wraster = Raster.createPackedRaster(DataBuffer.TYPE_BYTE, targetDim.width,
                    targetDim.height, 1, 1, null);
            mask = new BufferedImage(colorModel, wraster, false, null);
        }

        Graphics2D g2d = mask.createGraphics();
        try {
            AffineTransform at = new AffineTransform();
            double sx = targetDim.getWidth() / img.getWidth();
            double sy = targetDim.getHeight() / img.getHeight();
            at.scale(sx, sy);
            g2d.drawRenderedImage(alphat, at);
        } finally {
            g2d.dispose();
        }
        /*
        try {
        BatchDiffer.saveAsPNG(alpha, new java.io.File("D:/out-alpha.png"));
        BatchDiffer.saveAsPNG(mask, new java.io.File("D:/out-mask.png"));
        } catch (IOException e) {
        e.printStackTrace();
        }*/
        return mask;
    } else {
        return null;
    }
}

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    RenderedImage imageData = null;
    IIOException firstException = null;

    IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA);
    boolean ignoreMetadata = (iiometa != null);
    boolean providerIgnoresICC = false;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream imgStream = ImageUtil.needImageInputStream(src);
    try {/*from w  w w.ja va2  s  .co  m*/
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                ImageReadParam param = reader.getDefaultReadParam();
                reader.setInput(imgStream, false, ignoreMetadata);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                        imageData = reader.read(pageIndex, param);
                    } else {
                        imageData = reader.read(pageIndex, param);
                        //imageData = reader.readAsRenderedImage(pageIndex, param);
                        //TODO Reenable the above when proper listeners are implemented
                        //to react to late pixel population (so the stream can be closed
                        //properly).
                    }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    break; //Quit early, we have the image
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw
                    //IllegalArgumentExceptions when they have trouble parsing the image.
                    throw new ImageException("Error loading image using ImageIO codec", iae);
                } catch (IIOException iioe) {
                    if (firstException == null) {
                        firstException = iioe;
                    } else {
                        log.debug("non-first error loading image: " + iioe.getMessage());
                    }
                }
                try {
                    //Try fallback for CMYK images
                    BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param);
                    imageData = bi;
                    firstException = null; //Clear exception after successful fallback attempt
                    break;
                } catch (IIOException iioe) {
                    //ignore
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        ImageUtil.closeQuietly(src);
        //TODO Some codecs may do late reading.
    }
    if (firstException != null) {
        throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException);
    }
    if (imageData == null) {
        throw new ImageException("No ImageIO ImageReader found .");
    }

    ColorModel cm = imageData.getColorModel();

    Color transparentColor = null;
    if (cm instanceof IndexColorModel) {
        //transparent color will be extracted later from the image
    } else {
        if (providerIgnoresICC && cm instanceof ComponentColorModel) {
            // Apply ICC Profile to Image by creating a new image with a new
            // color model.
            ICC_Profile iccProf = tryToExctractICCProfile(iiometa);
            if (iccProf != null) {
                ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(),
                        cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType());
                WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null);
                imageData.copyData(wr);
                BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                imageData = bi;
                cm = cm2;
            }
        }
        // ImageIOUtil.dumpMetadataToSystemOut(iiometa);
        // Retrieve the transparent color from the metadata
        if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) {
            Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
            Element dim = ImageIOUtil.getChild(metanode, "Transparency");
            if (dim != null) {
                Element child;
                child = ImageIOUtil.getChild(dim, "TransparentColor");
                if (child != null) {
                    String value = child.getAttribute("value");
                    if (value == null || value.length() == 0) {
                        //ignore
                    } else if (cm.getNumColorComponents() == 1) {
                        int gray = Integer.parseInt(value);
                        transparentColor = new Color(gray, gray, gray);
                    } else {
                        StringTokenizer st = new StringTokenizer(value);
                        transparentColor = new Color(Integer.parseInt(st.nextToken()),
                                Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                    }
                }
            }
        }
    }

    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
        return new ImageBuffered(info, (BufferedImage) imageData, transparentColor);
    } else {
        return new ImageRendered(info, imageData, transparentColor);
    }
}

From source file:org.geoserver.catalog.CoverageViewReader.java

private int getAlphaBandIndex(GridCoverage2D coverage) {
    final ColorModel cm = coverage.getRenderedImage().getColorModel();
    if (!cm.hasAlpha() || cm.getNumComponents() == cm.getNumColorComponents()) {
        throw new IllegalArgumentException(
                "The source coverage does not have an alpha band, cannot extract an alpha band");
    }//from   w  w w.  j av  a2s.  co m
    // the alpha band is always the last (see ComponentColorModel.getAlphaRaster or the getAlpha(object) code
    if (cm.getNumColorComponents() == 1) {
        // gray-alpha
        return 1;
    } else {
        // rgba/argb
        return 3;
    }
}

From source file:org.geoserver.catalog.CoverageViewReader.java

private boolean hasAlphaBand(ColorModel cm) {
    // num components returns the alpha, num _color_ components does not
    return (cm.getNumComponents() == 2 && cm.getNumColorComponents() == 1)
            /* gray-alpha case */ || (cm.getNumComponents() == 4
                    && cm.getNumColorComponents() == 3) /* rgba case */;
}

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  www. jav a 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.photovault.swingui.color.ColorSettingsDlg.java

private void setupColorCurvesForImage() {
    if (previewImage != null) {
        ColorModel cm = previewImage.getCorrectedImageColorModel();
        if (cm != null) {
            setColorChannelCurvesEnabled(cm.getNumColorComponents() >= 3);
        } else {/*  w  w  w  .  ja v  a2 s. c  om*/
            /*
             The image has not yet been rendered. Register a listener so that 
             we can complete setup after rendering the image
             */
            previewImage.addRenderingListener(this);
        }
    }
    // Update color curves with histogram data from this image.
    showCurve(currentColorCurve);
}

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]);/*from www.  jav a 2s  . c  om*/
            icm.getGreens(data[1]);
            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;
}