Example usage for java.awt.image BufferedImage getAlphaRaster

List of usage examples for java.awt.image BufferedImage getAlphaRaster

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getAlphaRaster.

Prototype

public WritableRaster getAlphaRaster() 

Source Link

Document

Returns a WritableRaster representing the alpha channel for BufferedImage objects with ColorModel objects that support a separate spatial alpha channel, such as ComponentColorModel and DirectColorModel .

Usage

From source file:de.fhg.igd.swingrcp.SwingRCPUtilities.java

/**
 * Applies the given transparency mask to a buffered image. Always creates a
 * new buffered image containing an alpha channel. Copies the old image into
 * the new one and then sets the alpha pixels according to the given mask.
 * /*from   ww  w. j a  v  a  2s .  c  o m*/
 * @param img the old image
 * @param mask the alpha mask
 * @return the new image with alpha channel applied
 * @throws IllegalArgumentException if the image's size does not match the
 *             mask's size
 */
public static BufferedImage applyTransparencyMask(BufferedImage img, ImageData mask) {
    if (mask.width != img.getWidth() || mask.height != img.getHeight()) {
        throw new IllegalArgumentException("Image size does not match the mask size");
    }

    // copy image and also convert to RGBA
    BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics g = result.getGraphics();
    g.drawImage(img, 0, 0, null);

    WritableRaster alphaRaster = result.getAlphaRaster();
    int alpha0[] = new int[] { 0 };
    int alpha255[] = new int[] { 255 };
    for (int y = 0; y < img.getHeight(); y++) {
        for (int x = 0; x < img.getWidth(); x++) {
            alphaRaster.setPixel(x, y, mask.getPixel(x, y) == 0 ? alpha0 : alpha255);
        }
    }

    return result;
}

From source file:oct.util.Util.java

/**
 * Convert the supplied image to a 2D pixel array such that an (X,Y) value
 * indexes as array[x][y].// w  w w.j  av  a2s  . c  o m
 *
 * Credit for this method goes to Stack Overflow user Mota and their post
 * here:
 * http://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image
 * for this implementation.
 *
 * This method will return the red, green and blue values directly for each
 * pixel, and if there is an alpha channel it will add the alpha value.
 * Using this method is harder in terms of calculating indices, but is much
 * faster than using getRGB to build this same array.
 *
 * @param image
 * @return
 */
public static int[][] convertTo2D(BufferedImage image) {

    final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    final int width = image.getWidth();
    final int height = image.getHeight();
    final boolean hasAlphaChannel = image.getAlphaRaster() != null;

    int[][] result = new int[width][height];
    if (hasAlphaChannel) {
        final int pixelLength = 4;
        for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
            argb += ((int) pixels[pixel + 1] & 0xff); // blue
            argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
            result[col][row] = argb;
            col++;
            if (col == width) {
                col = 0;
                row++;
            }
        }
    } else {
        final int pixelLength = 3;
        for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += -16777216; // 255 alpha
            argb += ((int) pixels[pixel] & 0xff); // blue
            argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
            result[col][row] = argb;
            col++;
            if (col == width) {
                col = 0;
                row++;
            }
        }
    }

    return result;
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

