Example usage for java.awt.image ColorModel hasAlpha

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

Introduction

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

Prototype

public final boolean hasAlpha() 

Source Link

Document

Returns whether or not alpha is supported in this ColorModel .

Usage

From source file:com.aurel.track.attachment.AttachBL.java

private static boolean hasAlpha(Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        return bimage.getColorModel().hasAlpha();
    }/*from   w ww.j av a 2  s.  c o  m*/

    // grabbing a single pixel is usually sufficient
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
    }

    // Get the image's color model
    ColorModel cm = pg.getColorModel();
    return cm.hasAlpha();
}

From source file:net.sf.jasperreports.engine.RenderableUtil.java

/**
 *
 *///  w w  w .  j  a v a2  s  .c o  m
public Renderable getRenderable(Image img, OnErrorTypeEnum onErrorType) throws JRException {
    ImageTypeEnum type = ImageTypeEnum.JPEG;
    if (img instanceof RenderedImage) {
        ColorModel colorModel = ((RenderedImage) img).getColorModel();
        //if the image has transparency, encode as PNG
        if (colorModel.hasAlpha() && colorModel.getTransparency() != Transparency.OPAQUE) {
            type = ImageTypeEnum.PNG;
        }
    }

    return getRenderable(img, type, onErrorType);
}

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

/**
 * This method returns true if the specified image has transparent pixels
 * @param image//from   w ww  .j  a  va2s .  c om
 * @return
 */
public static boolean hasAlpha(java.awt.Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        return bimage.getColorModel().hasAlpha();
    }

    // Use a pixel grabber to retrieve the image's color model;
    // grabbing a single pixel is usually sufficient
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
    }

    // Get the image's color model
    ColorModel cm = pg.getColorModel();
    return cm.hasAlpha();
}

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

private void _writeOut(ImageOutputStream ios, String format, float quality, boolean noMeta)
        throws IOException, ExpressionException {
    if (quality < 0 || quality > 1)
        throw new IOException(
                "quality has an invalid value [" + quality + "], value has to be between 0 and 1");
    if (StringUtil.isEmpty(format))
        format = this.format;
    if (StringUtil.isEmpty(format))
        throw new IOException("missing format");

    BufferedImage im = image();//  w  w w .j ava2  s  .  c  o  m

    //IIOMetadata meta = noMeta?null:metadata(format);
    IIOMetadata meta = noMeta ? null : getMetaData(null);

    ImageWriter writer = null;
    ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(im);
    Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, format);

    if (iter.hasNext()) {
        writer = iter.next();
    }
    if (writer == null)
        throw new IOException("no writer for format [" + format + "] available, available writer formats are ["
                + ListUtil.arrayToList(ImageUtil.getWriterFormatNames(), ",") + "]");

    ImageWriteParam iwp = null;
    if ("jpg".equalsIgnoreCase(format)) {
        ColorModel cm = im.getColorModel();
        if (cm.hasAlpha())
            im = jpgImage(im);
        JPEGImageWriteParam jiwp = new JPEGImageWriteParam(Locale.getDefault());
        jiwp.setOptimizeHuffmanTables(true);
        iwp = jiwp;
    } else
        iwp = writer.getDefaultWriteParam();

    setCompressionModeEL(iwp, ImageWriteParam.MODE_EXPLICIT);
    setCompressionQualityEL(iwp, quality);
    writer.setOutput(ios);
    try {
        writer.write(meta, new IIOImage(im, null, meta), iwp);

    } finally {
        writer.dispose();
        ios.flush();
    }
}

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

