Example usage for java.awt.image BufferedImage getGraphics

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

Introduction

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

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:algorithm.QRCodeWatermarking.java

/**
 * This algorithm writes a QR-code image on a carrier image.
 * /*from   w  ww  .  jav a  2 s  . c  o m*/
 * @param qrCodeFile
 * @param carrierFile
 * @param imageFormat
 * @return image file with qr code on top of carrier
 * @throws IOException
 */
private File writeQRCodeOnImage(File qrCodeFile, File carrierFile, String imageFormat) throws IOException {
    BufferedImage barcode = ImageIO.read(qrCodeFile);
    BufferedImage carrier = ImageIO.read(carrierFile);
    if (barcode.getWidth() > carrier.getWidth() || barcode.getHeight() > carrier.getHeight()) {
        displayMessage(
                "The QR-code is to big to add it to the carrier image. Try again with a lower QR-code size!");
        qrCodeFile.delete();
        return null;
    }
    Graphics graphics = carrier.getGraphics();
    graphics.drawImage(barcode, getXPosition(), getYPosition(), null);
    String outputFileName = FilenameUtils.removeExtension(getOutputFileName(carrierFile)) + "." + imageFormat;
    File outputFile = new File(outputFileName);
    ImageIO.write(carrier, imageFormat, outputFile);
    qrCodeFile.delete();
    return outputFile;
}

From source file:org.jtrfp.trcl.core.ResourceManager.java

private BufferedImage[] getSpecialRAWImage(String name, Color[] palette, int upscalePowerOfTwo)
        throws IllegalAccessException, FileLoadException, IOException {
    RAWFile dat = getRAW(name);/*from www  . jav a2  s.c o  m*/
    dat.setPalette(palette);
    BufferedImage[] segs = dat.asSegments(upscalePowerOfTwo);
    for (BufferedImage seg : segs) {
        Graphics g = seg.getGraphics();
        BufferedImage scaled = new BufferedImage(seg.getColorModel(), seg.copyData(null),
                seg.isAlphaPremultiplied(), null);
        g.drawImage(
                scaled.getScaledInstance(seg.getWidth() - 2, seg.getHeight() - 2, Image.SCALE_AREA_AVERAGING),
                1, 1, seg.getWidth() - 2, seg.getHeight() - 2, null);
        g.dispose();
    }
    return segs;
}

From source file:org.pentaho.di.core.gui.SwingDirectGC.java

private void drawImage(SwingUniversalImage img, int locationX, int locationY, int imageSize) {
    if (isDrawingPixelatedImages() && img.isBitmap()) {
        BufferedImage bi = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, imageSize, imageSize);
        g2.drawImage(img.getAsBitmapForSize(imageSize, imageSize), 0, 0, observer);
        g2.dispose();/*from  w  w  w.  j a v a2  s .  com*/

        for (int x = 0; x < bi.getWidth(observer); x++) {
            for (int y = 0; y < bi.getHeight(observer); y++) {
                int rgb = bi.getRGB(x, y);
                gc.setColor(new Color(rgb));
                gc.setStroke(new BasicStroke(1.0f));
                gc.drawLine(locationX + xOffset + x, locationY + yOffset + y, locationX + xOffset + x,
                        locationY + yOffset + y);
            }
        }
    } else {
        gc.setBackground(Color.white);
        gc.clearRect(locationX, locationY, imageSize, imageSize);
        img.drawToGraphics(gc, locationX, locationY, imageSize, imageSize);
    }
}

From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java