public static BufferedImage scale(BufferedImage bi, int width, int height) {
    BufferedImage bi2;//  w w w. j a v  a  2s  . c o m
    int scaleWidth = bi.getWidth(null);
    int scaleHeight = bi.getHeight(null);
    double scaleX = (double) width / scaleWidth;
    double scaleY = (double) height / scaleHeight;
    double scale = Math.min(scaleX, scaleY);
    scaleWidth = (int) ((double) scaleWidth * scale);
    scaleHeight = (int) ((double) scaleHeight * scale);
    Image scaledImage;
    if (HEADLESS) {
        // create a new buffered image, don't rely on a local graphics system (headless mode)
        final int type;
        if (bi.getType() != BufferedImage.TYPE_CUSTOM) {
            type = bi.getType();
        } else if (bi.getAlphaRaster() != null) {
            // alpha channel available
            type = BufferedImage.TYPE_INT_ARGB;
        } else {
            type = BufferedImage.TYPE_INT_RGB;
        }
        bi2 = new BufferedImage(scaleWidth, scaleHeight, type);
    } else {
        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration();
        bi2 = gc.createCompatibleImage(scaleWidth, scaleHeight, bi.getTransparency());
    }
    Graphics2D g = bi2.createGraphics();
    if (scale < 0.3 && Math.max(scaleWidth, scaleHeight) < 500) {
        scaledImage = bi.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
        new ImageIcon(scaledImage).getImage();
        g.drawImage(scaledImage, 0, 0, scaleWidth, scaleHeight, null);
    } else {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawImage(bi, 0, 0, scaleWidth, scaleHeight, null);
    }
    g.dispose();
    return bi2;
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java

private void readTableResources(PDFBoxTable table, PDDocument template) throws PdfAsException, IOException {

    float[] colsSizes = table.getColsRelativeWith();
    int max_cols = table.getColCount();
    float padding = table.getPadding();
    if (colsSizes == null) {
        colsSizes = new float[max_cols];
        // set the column ratio for all columns to 1
        for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
            colsSizes[cols_idx] = 1;//from   w w w.  j  a  va2  s  .  c  om
        }
    }

    logger.debug("TOTAL Width: " + table.getWidth());

    float total = 0;

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        total += colsSizes[cols_idx];
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        colsSizes[cols_idx] = (colsSizes[cols_idx] / total) * table.getWidth();
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        logger.debug("Col: " + cols_idx + " : " + colsSizes[cols_idx]);
    }

    /*
     * if(!addedFonts.contains(table.getFont().getFont(null))) { PDFont font
     * = table.getFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     *
     * if(!addedFonts.contains(table.getValueFont().getFont(null))) { PDFont
     * font = table.getValueFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     */

    for (int i = 0; i < table.getRowCount(); i++) {
        ArrayList<Entry> row = table.getRow(i);
        for (int j = 0; j < row.size(); j++) {
            Entry cell = (Entry) row.get(j);
            if (cell.getType() == Entry.TYPE_IMAGE) {
                String img_value = (String) cell.getValue();
                String img_ref = createHashedId(img_value);
                if (!images.containsKey(img_ref)) {
                    BufferedImage img = ImageUtils.getImage(img_value, settings);

                    float width = colsSizes[j];
                    float height = table.getRowHeights()[i] + padding * 2;

                    float iwidth = (int) Math.floor((double) width);
                    iwidth -= 2 * padding;

                    float iheight = (int) Math.floor((double) height);
                    iheight -= 2 * padding;

                    float origWidth = (float) img.getWidth();
                    float origHeight = (float) img.getHeight();

                    if (table.style != null) {
                        if (table.style.getImageScaleToFit() != null) {
                            iwidth = table.style.getImageScaleToFit().getWidth();
                            iheight = table.style.getImageScaleToFit().getHeight();
                        }
                    }

                    float wfactor = iwidth / origWidth;
                    float hfactor = iheight / origHeight;
                    float scaleFactor = wfactor;
                    if (hfactor < wfactor) {
                        scaleFactor = hfactor;
                    }

                    iwidth = (float) Math.floor((double) (scaleFactor * origWidth));
                    iheight = (float) Math.floor((double) (scaleFactor * origHeight));

                    logger.debug("Scaling image to: " + iwidth + " x " + iheight);

                    if (this.designer.properties.getSignatureProfileSettings().isPDFA()) {
                        img = ImageUtils.removeAlphaChannel(img);
                    } else {
                        if (img.getAlphaRaster() == null && img.getColorModel().hasAlpha()) {
                            img = ImageUtils.removeAlphaChannel(img);
                        }
                    }
                    // img = ImageUtils.convertRGBAToIndexed(img);

                    PDXObjectImage pdImage = new PDPixelMap(template, img);

                    ImageObject image = new ImageObject(pdImage, iwidth, iheight);
                    images.put(img_ref, image);
                    innerFormResources.addXObject(pdImage, "Im");
                }
            } else if (cell.getType() == Entry.TYPE_TABLE) {
                PDFBoxTable tbl_value = (PDFBoxTable) cell.getValue();
                readTableResources(tbl_value, template);
            }
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java

private void readTableResources(PDFBoxTable table, PDDocument template) throws PdfAsException, IOException {

    float[] colsSizes = table.getColsRelativeWith();
    int max_cols = table.getColCount();
    float padding = table.getPadding();
    if (colsSizes == null) {
        colsSizes = new float[max_cols];
        // set the column ratio for all columns to 1
        for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
            colsSizes[cols_idx] = 1;//from ww  w .  ja  v a2  s .c  o  m
        }
    }

    logger.debug("TOTAL Width: " + table.getWidth());

    float total = 0;

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        total += colsSizes[cols_idx];
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        colsSizes[cols_idx] = (colsSizes[cols_idx] / total) * table.getWidth();
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        logger.debug("Col: " + cols_idx + " : " + colsSizes[cols_idx]);
    }

    /*
     * if(!addedFonts.contains(table.getFont().getFont(null))) { PDFont font
     * = table.getFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     * 
     * if(!addedFonts.contains(table.getValueFont().getFont(null))) { PDFont
     * font = table.getValueFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     */

    for (int i = 0; i < table.getRowCount(); i++) {
        ArrayList<Entry> row = table.getRow(i);
        for (int j = 0; j < row.size(); j++) {
            Entry cell = (Entry) row.get(j);
            if (cell.getType() == Entry.TYPE_IMAGE) {
                String img_value = (String) cell.getValue();
                String img_ref = createHashedId(img_value);
                if (!images.containsKey(img_ref)) {
                    BufferedImage img = ImageUtils.getImage(img_value, settings);

                    float width = colsSizes[j];
                    float height = table.getRowHeights()[i] + padding * 2;

                    float iwidth = (int) Math.floor((double) width);
                    iwidth -= 2 * padding;

                    float iheight = (int) Math.floor((double) height);
                    iheight -= 2 * padding;

                    float origWidth = (float) img.getWidth();
                    float origHeight = (float) img.getHeight();

                    if (table.style != null) {
                        if (table.style.getImageScaleToFit() != null) {
                            iwidth = table.style.getImageScaleToFit().getWidth();
                            iheight = table.style.getImageScaleToFit().getHeight();
                        }
                    }

                    float wfactor = iwidth / origWidth;
                    float hfactor = iheight / origHeight;
                    float scaleFactor = wfactor;
                    if (hfactor < wfactor) {
                        scaleFactor = hfactor;
                    }

                    iwidth = (float) Math.floor((double) (scaleFactor * origWidth));
                    iheight = (float) Math.floor((double) (scaleFactor * origHeight));

                    logger.debug("Scaling image to: " + iwidth + " x " + iheight);

                    if (this.designer.properties.getSignatureProfileSettings().isPDFA()) {
                        img = ImageUtils.removeAlphaChannel(img);
                    } else {
                        if (img.getAlphaRaster() == null && img.getColorModel().hasAlpha()) {
                            img = ImageUtils.removeAlphaChannel(img);
                        }
                    }
                    // img = ImageUtils.convertRGBAToIndexed(img);

                    PDImageXObject pdImage = LosslessFactory.createFromImage(template, img);

                    ImageObject image = new ImageObject(pdImage, iwidth, iheight);
                    images.put(img_ref, image);
                    innerFormResources.add(pdImage, "Im");
                }
            } else if (cell.getType() == Entry.TYPE_TABLE) {
                PDFBoxTable tbl_value = (PDFBoxTable) cell.getValue();
                readTableResources(tbl_value, template);
            }
        }
    }
}

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

