Example usage for java.awt.image BufferedImage TYPE_INT_RGB

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

Introduction

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

Prototype

int TYPE_INT_RGB

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

Click Source Link

Document

Represents an image with 8-bit RGB color components packed into integer pixels.

Usage

From source file:org.lmn.fc.common.datatranslators.DataExporter.java

/***********************************************************************************************
 * exportComponent().//w  w w .  j  a  v a2s.c  om
 *
 * @param exportable
 * @param filename
 * @param timestamp
 * @param type
 * @param width
 * @param height
 * @param log
 * @param clock
 *
 * @return boolean
 */

public static boolean exportComponent(final ExportableComponentInterface exportable, final String filename,
        final boolean timestamp, final String type, final int width, final int height, final Vector<Vector> log,
        final ObservatoryClockInterface clock) {
    final String SOURCE = "DataExporter.exportComponent()";
    boolean boolSuccess;

    //        String[] arrayNames = ImageIO.getWriterFormatNames();
    //
    //        for (int i = 0;
    //             i < arrayNames.length;
    //             i++)
    //            {
    //            String arrayName = arrayNames[i];
    //            System.out.println("DataExporter.exportComponent() FORMAT NAME=" + arrayName);
    //            }
    //
    boolSuccess = false;

    if ((exportable != null) && (filename != null) && (!EMPTY_STRING.equals(filename)) && (type != null)
            && (!EMPTY_STRING.equals(type)) && (log != null) && (clock != null)
            && (Arrays.asList(ImageIO.getWriterFormatNames()).contains(type))) {
        try {
            final File file;
            final int intRealWidth;
            final int intRealHeight;

            file = new File(FileUtilities.buildFullFilename(filename, timestamp, type));
            FileUtilities.overwriteFile(file);

            intRealWidth = width;
            intRealHeight = height;

            // Support all current formats
            if ((FileUtilities.png.equalsIgnoreCase(type)) || (FileUtilities.jpg.equalsIgnoreCase(type))
                    || (FileUtilities.gif.equalsIgnoreCase(type))) {
                BufferedImage buffer;
                final Graphics2D graphics2D;

                LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(),
                        "DataExporter.exportComponent() writing [file " + file.getAbsolutePath() + "] [width="
                                + intRealWidth + "] [height=" + intRealHeight + "]");

                buffer = new BufferedImage(intRealWidth, intRealHeight, BufferedImage.TYPE_INT_RGB);

                // Create a graphics context on the buffered image
                graphics2D = buffer.createGraphics();

                // Draw on the image
                graphics2D.clearRect(0, 0, intRealWidth, intRealHeight);
                exportable.paintForExport(graphics2D, intRealWidth, intRealHeight);

                // Export the image
                ImageIO.write(buffer, type, file);
                graphics2D.dispose();
                boolSuccess = true;

                SimpleEventLogUIComponent
                        .logEvent(
                                log, EventStatus.INFO, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT
                                        + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR,
                                SOURCE, clock);
                // Help the GC?
                buffer = null;

                ObservatoryInstrumentHelper.runGarbageCollector();
            } else {
                SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT
                        + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_INVALID_FORMAT + TERMINATOR, SOURCE,
                        clock);
            }
        }

        catch (IllegalArgumentException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT
                            + EXCEPTION_PARAMETER_INVALID + TERMINATOR + SPACE + METADATA_EXCEPTION
                            + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (SecurityException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_ACCESS_DENIED
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (FileNotFoundException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_NOT_FOUND
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (IOException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_SAVE
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }
    } else {
        SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT
                + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_COMPONENT + TERMINATOR, SOURCE, clock);
    }

    return (boolSuccess);
}

From source file:edu.ku.brc.af.ui.forms.validation.ValFormattedTextField.java

/**
 * Creates the various UI Components for the formatter.
 */// ww  w  .  j  a v a 2 s  . c om