private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
    JTableHeader tableHeaderComp = applianceTable.getTableHeader();
    int totalWidth = tableHeaderComp.getWidth() + applianceTable.getWidth();
    int totalHeight = tableHeaderComp.getHeight() + applianceTable.getHeight();
    BufferedImage tableImage = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2D = (Graphics2D) tableImage.getGraphics();
    tableHeaderComp.paint(g2D);/*from   w  w  w .jav a  2 s  .c  o m*/
    g2D.translate(0, tableHeaderComp.getHeight());
    applianceTable.paint(g2D);
    String name = fileNameTxt.getText();
    try {
        if (!name.equals("")) {
            ImageIO.write(tableImage, "png",
                    new File("C:\\Users\\Reshmi\\Documents\\NetBeansProjects\\FinalProject\\Saved Files\\"
                            + name + ".png"));
            JOptionPane.showMessageDialog(null, "image saved as " + name + ".png", "Saved",
                    JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "enter name to be saved", "No image name",
                    JOptionPane.ERROR_MESSAGE);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:org.openpnp.machine.reference.camera.TableScannerCamera.java

private BufferedImage renderFrame() {
    if (buffer == null) {
        return null;
    }/*from   w  w  w. j  a va2s .  c o  m*/
    if (head == null) {
        return null;
    }
    synchronized (buffer) {
        // Grab these values only once since the head may continue to move
        // while we are rendering.
        Location l = getLocation().convertToUnits(LengthUnit.Millimeters);
        double headX = l.getX();
        double headY = l.getY();
        if (lastX != headX || lastY != headY) {
            // Find the closest tile to the head's current position.
            Tile closestTile = getClosestTile(headX, headY);
            logger.debug("closestTile {}", closestTile);

            // If it has changed we need to render the entire buffer.
            if (closestTile != lastCenterTile) {
                lastCenterTile = closestTile;
                renderBuffer();
            }

            // And remember the last position we rendered.
            lastX = headX;
            lastY = headY;
        }

        /*
         * Get the distance from the center tile to the point we need to render.
         * TODO: Had to invert these from experimentation. Need to figure out
         * why and maybe make it configurable. I was too tired to figure it out.
         */
        double unitsDeltaX = headX - lastCenterTile.getX();
        double unitsDeltaY = lastCenterTile.getY() - headY;

        /*
         * Get the distance in pixels from the center tile to the head.
         */
        Location unitsPerPixel = getUnitsPerPixel().convertToUnits(LengthUnit.Millimeters);
        double deltaX = unitsDeltaX / unitsPerPixel.getX();
        double deltaY = unitsDeltaY / unitsPerPixel.getY();

        /*
         * Get the position within the buffer of the top left pixel of the
         * frame sized chunk we'll grab.
         */
        double bufferStartX = (buffer.getWidth() / 2) - (width / 2);
        double bufferStartY = (buffer.getHeight() / 2) - (height / 2);

        BufferedImage frame = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        /*
         * Render the frame sized chunk from the center of the buffer offset
         * by the distance of the head from the center tile to the frame
         * buffer for final output.
         */
        Graphics2D g = (Graphics2D) frame.getGraphics();
        g.drawImage(buffer, 0, 0, frame.getWidth(), frame.getHeight(), (int) (bufferStartX + deltaX),
                (int) (bufferStartY + deltaY), (int) (bufferStartX + frame.getWidth() + deltaX),
                (int) (bufferStartY + frame.getHeight() + deltaY), null);
        g.dispose();

        return frame;
    }
}

From source file:au.com.gaiaresources.bdrs.controller.theme.ThemeControllerTest.java

private byte[] createTestImage() throws IOException {
    BufferedImage img = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = (Graphics2D) img.getGraphics();
    Random rand = new Random();
    g2.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
    g2.fillRect(0, 0, img.getWidth(), img.getHeight());

    ByteArrayOutputStream baos = new ByteArrayOutputStream(img.getWidth() * img.getHeight());
    ImageIO.write(img, "png", baos);
    baos.flush();/*w w  w  .  j  a  v a 2  s . com*/
    byte[] rawBytes = baos.toByteArray();
    baos.close();

    return rawBytes;
}

From source file:com.ikon.module.common.CommonWorkflowModule.java

/**
 * Get Process Definition Image/*from  www. j a v  a 2  s.  c  om*/
 */
public static byte[] getProcessDefinitionImage(long processDefinitionId, String node) throws WorkflowException {
    log.debug("getProcessDefinitionImage({}, {})", new Object[] { processDefinitionId, node });
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    byte[] image = null;

    try {
        GraphSession graphSession = jbpmContext.getGraphSession();
        org.jbpm.graph.def.ProcessDefinition pd = graphSession.getProcessDefinition(processDefinitionId);
        FileDefinition fileDef = pd.getFileDefinition();

        WorkflowUtils.DiagramInfo dInfo = WorkflowUtils.getDiagramInfo(fileDef.getInputStream("gpd.xml"));
        WorkflowUtils.DiagramNodeInfo dNodeInfo = dInfo.getNodeMap().get(node);
        BufferedImage img = ImageIO.read(fileDef.getInputStream("processimage.jpg"));

        // Obtain all nodes Y and X
        List<Integer> ordenadas = new ArrayList<Integer>();
        List<Integer> abcisas = new ArrayList<Integer>();

        for (WorkflowUtils.DiagramNodeInfo nodeInfo : dInfo.getNodeMap().values()) {
            ordenadas.add(nodeInfo.getY());
            abcisas.add(nodeInfo.getX());
        }

        // Calculate minimal Y
        Collections.sort(ordenadas);
        int fixOrd = ordenadas.get(0) < 0 ? ordenadas.get(0) : 0;

        // Calculate minimal X
        Collections.sort(abcisas);
        int fixAbs = abcisas.get(0) < 0 ? abcisas.get(0) : 0;

        if (dNodeInfo != null) {
            // Select node
            log.debug("DiagramNodeInfo: {}", dNodeInfo);
            Graphics g = img.getGraphics();
            Graphics2D g2d = (Graphics2D) g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25F));
            g2d.setColor(Color.blue);
            g2d.fillRect(dNodeInfo.getX() - fixAbs, dNodeInfo.getY() - fixOrd, dNodeInfo.getWidth(),
                    dNodeInfo.getHeight());
            g.dispose();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        image = baos.toByteArray();
        baos.flush();
        baos.close();
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } catch (IOException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        jbpmContext.close();
    }

    log.debug("getProcessDefinitionImage: {}", image);
    return image;
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

public String generateScale(Dataset dataset, boolean clustColumn) {
    int W = 0;//from  w  w  w .  j  a v a 2  s.c om
    if (clustColumn) {
        W = (Math.min((upperTree.getWidth() + 21), 250));
    } else {
        W = (Math.min((dataset.getColumnIds().length * 12 + 21), 250));
    }
    BufferedImage nfo = new BufferedImage(W, 50, BufferedImage.TYPE_INT_ARGB);
    Graphics g = nfo.getGraphics();
    g.setFont(getTableFont(9));
    drawScale(g, new Point(0, 0), W, 30);
    return this.generateEncodedImg(nfo);

}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

public InteractiveColumnsResults generateInteractiveColumn(Dataset dataset, int[] selection) {

    interactiveColumnImg = null;//from  w w w . j av a2 s . co  m
    interactiveColumnImg = new BufferedImage(squareW + squareW, (sideTree.getHeight()),
            BufferedImage.TYPE_INT_ARGB);

    BufferedImage navgBackGroungImg = new BufferedImage(400, 10, BufferedImage.TYPE_INT_ARGB);
    Graphics navGr = navgBackGroungImg.getGraphics();
    int navUnit = (dataset.getDataLength() / 200) + 1;

    Graphics g = interactiveColumnImg.getGraphics();
    g.setFont(getTableFont(5));
    drawTable(g, new Point(0, 0), dataset, selection, navGr, navUnit);
    navgBackGroungImg = rotateImage(navgBackGroungImg, 180);
    navgStringImg = this.generateEncodedImg(navgBackGroungImg);
    InteractiveColumnsResults results = new InteractiveColumnsResults();
    results.setInteractiveColumn(splitImage(interactiveColumnImg));
    results.setNavgUrl(navgStringImg);
    return results;
}

From source file:org.jtrfp.trcl.core.ResourceManager.java

/**
 * Returns RAW image as an R8-G8-B8 buffer with a side-width which is the square root of the total number of pixels
 * @param name/* w  w w  . j  av a2  s  .com*/
 * @param palette
 * @param proc
 * @return
 * @throws IOException
 * @throws FileLoadException
 * @throws IllegalAccessException
 * @throws NotSquareException 
 * @since Oct 26, 2012
 */
public BufferedImage getRAWImage(String name, Color[] palette) throws IOException, FileLoadException,
        IllegalAccessException, NotSquareException, NonPowerOfTwoException {
    final RAWFile dat = getRAW(name);
    final byte[] raw = dat.getRawBytes();
    if (raw.length != dat.getSideLength() * dat.getSideLength())
        throw new NotSquareException(name);
    if ((dat.getSideLength() & (dat.getSideLength() - 1)) != 0)
        throw new NonPowerOfTwoException(name);
    final BufferedImage stamper = new BufferedImage(dat.getSideLength(), dat.getSideLength(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics stG = stamper.getGraphics();
    for (int i = 0; i < raw.length; i++) {
        Color c = palette[(int) raw[i] & 0xFF];
        stG.setColor(c);
        stG.fillRect(i % dat.getSideLength(), i / dat.getSideLength(), 1, 1);
    }
    stG.dispose();
    Graphics g = stamper.getGraphics();
    //The following code stamps the filename into the texture for debugging purposes
    if (tr.isStampingTextures()) {
        g.setFont(new Font(g.getFont().getName(), g.getFont().getStyle(), 9));
        g.drawString(name, 1, 16);
    }

    g.dispose();
    return stamper;
}