Example usage for java.awt.image BufferedImage TYPE_4BYTE_ABGR

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

Introduction

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

Prototype

int TYPE_4BYTE_ABGR

To view the source code for java.awt.image BufferedImage TYPE_4BYTE_ABGR.

Click Source Link

Document

Represents an image with 8-bit RGBA color components with the colors Blue, Green, and Red stored in 3 bytes and 1 byte of alpha.

Usage

From source file:com.occamlab.te.parsers.ImageParser.java

private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger)
        throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }/*from  ww  w  .  jav  a2  s.c  o m*/
    String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08
                                                              // PwD
    BufferedImage image = reader.read(frame);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(formatName); // 2011-09-08 PwD was
                                                 // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try { // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) { // 2011-08-24
                                                                     // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch (transparency) {
                case Transparency.OPAQUE: {
                    transparencyName = "Opaque";
                    break;
                }
                case Transparency.BITMASK: {
                    transparencyName = "Bitmask";
                    break;
                }
                case Transparency.TRANSLUCENT: {
                    transparencyName = "Translucent";
                    break;
                }
                default: {
                    transparencyName = "Unknown";
                }
                }
                node.setTextContent(transparencyName);

            } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08
                                                                   // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}

From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.java

private void createSpacer(int width, int height) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    byte[] imageBytes = bufferedImageToByteArray(image);
    this.kmzWriter.addNonKMLFile(imageBytes, SPACER);
}

From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.java

private ScreenOverlayType createHistogram(String transportMode, Map<Id, Double> evacuationTimes)
        throws IOException {

    /*//from  w w w .j  ava  2s .co  m
     * Remove NaN entries from the List
     */
    List<Double> listWithoutNaN = new ArrayList<Double>();
    for (Double d : evacuationTimes.values())
        if (!d.isNaN())
            listWithoutNaN.add(d);

    /*
     * If trip with significant to high evacuation times should be cut off
     */
    if (limitMaxEvacuationTime) {
        double cutOffValue = meanEvacuationTime + standardDeviation * evacuationTimeCutOffFactor;
        ListIterator<Double> iter = listWithoutNaN.listIterator();
        while (iter.hasNext()) {
            double value = iter.next();
            if (value > cutOffValue)
                iter.remove();
        }
    }

    double[] array = new double[listWithoutNaN.size()];
    int i = 0;
    for (double d : listWithoutNaN)
        array[i++] = d;

    JFreeChart chart = createHistogramChart(transportMode, array);
    BufferedImage chartImage = chart.createBufferedImage(OVERALLHISTOGRAMWIDTH, OVERALLHISTOGRAMHEIGHT);
    BufferedImage image = new BufferedImage(OVERALLHISTOGRAMWIDTH, OVERALLHISTOGRAMHEIGHT,
            BufferedImage.TYPE_4BYTE_ABGR);

    // clone image and set alpha value
    for (int x = 0; x < OVERALLHISTOGRAMWIDTH; x++) {
        for (int y = 0; y < OVERALLHISTOGRAMHEIGHT; y++) {
            int rgb = chartImage.getRGB(x, y);
            Color c = new Color(rgb);
            int r = c.getRed();
            int b = c.getBlue();
            int g = c.getGreen();
            int argb = 225 << 24 | r << 16 | g << 8 | b; // 225 as transparency value
            image.setRGB(x, y, argb);
        }
    }

    byte[] imageBytes = bufferedImageToByteArray(image);
    this.kmzWriter.addNonKMLFile(imageBytes, transportMode + OVERALLHISTROGRAM);

    ScreenOverlayType overlay = kmlObjectFactory.createScreenOverlayType();
    LinkType icon = kmlObjectFactory.createLinkType();
    icon.setHref(transportMode + OVERALLHISTROGRAM);
    overlay.setIcon(icon);
    overlay.setName("Histogram " + transportMode);
    // place the image top right
    Vec2Type overlayXY = kmlObjectFactory.createVec2Type();
    overlayXY.setX(0.0);
    overlayXY.setY(1.0);
    overlayXY.setXunits(UnitsEnumType.FRACTION);
    overlayXY.setYunits(UnitsEnumType.FRACTION);
    overlay.setOverlayXY(overlayXY);
    Vec2Type screenXY = kmlObjectFactory.createVec2Type();
    screenXY.setX(0.02);
    screenXY.setY(0.98);
    screenXY.setXunits(UnitsEnumType.FRACTION);
    screenXY.setYunits(UnitsEnumType.FRACTION);
    overlay.setScreenXY(screenXY);
    return overlay;
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java

private static File copyEmptyTiffFile(File original, String newFileName, int width, int height) {

    BufferedImage orjImg;//from   w  w  w  . j av  a2s  .c om
    try {
        orjImg = ImageIO.read(original);

        if (width != orjImg.getWidth() || height != orjImg.getHeight()) {
            log.warning("Width and height not right. Old width:" + width + " updated:" + orjImg.getWidth()
                    + " old height:" + height + " updated:" + orjImg.getHeight());
            width = orjImg.getWidth();
            height = orjImg.getHeight();

        }
    } catch (IOException e1) {
        log.warning("failed to read original tiff;", e1);
    }

    File newFile = null;
    try {
        long len = original.length();
        long rgbLen = width * height * 4;
        long greyLen = width * height;
        long bwLen = width * height / 8;
        int imagetype = BufferedImage.TYPE_BYTE_BINARY;
        if (len > greyLen)
            imagetype = BufferedImage.TYPE_BYTE_GRAY;
        if (len > rgbLen)
            imagetype = BufferedImage.TYPE_4BYTE_ABGR;
        newFile = File.createTempFile(newFileName, ".tif");
        //log.info("Creating empty tiff:" + newFile.getAbsolutePath() + " width:" + width + " height:" + height);
        BufferedImage bufferedImage = new BufferedImage(width, height, imagetype);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bufferedImage.setRGB(x, y, Color.black.getRGB());
            }
        }
        ImageIO.write(bufferedImage, "tif", newFile);
    } catch (IOException e) {
        log.warning("Error creating empty TIFF  file" + newFile.getAbsolutePath());
    }
    return newFile;
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {/*from  ww  w.j  a v  a 2s .c o m*/
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDRectangle.A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, pdfObject.getStatus().getSettings());
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, pdfObject.getStatus().getSettings());
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);

        PDPage firstPage = visualDoc.getDocumentCatalog().getPages().get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        int targetPageNumber = 0;//TODO: is this always the case
        PDFRenderer pdfRenderer = new PDFRenderer(visualDoc);
        BufferedImage outputImage = pdfRenderer.renderImageWithDPI(targetPageNumber, targetRes, ImageType.ARGB);

        //BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:TextureByReference.java

