Example usage for java.awt.image ColorModel getTransparency

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

Introduction

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

Prototype

public int getTransparency() 

Source Link

Document

Returns the transparency.

Usage

From source file:net.rptools.lib.image.ImageUtil.java

public static int pickBestTransparency(BufferedImage image) {
    // See if we can short circuit
    ColorModel colorModel = image.getColorModel();
    if (colorModel.getTransparency() == Transparency.OPAQUE) {
        return Transparency.OPAQUE;
    }//ww w  .j  a  v  a 2 s .co  m
    // Get the pixels
    int width = image.getWidth();
    int height = image.getHeight();

    // Look for specific pixels
    boolean foundTransparent = false;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            // Get the next pixel
            int pixel = image.getRGB(x, y);
            int alpha = (pixel >> 24) & 0xff;

            // Is there translucency or just pure transparency ?
            if (alpha > 0 && alpha < 255) {
                return Transparency.TRANSLUCENT;
            }
            if (alpha == 0 && !foundTransparent) {
                foundTransparent = true;
            }
        }
    }
    return foundTransparent ? Transparency.BITMASK : Transparency.OPAQUE;
}

From source file:com.t3.image.ImageUtil.java

public static int pickBestTransparency(BufferedImage image) {

    // See if we can short circuit
    ColorModel colorModel = image.getColorModel();
    if (colorModel.getTransparency() == Transparency.OPAQUE) {
        return Transparency.OPAQUE;
    }// w  ww .  ja  v  a2s. c o m

    // Get the pixels
    int width = image.getWidth();
    int height = image.getHeight();

    // Look for specific pixels
    boolean foundTransparent = false;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            // Get the next pixel
            int pixel = image.getRGB(x, y);
            int alpha = (pixel >> 24) & 0xff;

            // Is there translucency or just pure transparency ?
            if (alpha > 0 && alpha < 255) {
                return Transparency.TRANSLUCENT;
            }

            if (alpha == 0 && !foundTransparent) {
                foundTransparent = true;
            }
        }
    }

    return foundTransparent ? Transparency.BITMASK : Transparency.OPAQUE;
}

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

public static BufferedImage createBufferedImage(BufferedImage image, int columns, int rows) {
    ColorModel colormodel = image.getColorModel();
    BufferedImage newImage;//from  w  w  w . j  a  v  a 2s. c om
    if (colormodel instanceof IndexColorModel) {
        if (colormodel.getTransparency() != 1)
            newImage = new BufferedImage(columns, rows, 2);
        else
            newImage = new BufferedImage(columns, rows, 1);
    } else {
        newImage = new BufferedImage(colormodel,
                image.getRaster().createCompatibleWritableRaster(columns, rows),
                colormodel.isAlphaPremultiplied(), null);
    }
    return newImage;
}

From source file:GraphicsUtil.java

/**
 * Extracts an alpha raster from a RenderedImage. The method tries to avoid copying data
 * unnecessarily by checking if the RenderedImage is a BufferedImage which offers suitable
 * direct methods./*from   w  w w.  j  av a 2  s .c  om*/
 * @param image the image
 * @return the alpha raster
 */
public static Raster getAlphaRaster(RenderedImage image) {
    ColorModel cm = image.getColorModel();
    if (!cm.hasAlpha() || cm.getTransparency() != ColorModel.TRANSLUCENT) {
        throw new IllegalStateException("Image doesn't have an alpha channel");
    }
    Raster alpha;
    if (image instanceof BufferedImage) {
        //Optimization possible with BufferedImage (No copying)
        alpha = ((BufferedImage) image).getAlphaRaster();
    } else {
        WritableRaster wraster = GraphicsUtil.makeRasterWritable(image.getData());
        alpha = image.getColorModel().getAlphaRaster(wraster);
    }
    return alpha;
}

From source file:omr.jai.TestImage3.java

public static void print(PlanarImage pi) {
        // Show the image dimensions and coordinates.
        System.out.print("Image Dimensions: ");
        System.out.print(pi.getWidth() + "x" + pi.getHeight() + " pixels");

        // Remember getMaxX and getMaxY return the coordinate of the next point!
        System.out.println(" (from " + pi.getMinX() + "," + pi.getMinY() + " to " + (pi.getMaxX() - 1) + ","
                + (pi.getMaxY() - 1) + ")");
        if ((pi.getNumXTiles() != 1) || (pi.getNumYTiles() != 1)) { // Is it tiled?
            // Tiles number, dimensions and coordinates.
            System.out.print("Tiles: ");
            System.out.print(pi.getTileWidth() + "x" + pi.getTileHeight() + " pixels" + " (" + pi.getNumXTiles()
                    + "x" + pi.getNumYTiles() + " tiles)");
            System.out.print(" (from " + pi.getMinTileX() + "," + pi.getMinTileY() + " to " + pi.getMaxTileX() + ","
                    + pi.getMaxTileY() + ")");
            System.out.println(" offset: " + pi.getTileGridXOffset() + "," + pi.getTileGridXOffset());
        }/*from w  ww  .j  av a  2s .  c om*/

        // Display info about the SampleModel of the image.
        SampleModel sm = pi.getSampleModel();
        System.out.println("Number of bands: " + sm.getNumBands());
        System.out.print("Data type: ");
        switch (sm.getDataType()) {
        case DataBuffer.TYPE_BYTE:
            System.out.println("byte");
            break;
        case DataBuffer.TYPE_SHORT:
            System.out.println("short");
            break;
        case DataBuffer.TYPE_USHORT:
            System.out.println("ushort");
            break;
        case DataBuffer.TYPE_INT:
            System.out.println("int");
            break;
        case DataBuffer.TYPE_FLOAT:
            System.out.println("float");
            break;
        case DataBuffer.TYPE_DOUBLE:
            System.out.println("double");
            break;
        case DataBuffer.TYPE_UNDEFINED:
            System.out.println("undefined");
            break;
        }

        // Display info about the ColorModel of the image.
        ColorModel cm = pi.getColorModel();
        if (cm != null) {
            System.out.println("Number of color components: " + cm.getNumComponents());
            System.out.println("Bits per pixel: " + cm.getPixelSize());
            System.out.print("Image Transparency: ");
            switch (cm.getTransparency()) {
            case Transparency.OPAQUE:
                System.out.println("opaque");
                break;
            case Transparency.BITMASK:
                System.out.println("bitmask");
                break;
            case Transparency.TRANSLUCENT:
                System.out.println("translucent");
                break;
            }
        } else
            System.out.println("No color model.");
    }

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

/**
 *
 *///from   w  w w.j  a  va  2 s  .  co  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

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 av  a  2s  .  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.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 {//from  w  ww . j  av  a 2s . 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/*w  w w  .  j a v a  2s .co  m*/
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.fop.render.pdf.ImageRenderedAdapter.java

/** {@inheritDoc} */
@Override//  www  .j  av  a  2s.c om
public boolean isTransparent() {
    ColorModel cm = getEffectiveColorModel();
    if (cm instanceof IndexColorModel) {
        if (cm.getTransparency() == IndexColorModel.TRANSLUCENT) {
            return true;
        }
    }
    return (getImage().getTransparentColor() != null);
}