protected void createUI() {
    CellConstraints cc = new CellConstraints();

    if (isViewOnly
            || (formatter != null && !formatter.isUserInputNeeded() && fields != null && fields.size() == 1)) {
        viewtextField = new JTextField();
        setControlSize(viewtextField);

        // Remove by rods 12/5/08 this messes thihngs up
        // values don't get inserted correctly, shouldn't be needed anyway

        //JFormattedDoc document = new JFormattedDoc(viewtextField, formatter, formatter.getFields().get(0));
        //viewtextField.setDocument(document);
        //document.addDocumentListener(this);
        //documents.add(document);

        ViewFactory.changeTextFieldUIForDisplay(viewtextField, false);
        PanelBuilder builder = new PanelBuilder(new FormLayout("1px,f:p:g,1px", "1px,f:p:g,1px"), this);
        builder.add(viewtextField, cc.xy(2, 2));
        bgColor = viewtextField.getBackground();

    } else {
        JTextField txt = new JTextField();

        Font txtFont = txt.getFont();

        Font font = new Font("Courier", Font.PLAIN, txtFont.getSize());

        BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setFont(font);
        FontMetrics fm = g.getFontMetrics(font);
        g.dispose();

        Insets ins = txt.getBorder().getBorderInsets(txt);
        int baseWidth = ins.left + ins.right;

        bgColor = txt.getBackground();

        StringBuilder sb = new StringBuilder("1px");
        for (UIFieldFormatterField f : fields) {
            sb.append(",");
            if (f.getType() == FieldType.separator || f.getType() == FieldType.constant) {
                sb.append('p');
            } else {
                sb.append(((fm.getMaxAdvance() * f.getSize()) + baseWidth) + "px");
            }
        }
        sb.append(",1px");
        PanelBuilder builder = new PanelBuilder(new FormLayout(sb.toString(), "1px,P:G,1px"), this);

        comps = new JComponent[fields.size()];
        int inx = 0;
        for (UIFieldFormatterField f : fields) {
            JComponent comp = null;
            JComponent tfToAdd = null;

            if (f.getType() == FieldType.separator || f.getType() == FieldType.constant) {
                comp = createLabel(f.getValue());
                if (f.getType() == FieldType.constant) {
                    comp.setBackground(Color.WHITE);
                    comp.setOpaque(true);
                }
                tfToAdd = comp;

            } else {
                JTextField tf = new BGTextField(f.getSize(), isViewOnly ? "" : f.getValue());
                tfToAdd = tf;

                if (inx == 0) {
                    tf.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent e) {
                            checkForPaste(e);
                        }
                    });
                }

                JFormattedDoc document = new JFormattedDoc(tf, formatter, f);
                tf.setDocument(document);
                document.addDocumentListener(new DocumentAdaptor() {
                    @Override
                    protected void changed(DocumentEvent e) {
                        isChanged = true;
                        if (!shouldIgnoreNotifyDoc) {
                            String fldStr = getText();
                            int len = StringUtils.isNotEmpty(fldStr) ? fldStr.length() : 0;
                            if (formatter != null && len > 0 && formatter.isLengthOK(len)) {
                                setState(formatter.isValid(fldStr) ? UIValidatable.ErrorType.Valid
                                        : UIValidatable.ErrorType.Error);
                                repaint();
                            }

                            //validateState();
                            if (changeListener != null) {
                                changeListener.stateChanged(new ChangeEvent(this));
                            }

                            if (documentListeners != null) {
                                for (DocumentListener dl : documentListeners) {
                                    dl.changedUpdate(null);
                                }
                            }
                        }
                        currCachedValue = null;
                    }
                });
                documents.add(document);

                addFocusAdapter(tf);

                comp = tf;
                comp.setFont(font);

                if (f.isIncrementer()) {
                    editTF = tf;
                    cardLayout = new CardLayout();
                    cardPanel = new JPanel(cardLayout);
                    cardPanel.add("edit", tf);

                    viewTF = new BGTextField(f.getSize(), isViewOnly ? "" : f.getValue());
                    viewTF.setDocument(document);
                    cardPanel.add("view", viewTF);

                    cardLayout.show(cardPanel, "view");
                    comp = cardPanel;
                    tfToAdd = cardPanel;
                }
            }

            setControlSize(tfToAdd);
            builder.add(comp, cc.xy(inx + 2, 2));
            comps[inx] = tfToAdd;
            inx++;
        }
    }
}

From source file:com.poscoict.license.service.CertificateService.java