private void createImageStream(PDDocument doc, BufferedImage bi) throws IOException {
    BufferedImage alphaImage = null;
    BufferedImage rgbImage = null;
    int width = bi.getWidth();
    int height = bi.getHeight();
    if (bi.getColorModel().hasAlpha()) {
        // extract the alpha information
        WritableRaster alphaRaster = bi.getAlphaRaster();
        ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false,
                Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
        alphaImage = new BufferedImage(cm, alphaRaster, false, null);
        // create a RGB image without alpha
        rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = rgbImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.drawImage(bi, 0, 0, null);/* ww w .  j  a  va2s . c o m*/
    } else {
        rgbImage = bi;
    }
    java.io.OutputStream os = null;
    try {
        int numberOfComponents = rgbImage.getColorModel().getNumComponents();
        if (numberOfComponents == 3) {
            setColorSpace(PDDeviceRGB.INSTANCE);
        } else {
            if (numberOfComponents == 1) {
                setColorSpace(new PDDeviceGray());
            } else {
                throw new IllegalStateException();
            }
        }
        byte[] outData = new byte[width * height * numberOfComponents];
        rgbImage.getData().getDataElements(0, 0, width, height, outData);
        // add FlateDecode compression
        getPDStream().addCompression();
        os = getCOSStream().createUnfilteredStream();
        os.write(outData);

        COSDictionary dic = getCOSStream();
        dic.setItem(COSName.FILTER, COSName.FLATE_DECODE);
        dic.setItem(COSName.SUBTYPE, COSName.IMAGE);
        dic.setItem(COSName.TYPE, COSName.XOBJECT);
        if (alphaImage != null) {
            PDPixelMap smask = new PDPixelMap(doc, alphaImage);
            dic.setItem(COSName.SMASK, smask);
        }
        setBitsPerComponent(8);
        setHeight(height);
        setWidth(width);
    } finally {
        os.close();
    }
}

From source file:org.polymap.rhei.batik.engine.svg.Svg2Png.java

private static void setAlpha(BufferedImage finalThresholdImage, int x, int y, int rgb) {
    int bands = finalThresholdImage.getAlphaRaster().getSampleModel().getNumBands();
    int alpha = (rgb >> 24) & 0xFF;
    for (int b = 0; b < bands; b++) {
        finalThresholdImage.getAlphaRaster().setSample(x, y, b, alpha);
    }//from w  w w .ja v a2  s . c om
}

From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java

private static BufferedImage getAlphaImage(BufferedImage image) {
    if (!image.getColorModel().hasAlpha()) {
        return null;
    }//from w w  w. j  a  v a  2 s.  c  o  m
    if (image.getTransparency() == Transparency.BITMASK) {
        throw new UnsupportedOperationException(
                "BITMASK Transparency JPEG compression is not" + " useful, use LosslessImageFactory instead");
    }
    WritableRaster alphaRaster = image.getAlphaRaster();
    if (alphaRaster == null) {
        // happens sometimes (PDFBOX-2654) despite colormodel claiming to have alpha
        return null;
    }
    BufferedImage alphaImage = new BufferedImage(image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_BYTE_GRAY);
    alphaImage.setData(alphaRaster);
    return alphaImage;
}