static void printType(BufferedImage bImage) {
    int type = bImage.getType();
    if (type == BufferedImage.TYPE_4BYTE_ABGR) {
        System.out.println("TYPE_4BYTE_ABGR");
    } else if (type == BufferedImage.TYPE_INT_ARGB) {
        System.out.println("TYPE_INT_ARGB");
    } else if (type == BufferedImage.TYPE_3BYTE_BGR) {
        System.out.println("TYPE_3BYTE_BGR");
    } else if (type == BufferedImage.TYPE_CUSTOM) {
        System.out.println("TYPE_CUSTOM");
    } else//from  w w w  .ja  v  a 2s . c  om
        System.out.println(type);
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {//from  w  w  w .  j  av a 2s  .  c  o m
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDPage.PAGE_SIZE_A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, false, false);
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, false, false);
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);
        List<PDPage> pages = new ArrayList<PDPage>();
        visualDoc.getDocumentCatalog().getPages().getAllKids(pages);

        PDPage firstPage = pages.get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:lu.fisch.unimozer.Diagram.java

public void exportPNG() {
    selectClass(null);/*from   www.  java2s  .co m*/

    JFileChooser dlgSave = new JFileChooser("Export diagram as PNG ...");
    // propose name
    String uniName = directoryName.substring(directoryName.lastIndexOf('/') + 1).trim();
    dlgSave.setSelectedFile(new File(uniName));

    dlgSave.addChoosableFileFilter(new PNGFilter());
    int result = dlgSave.showSaveDialog(frame);
    if (result == JFileChooser.APPROVE_OPTION) {
        String filename = dlgSave.getSelectedFile().getAbsoluteFile().toString();
        if (!filename.substring(filename.length() - 4, filename.length()).toLowerCase().equals(".png")) {
            filename += ".png";
        }

        File file = new File(filename);
        BufferedImage bi = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        paint(bi.getGraphics());
        try {
            ImageIO.write(bi, "png", file);
        } catch (Exception e) {
            JOptionPane.showOptionDialog(frame, "Error while saving the image!", "Error", JOptionPane.OK_OPTION,
                    JOptionPane.ERROR_MESSAGE, null, null, null);
        }
    }
}

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