public void rotate(float x, float y, float angle, int interpolation) throws ExpressionException {
    if (x == -1)//from  ww  w .  ja  v a2s  .co m
        x = (float) getWidth() / 2;
    if (y == -1)
        y = (float) getHeight() / 2;

    angle = (float) Math.toRadians(angle);
    ColorModel cmSource = image().getColorModel();

    if (cmSource instanceof IndexColorModel && cmSource.hasAlpha() && !cmSource.isAlphaPremultiplied()) {
        image(PaletteToARGB(image()));
        cmSource = image().getColorModel();
    }

    BufferedImage alpha = null;
    if (cmSource.hasAlpha() && !cmSource.isAlphaPremultiplied()) {
        alpha = getAlpha(image());
        image(removeAlpha(image()));
    }

    Interpolation interp = Interpolation.getInstance(0);
    if (INTERPOLATION_BICUBIC == interpolation)
        interp = Interpolation.getInstance(1);
    else if (INTERPOLATION_BILINEAR == interpolation)
        interp = Interpolation.getInstance(2);

    if (alpha != null) {
        ParameterBlock params = new ParameterBlock();
        params.addSource(alpha);
        params.add(x);
        params.add(y);
        params.add(angle);
        params.add(interp);
        params.add(new double[] { 0.0 });
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                (RenderingHints.VALUE_INTERPOLATION_BICUBIC));
        hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                new BorderExtenderConstant(new double[] { 255.0 })));
        hints.add(new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.TRUE));
        alpha = JAI.create("rotate", params, hints).getAsBufferedImage();
    }

    ParameterBlock params = new ParameterBlock();
    params.addSource(image());
    params.add(x);
    params.add(y);
    params.add(angle);
    params.add(interp);
    params.add(new double[] { 0.0 });
    BorderExtender extender = new BorderExtenderConstant(new double[] { 0.0 });
    RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
    hints.add(new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.TRUE));
    image(JAI.create("rotate", params, hints).getAsBufferedImage());
    if (alpha != null)
        image(addAlpha(image(), alpha, 0, 0));
}

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;//from  w  w w. j  a v a2  s.c  o  m
    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;/*from   w ww  . j a v  a  2s .  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.fop.render.pdf.ImageRawPNGAdapter.java

/** {@inheritDoc} */
public void setup(PDFDocument doc) {
    super.setup(doc);
    ColorModel cm = ((ImageRawPNG) this.image).getColorModel();
    if (cm instanceof IndexColorModel) {
        numberOfInterleavedComponents = 1;
    } else {/*w w  w .jav a2  s.  c o m*/
        // this can be 1 (gray), 2 (gray + alpha), 3 (rgb) or 4 (rgb + alpha)
        // numberOfInterleavedComponents = (cm.hasAlpha() ? 1 : 0) + cm.getNumColorComponents();
        numberOfInterleavedComponents = cm.getNumComponents();
    }

    // set up image compression for non-alpha channel
    FlateFilter flate;
    try {
        flate = new FlateFilter();
        flate.setApplied(true);
        flate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
        if (numberOfInterleavedComponents < 3) {
            // means palette (1) or gray (1) or gray + alpha (2)
            flate.setColors(1);
        } else {
            // means rgb (3) or rgb + alpha (4)
            flate.setColors(3);
        }
        flate.setColumns(image.getSize().getWidthPx());
        flate.setBitsPerComponent(this.getBitsPerComponent());
    } catch (PDFFilterException e) {
        throw new RuntimeException("FlateFilter configuration error", e);
    }
    this.pdfFilter = flate;
    this.disallowMultipleFilters();

    // Handle transparency channel if applicable; note that for palette images the transparency is
    // not TRANSLUCENT
    if (cm.hasAlpha() && cm.getTransparency() == ColorModel.TRANSLUCENT) {
        doc.getProfile().verifyTransparencyAllowed(image.getInfo().getOriginalURI());
        // TODO: Implement code to combine image with background color if transparency is not allowed
        // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha channel
        // and then deflate it back again
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DeflaterOutputStream dos = new DeflaterOutputStream(baos, new Deflater());
        InputStream in = ((ImageRawStream) image).createInputStream();
        try {
            InflaterInputStream infStream = new InflaterInputStream(in, new Inflater());
            DataInputStream dataStream = new DataInputStream(infStream);
            // offset is the byte offset of the alpha component
            int offset = numberOfInterleavedComponents - 1; // 1 for GA, 3 for RGBA
            int numColumns = image.getSize().getWidthPx();
            int bytesPerRow = numberOfInterleavedComponents * numColumns;
            int filter;
            // read line by line; the first byte holds the filter
            while ((filter = dataStream.read()) != -1) {
                byte[] bytes = new byte[bytesPerRow];
                dataStream.readFully(bytes, 0, bytesPerRow);
                dos.write((byte) filter);
                for (int j = 0; j < numColumns; j++) {
                    dos.write(bytes, offset, 1);
                    offset += numberOfInterleavedComponents;
                }
                offset = numberOfInterleavedComponents - 1;
            }
            dos.close();
        } catch (IOException e) {
            throw new RuntimeException("Error processing transparency channel:", e);
        } finally {
            IOUtils.closeQuietly(in);
        }
        // set up alpha channel compression
        FlateFilter transFlate;
        try {
            transFlate = new FlateFilter();
            transFlate.setApplied(true);
            transFlate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
            transFlate.setColors(1);
            transFlate.setColumns(image.getSize().getWidthPx());
            transFlate.setBitsPerComponent(this.getBitsPerComponent());
        } catch (PDFFilterException e) {
            throw new RuntimeException("FlateFilter configuration error", e);
        }
        BitmapImage alphaMask = new BitmapImage("Mask:" + this.getKey(), image.getSize().getWidthPx(),
                image.getSize().getHeightPx(), baos.toByteArray(), null);
        alphaMask.setPDFFilter(transFlate);
        alphaMask.disallowMultipleFilters();
        alphaMask.setColorSpace(new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_GRAY));
        softMask = doc.addImage(null, alphaMask).makeReference();
    }
}

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