public boolean extractPagesAsImage(String sourceFile, String fileName, int resolution, String password) {

    boolean result = false;
    //? ?/*  www.j  a  v a2s .co  m*/
    String imageFormat = Consts.IMG_FORMAT;
    int pdfPageCn = 0;
    PDDocument pdfDoc = null;

    try {
        //PDF?  ?
        pdfDoc = PDDocument.load(sourceFile);

        //PDF? ??  ?
        pdfPageCn = pdfDoc.getNumberOfPages();
    } catch (IOException ioe) {
        logger.error("PDF ?  : ", ioe);
    }

    PDFImageWriter imageWriter = new PDFImageWriter();
    try {
        result = imageWriter.writeImage(pdfDoc, imageFormat, password, 1, //?  ?
                pdfPageCn, //?  ?
                //? ? ?  ?+? "?1.gif" ?
                Consts.IMG_PATH + fileName, BufferedImage.TYPE_INT_RGB, resolution //?   300 
        );
        pdfDoc.close();
    } catch (IOException ioe) {
        logger.error("PDF ?  : ", ioe);
    }
    return result;
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

public static void saveImageResultsToPng(String prefix, TopDocs hits, String queryImage, IndexReader ir)
        throws IOException {
    LinkedList<BufferedImage> results = new LinkedList<BufferedImage>();
    int width = 0;
    for (int i = 0; i < Math.min(hits.scoreDocs.length, 10); i++) {
        // hits.score(i)
        // hits.doc(i).get("descriptorImageIdentifier")
        BufferedImage tmp = ImageIO
                .read(new FileInputStream(ir.document(hits.scoreDocs[i].doc).get("descriptorImageIdentifier")));
        if (tmp.getHeight() > 200) {
            double factor = 200d / ((double) tmp.getHeight());
            tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200);
        }/*from   ww w.j a va 2 s  . c  o  m*/
        width += tmp.getWidth() + 5;
        results.add(tmp);
    }
    BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) result.getGraphics();
    g2.setColor(Color.black);
    g2.clearRect(0, 0, result.getWidth(), result.getHeight());
    g2.setColor(Color.green);
    g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12"));
    int offset = 0;
    int count = 0;
    for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) {
        BufferedImage next = iterator.next();
        g2.drawImage(next, offset, 20, null);
        g2.drawString(hits.scoreDocs[count].score + "", offset + 5, 12);
        offset += next.getWidth() + 5;
        count++;
    }
    ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png"));
}

From source file:edu.ku.brc.ui.GraphicsUtils.java

/**
 * Convenience method that returns a scaled instance of the
 * provided {@code BufferedImage}./*from w  ww .  ja  v  a 2 s.  c om*/
 * 
 * Code stolen from http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
 *
 * @param img the original image to be scaled
 * @param targetWidth the desired width of the scaled instance,
 *    in pixels
 * @param targetHeight the desired height of the scaled instance,
 *    in pixels
 * @param hint one of the rendering hints that corresponds to
 *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
 *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
 *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
 *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
 * @param higherQuality if true, this method will use a multi-step
 *    scaling technique that provides higher quality than the usual
 *    one-step technique (only useful in down-scaling cases, where
 *    {@code targetWidth} or {@code targetHeight} is
 *    smaller than the original dimensions, and generally only when
 *    the {@code BILINEAR} hint is specified)
 * @return a scaled version of the original {@code BufferedImage}
 */
public static BufferedImage getScaledInstance(final BufferedImage img, final int targetWidth,
        final int targetHeight, final boolean higherQuality) {
    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage temp = img;

    BufferedImage result = new BufferedImage(targetWidth, targetHeight, type);
    Graphics2D g2 = result.createGraphics();
    if (higherQuality) {
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    }
    g2.drawImage(temp, 0, 0, targetWidth, targetHeight, null);
    g2.dispose();

    return result;
}

From source file:displayStructureAsPDFTable.java