private BufferedImage getFallbackBufferedImage(ImageReader reader, int pageIndex, ImageReadParam param)
        throws IOException {
    //Work-around found at: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903
    //There are some additional ideas there if someone wants to go further.

    // Try reading a Raster (no color conversion).
    Raster raster = reader.readRaster(pageIndex, param);

    // Arbitrarily select a BufferedImage type.
    int imageType;
    switch (raster.getNumBands()) {
    case 1://  www .j  ava 2  s.  c om
        imageType = BufferedImage.TYPE_BYTE_GRAY;
        break;
    case 3:
        imageType = BufferedImage.TYPE_3BYTE_BGR;
        break;
    case 4:
        imageType = BufferedImage.TYPE_4BYTE_ABGR;
        break;
    default:
        throw new UnsupportedOperationException();
    }

    // Create a BufferedImage.
    BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(), imageType);

    // Set the image data.
    bi.getRaster().setRect(raster);
    return bi;
}

From source file:org.codice.alliance.imaging.chip.transformer.CatalogOutputAdapter.java

private void setImageDataFields(BufferedImage chip, ImageSegment chipImageSegment) throws IOException {

    int[] componentSizes = chip.getColorModel().getComponentSize();
    int pixelSize = chip.getColorModel().getPixelSize();

    switch (chip.getType()) {
    case BufferedImage.TYPE_BYTE_GRAY:
    case BufferedImage.TYPE_USHORT_GRAY:
    case BufferedImage.TYPE_BYTE_BINARY:
        setMonochrome(chipImageSegment, componentSizes[0], pixelSize);
        break;/*from ww w .  ja  v  a  2 s.co  m*/
    case BufferedImage.TYPE_3BYTE_BGR:
    case BufferedImage.TYPE_INT_BGR:
        setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR,
                componentSizes[0], pixelSize / 3, new String[] { "B", "G", "R" });
        break;
    case BufferedImage.TYPE_4BYTE_ABGR:
    case BufferedImage.TYPE_4BYTE_ABGR_PRE:
        setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR,
                componentSizes[0], pixelSize / 4, new String[] { "B", "G", "R" });
        break;
    case BufferedImage.TYPE_INT_ARGB_PRE:
    case BufferedImage.TYPE_INT_ARGB:
        setARGB(chipImageSegment, componentSizes[0], pixelSize);
        break;
    case BufferedImage.TYPE_INT_RGB:
    case BufferedImage.TYPE_USHORT_555_RGB:
        setRGB(chipImageSegment, componentSizes[0], pixelSize);
        break;
    case BufferedImage.TYPE_CUSTOM:
        if (componentSizes.length == 1) {
            setMonochrome(chipImageSegment, componentSizes[0], pixelSize);
        } else if (componentSizes.length == 3) {
            setRGB(chipImageSegment, componentSizes[0], pixelSize);
        } else if (componentSizes.length == 4) {
            setARGB(chipImageSegment, componentSizes[0], pixelSize);
        } else {
            throw new IOException(
                    "unsupported color model for image type CUSTOM, only monochrome and 32-bit argb are supported");
        }
        break;
    case BufferedImage.TYPE_BYTE_INDEXED:
        setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBLUT,
                componentSizes[0], pixelSize, new String[] { "LU" });
        break;
    case BufferedImage.TYPE_USHORT_565_RGB:
        // don't know how to handle this one, since the bitsPerPixelPerBand is not consistent
        break;
    default:
        throw new IOException("unsupported image data type: type=" + chip.getType());
    }
}