/** {@inheritDoc} */
@Override//from   w w w .  j  a v a 2 s .  c  om
public void setup(PDFDocument doc) {
    RenderedImage ri = getImage().getRenderedImage();

    super.setup(doc);

    //Handle transparency mask if applicable
    ColorModel orgcm = ri.getColorModel();
    if (orgcm.hasAlpha() && orgcm.getTransparency() == ColorModel.TRANSLUCENT) {
        doc.getProfile().verifyTransparencyAllowed(image.getInfo().getOriginalURI());
        //TODO Implement code to combine image with background color if transparency is not
        //allowed (need BufferedImage support for that)

        AlphaRasterImage alphaImage = new AlphaRasterImage("Mask:" + getKey(), ri);
        this.softMask = doc.addImage(null, alphaImage).makeReference();
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java

/**
 * Returns a {@link java.awt.image.BufferedImage} of the COSStream
 * set in the constructor or null if the COSStream could not be encoded.
 *
 * @return {@inheritDoc}/*from ww  w . ja  va 2  s  .  c o m*/
 *
 * @throws IOException {@inheritDoc}
 */
public BufferedImage getRGBImage() throws IOException {
    if (image != null) {
        return image;
    }

    try {
        int width = getWidth();
        int height = getHeight();
        int bpc = getBitsPerComponent();

        byte[] array = getPDStream().getByteArray();
        if (array.length == 0) {
            LOG.error("Something went wrong ... the pixelmap doesn't contain any data.");
            return null;
        }
        // Get the ColorModel right
        PDColorSpace colorspace = getColorSpace();
        if (colorspace == null) {
            LOG.error("getColorSpace() returned NULL.  Predictor = " + getPredictor());
            return null;
        }

        ColorModel cm = null;
        if (colorspace instanceof PDIndexed) {
            PDIndexed csIndexed = (PDIndexed) colorspace;
            // the base color space uses 8 bit per component, as the indexed color values
            // of an indexed color space are always in a range from 0 to 255
            ColorModel baseColorModel = csIndexed.getBaseColorSpace().createColorModel(8);
            // number of possible color values in the target color space
            int numberOfColorValues = 1 << bpc;
            // number of indexed color values
            int highValue = csIndexed.getHighValue();
            // choose the correct size, sometimes there are more indexed values than needed
            // and sometimes there are fewer indexed value than possible
            int size = Math.min(numberOfColorValues - 1, highValue);
            byte[] index = csIndexed.getLookupData();
            boolean hasAlpha = baseColorModel.hasAlpha();
            COSBase maskArray = getMask();
            if (baseColorModel.getTransferType() != DataBuffer.TYPE_BYTE) {
                throw new IOException("Not implemented");
            }
            // the IndexColorModel uses RGB-based color values
            // which leads to 3 color components and a optional alpha channel
            int numberOfComponents = 3 + (hasAlpha ? 1 : 0);
            int buffersize = (size + 1) * numberOfComponents;
            byte[] colorValues = new byte[buffersize];
            byte[] inData = new byte[baseColorModel.getNumComponents()];
            int bufferIndex = 0;
            for (int i = 0; i <= size; i++) {
                System.arraycopy(index, i * inData.length, inData, 0, inData.length);
                // convert the indexed color values to RGB 
                colorValues[bufferIndex] = (byte) baseColorModel.getRed(inData);
                colorValues[bufferIndex + 1] = (byte) baseColorModel.getGreen(inData);
                colorValues[bufferIndex + 2] = (byte) baseColorModel.getBlue(inData);
                if (hasAlpha) {
                    colorValues[bufferIndex + 3] = (byte) baseColorModel.getAlpha(inData);
                }
                bufferIndex += numberOfComponents;
            }
            if (maskArray != null && maskArray instanceof COSArray) {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha,
                        ((COSArray) maskArray).getInt(0));
            } else {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha);
            }
        } else if (colorspace instanceof PDSeparation) {
            PDSeparation csSeparation = (PDSeparation) colorspace;
            int numberOfComponents = csSeparation.getAlternateColorSpace().getNumberOfComponents();
            PDFunction tintTransformFunc = csSeparation.getTintTransform();
            COSArray decode = getDecode();
            // we have to invert the tint-values,
            // if the Decode array exists and consists of (1,0)
            boolean invert = decode != null && decode.getInt(0) == 1;
            // TODO add interpolation for other decode values then 1,0
            int maxValue = (int) Math.pow(2, bpc) - 1;
            // destination array
            byte[] mappedData = new byte[width * height * numberOfComponents];
            int rowLength = width * numberOfComponents;
            float[] input = new float[1];
            for (int i = 0; i < height; i++) {
                int rowOffset = i * rowLength;
                for (int j = 0; j < width; j++) {
                    // scale tint values to a range of 0...1
                    int value = (array[i * width + j] + 256) % 256;
                    if (invert) {
                        input[0] = 1 - (value / maxValue);
                    } else {
                        input[0] = value / maxValue;
                    }
                    float[] mappedColor = tintTransformFunc.eval(input);
                    int columnOffset = j * numberOfComponents;
                    for (int k = 0; k < numberOfComponents; k++) {
                        // redo scaling for every single color value 
                        float mappedValue = mappedColor[k];
                        mappedData[rowOffset + columnOffset + k] = (byte) (mappedValue * maxValue);
                    }
                }
            }
            array = mappedData;
            cm = colorspace.createColorModel(bpc);
        } else if (bpc == 1) {
            byte[] map = null;
            if (colorspace instanceof PDDeviceGray) {
                COSArray decode = getDecode();
                // we have to invert the b/w-values,
                // if the Decode array exists and consists of (1,0)
                if (decode != null && decode.getInt(0) == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else {
                map = new byte[] { (byte) 0x00, (byte) 0xff };
            }
            cm = new IndexColorModel(bpc, map.length, map, map, map, Transparency.OPAQUE);
        } else {
            if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    byte[] map = new byte[] { (byte) 0xff };
                    cm = new IndexColorModel(bpc, 1, map, map, map, Transparency.OPAQUE);
                } else {
                    cm = colorspace.createColorModel(bpc);
                }
            } else {
                cm = colorspace.createColorModel(bpc);
            }
        }

        LOG.debug("ColorModel: " + cm.toString());
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        byte[] bufferData = buffer.getData();

        System.arraycopy(array, 0, bufferData, 0,
                (array.length < bufferData.length ? array.length : bufferData.length));
        image = new BufferedImage(cm, raster, false, null);

        // If there is a 'soft mask' image then we use that as a transparency mask.
        PDXObjectImage smask = getSMaskImage();
        if (smask != null) {
            BufferedImage smaskBI = smask.getRGBImage();

            COSArray decodeArray = smask.getDecode();

            CompositeImage compositeImage = new CompositeImage(image, smaskBI);
            BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);

            return rgbImage;
        } else if (getImageMask()) {
            BufferedImage stencilMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = (Graphics2D) stencilMask.getGraphics();
            if (getStencilColor() != null) {
                graphics.setColor(getStencilColor().getJavaColor());
            } else {
                // this might happen when using ExractImages, see PDFBOX-1145
                LOG.debug("no stencil color for PixelMap found, using Color.BLACK instead.");
                graphics.setColor(Color.BLACK);
            }

            graphics.fillRect(0, 0, width, height);
            // assume default values ([0,1]) for the DecodeArray
            // TODO DecodeArray == [1,0]
            graphics.setComposite(AlphaComposite.DstIn);
            graphics.drawImage(image, null, 0, 0);
            return stencilMask;
        } else {
            // if there is no mask, use the unaltered image.
            return image;
        }
    } catch (Exception exception) {
        LOG.error(exception, exception);
        //A NULL return is caught in pagedrawer.Invoke.process() so don't re-throw.
        //Returning the NULL falls through to Phillip Koch's TODO section.
        return null;
    }
}