public void drawStructure(IAtomContainer mol, int cnt) {

    // do aromaticity detection
    try {/*from w  w  w .j  av  a 2  s.  co  m*/
        CDKHueckelAromaticityDetector.detectAromaticity(mol);
    } catch (CDKException cdke) {
        cdke.printStackTrace();
    }
    mol = addHeteroHydrogens(mol);
    r2dm = new Renderer2DModel();
    renderer = new Renderer2D(r2dm);
    Dimension screenSize = new Dimension(this.width, this.height);
    setPreferredSize(screenSize);
    r2dm.setBackgroundDimension(screenSize); // make sure it is synched with the JPanel size
    setBackground(r2dm.getBackColor());

    try {
        StructureDiagramGenerator sdg = new StructureDiagramGenerator();
        sdg.setMolecule((IMolecule) mol);
        sdg.generateCoordinates();
        this.mol = sdg.getMolecule();

        r2dm.setDrawNumbers(false);
        r2dm.setUseAntiAliasing(true);
        r2dm.setColorAtomsByType(doColor);
        r2dm.setShowAromaticity(true);
        r2dm.setShowAromaticityInCDKStyle(false);
        r2dm.setShowReactionBoxes(false);
        r2dm.setKekuleStructure(false);
        r2dm.setShowExplicitHydrogens(withH);
        r2dm.setShowImplicitHydrogens(true);
        GeometryTools.translateAllPositive(this.mol);
        GeometryTools.scaleMolecule(this.mol, getPreferredSize(), this.scale);
        GeometryTools.center(this.mol, getPreferredSize());
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    this.frame.getContentPane().add(this);
    this.frame.pack();

    String filename;
    if (cnt < 10)
        filename = this.odir + "/img00" + cnt + this.suffix;
    else if (cnt < 100)
        filename = this.odir + "/img0" + cnt + this.suffix;
    else
        filename = this.odir + "/img" + cnt + this.suffix;

    if (oformat.equalsIgnoreCase("png") || oformat.equalsIgnoreCase("jpeg")) {
        BufferedImage img;
        try {
            img = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_RGB);
            //                img = (BufferedImage) createImage(this.getSize().width, this.getSize().height);
            Graphics2D snapGraphics = (Graphics2D) img.getGraphics();
            this.paint(snapGraphics);
            File graphicsFile = new File(filename);
            ImageIO.write(img, oformat, graphicsFile);
        } catch (NullPointerException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    } else if (oformat.equalsIgnoreCase("pdf")) {
        File file = new File(filename);
        Rectangle pageSize = new Rectangle(this.getSize().width, this.getSize().height);
        Document document = new Document(pageSize);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            Image awtImage = createImage(this.getSize().width, this.getSize().height);
            Graphics snapGraphics = awtImage.getGraphics();
            paint(snapGraphics);

            com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(awtImage, null);
            pdfImage.setAbsolutePosition(0, 0);
            cb.addImage(pdfImage);

        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
        document.close();
    } else if (oformat.equalsIgnoreCase("svg")) {
        /*
             try {
        SVGWriter cow = new SVGWriter(new FileWriter(filename));
        if (cow != null) {
            cow.writeAtomContainer(mol);
            cow.close();
        }
             } catch (IOException ioe) {
        ioe.printStackTrace();
             } catch (CDKException cdke) {
        cdke.printStackTrace();
             }
        */
    }
}

From source file:com.neophob.sematrix.core.glue.Collector.java

private void saveImage(Visual v, String filename, int[] data) {
    try {//w w w . java  2s. c o  m
        int w = v.getGenerator1().getInternalBufferXSize();
        int h = v.getGenerator1().getInternalBufferYSize();
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        bi.setRGB(0, 0, w, h, data, 0, w);
        File outputfile = new File(filename);
        ImageIO.write(bi, "png", outputfile);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Failed to save screenshot " + filename, e);
    }
}

From source file:com.piaoyou.util.ImageUtil.java

public static BufferedImage getProductionImage(String productVersion, String productRealeaseDate) {

    String str = productVersion + " on " + productRealeaseDate;
    int IMAGE_WIDTH = 250;
    int IMAGE_HEIGHT = 30;

    BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bufferedImage.createGraphics();
    g.setBackground(Color.blue);//from ww  w  .  j a  v a  2  s  .  c o m
    g.setColor(Color.white);
    g.draw3DRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, false);
    FontMetrics fontMetrics = g.getFontMetrics();
    int strWidth = fontMetrics.stringWidth(str);
    int strHeight = fontMetrics.getAscent() + fontMetrics.getDescent();
    g.drawString(str, (IMAGE_WIDTH - strWidth) / 2,
            IMAGE_HEIGHT - ((IMAGE_HEIGHT - strHeight) / 2) - fontMetrics.getDescent());
    g.dispose(); // free resource
    return bufferedImage;
}

From source file:PlatformTest.java

private Shape3D createLabel(String szText, float x, float y, float z) {
    BufferedImage bufferedImage = new BufferedImage(25, 14, BufferedImage.TYPE_INT_RGB);
    Graphics g = bufferedImage.getGraphics();
    g.setColor(Color.white);//from  w ww .j a  v a  2s.  c  om
    g.drawString(szText, 2, 12);

    ImageComponent2D imageComponent2D = new ImageComponent2D(ImageComponent2D.FORMAT_RGB, bufferedImage);

    // create the Raster for the image
    javax.media.j3d.Raster renderRaster = new javax.media.j3d.Raster(new Point3f(x, y, z),
            javax.media.j3d.Raster.RASTER_COLOR, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(),
            imageComponent2D, null);

    return new Shape3D(renderRaster);
}

From source file:org.jfree.experimental.swt.SWTUtils.java

/**
 * Converts an AWT image to SWT.//from  w  w w.j a v  a2 s  . com
 *
 * @param image  the image (<code>null</code> not permitted).
 *
 * @return Image data.
 */
public static ImageData convertAWTImageToSWT(Image image) {
    ParamChecks.nullNotPermitted(image, "image");
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    if (w == -1 || h == -1) {
        return null;
    }
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return convertToSWT(bi);
}