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:test.unit.be.fedict.eid.applet.service.VcardGeneratorTest.java

@Test
public void identityWithAddressAndPhotoVcard() throws Exception {
    // setup/*from   ww w  .  j  a va 2 s .c om*/
    Identity identity = new Identity();
    identity.name = "Test Name";
    identity.firstName = "Test First name";
    identity.dateOfBirth = new GregorianCalendar();
    identity.gender = Gender.MALE;

    Address address = new Address();
    address.streetAndNumber = "Test Street 1A";
    address.zip = "1234";
    address.municipality = "Test Municipality";

    BufferedImage image = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    graphics.setRenderingHints(renderingHints);
    graphics.setColor(Color.WHITE);
    graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
    graphics.setFont(new Font("Dialog", Font.BOLD, 20));
    graphics.setColor(Color.BLACK);
    graphics.drawString("Test Photo", 0, 200 / 2);
    graphics.dispose();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", baos);
    byte[] photo = baos.toByteArray();

    EIdData eIdData = new EIdData();
    eIdData.identity = identity;
    eIdData.address = address;
    eIdData.photo = photo;

    // operate
    byte[] document = this.testedInstance.generateVcard(eIdData);

    // verify
    assertNotNull(document);
    assertTrue(document.length > 0);

    toTmpFile(document);
}

From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java

/**
 * ??????????/*from  w ww. j a v  a  2s.  co m*/
 * 
 * @param url
 * @return
 * @throws Exception
 */
BufferedImage getFittingImage(String url) throws Exception {
    // ??
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = buildDefaultHttpMessage(new HttpGet(url));
    httpget.setHeader("Referer", "http://www.bijint.com/jp/");
    HttpResponse response = httpclient.execute(httpget);

    BufferedImage image = ImageIO.read(response.getEntity().getContent());
    httpclient.getConnectionManager().shutdown();

    int width = image.getWidth() / 10 * 4;
    int height = image.getHeight() / 10 * 4;
    BufferedImage resizedImage = null;
    resizedImage = new BufferedImage(width, height, image.getType());
    resizedImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 0,
            0, width, height, null);
    return resizedImage;
}

From source file:org.eclipse.wb.internal.swing.model.property.editor.beans.PropertyEditorWrapper.java

private Image paintValue(GC gc, int width, int height) throws Exception {
    // create AWT graphics
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = (Graphics2D) image.getGraphics();
    // prepare color's
    Color background = gc.getBackground();
    Color foreground = gc.getForeground();
    // fill graphics
    graphics2D.setColor(SwingUtils.getAWTColor(background));
    graphics2D.fillRect(0, 0, width, height);
    // set color//from  ww w . j  av  a 2s  . c om
    graphics2D.setBackground(SwingUtils.getAWTColor(background));
    graphics2D.setColor(SwingUtils.getAWTColor(foreground));
    // set font
    FontData[] fontData = gc.getFont().getFontData();
    String name = fontData.length > 0 ? fontData[0].getName() : "Arial";
    graphics2D.setFont(new java.awt.Font(name, java.awt.Font.PLAIN, graphics2D.getFont().getSize() - 1));
    // paint image
    m_propertyEditor.paintValue(graphics2D, new java.awt.Rectangle(0, 0, width, height));
    // conversion
    try {
        return SwingImageUtils.convertImage_AWT_to_SWT(image);
    } finally {
        image.flush();
        graphics2D.dispose();
    }
}

From source file:com.mycompany.controllers.ClubController.java

private byte[] LogoConvertion(byte[] bytes) {
    int width = 200;
    int height = 200;
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    try {// w w  w. ja v a  2 s. co m
        BufferedImage img = ImageIO.read(in);
        if (height == 0) {
            height = (width * img.getHeight()) / img.getWidth();
        }
        if (width == 0) {
            width = (height * img.getWidth()) / img.getHeight();
        }
        Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        ImageIO.write(imageBuff, "jpg", buffer);

        bytes = buffer.toByteArray();
    } catch (IOException e) {
        log.error("File convertion error");
    }
    return bytes;
}

From source file:com.ace.erp.controller.sys.company.OrganizationController.java

@RequestMapping(value = "/company/uploadLogo", method = RequestMethod.POST)
@ResponseBody//from  w  w  w .  ja  v  a2  s  .  com
public Response uploadLogo(@CurrentUser User user, String srcImageFile, int x, int y, int destWidth,
        int destHeight, int srcShowWidth, int srcShowHeight, HttpServletRequest request) {
    try {
        String path = request.getSession().getServletContext().getRealPath("/");
        String contextPath = request.getContextPath();
        Image img;
        ImageFilter cropFilter;
        //String srcFileName = FilenameUtils.getName(srcImageFile);
        String srcFileName = StringUtils.isNotBlank(contextPath) ? srcImageFile.replaceFirst(contextPath, "")
                : srcImageFile;
        // ???
        File srcFile = new File(path + "/" + srcFileName);

        BufferedImage bi = ImageIO.read(srcFile);
        //??????????
        int srcWidth = bi.getWidth(); // ?
        int srcHeight = bi.getHeight(); // ?
        if (srcShowWidth == 0)
            srcShowWidth = srcWidth;
        if (srcShowHeight == 0)
            srcShowHeight = srcHeight;

        if (srcShowWidth >= destWidth && srcShowHeight >= destHeight) {
            //???
            Image image = bi.getScaledInstance(srcShowWidth, srcShowHeight, Image.SCALE_DEFAULT);

            cropFilter = new CropImageFilter(x, y, destWidth, destHeight);

            img = Toolkit.getDefaultToolkit()
                    .createImage(new FilteredImageSource(image.getSource(), cropFilter));
            BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, null); // ??
            g.dispose();

            String ext = FilenameUtils.getExtension(srcImageFile);

            //path += HEADER_PIC;
            //User loginUser = SystemUtil.getLoginUser(request.getSession());
            //String fileName = user.getOrganizationList().get(0).getId()+"";
            File destImageFile = new File(path + "/" + System.currentTimeMillis() + ".jpg");
            // 
            ImageIO.write(tag, ext, destImageFile);

            //loginUser.setPicPath(SystemConst.SYSTEM_CONTEXT_PATH_VALUE + HEADER_PIC + "/" + fileName);
            //userService.update(loginUser);
            // 
            srcFile.delete();
            return new Response(new ResponseHeader(200, 20));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:trendgraph.XYLineChart_AWT.java

public XYLineChart_AWT(int yearStart, int yearEnd, String[] creditUnionName, String columnName)
        throws SQLException {
    super("Graph");
    super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    this.yearStart = yearStart;
    this.yearEnd = yearEnd;
    this.creditUnionName = creditUnionName;
    this.columnName = columnName;
    saveGraphButton = new JButton("Save Graph");
    saveGraphButton.setBorderPainted(false);
    saveGraphButton.setFocusPainted(false);

    JFreeChart xylineChart = ChartFactory.createXYLineChart("CU Report", "Year (YYYY)", //X-axis
            columnName, //Y-axis (replace with columnName
            createDataset(), PlotOrientation.VERTICAL, true, true, false);

    ChartPanel chartPanel = new ChartPanel(xylineChart);
    chartPanel.setPreferredSize(new java.awt.Dimension(1000, 800)); //(x, y)
    final XYPlot plot = xylineChart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();

    renderer.setSeriesPaint(0, Color.RED); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(0, new BasicStroke(3.0f)); //Font size

    renderer.setSeriesPaint(1, Color.BLUE); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(1, new BasicStroke(3.0f)); //Font size

    renderer.setSeriesPaint(2, Color.GREEN); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(2, new BasicStroke(3.0f)); //Font size

    renderer.setSeriesPaint(3, Color.yellow); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(3, new BasicStroke(3.0f)); //Font size

    plot.setRenderer(renderer);//from   w  w w. java2s.c  om
    chartPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));
    chartPanel.add(saveGraphButton);
    setContentPane(chartPanel);
    pack();
    RefineryUtilities.centerFrameOnScreen(this);
    setVisible(true);

    saveGraphButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Rectangle rect = chartPanel.getBounds();
            FileChooser chooser = new FileChooser();

            //get chosen path and save the variable
            String path = chooser.getPath();
            path = path.replace("\\", "/");

            String format = "png";
            String fileName = path + "." + format;
            BufferedImage captureImage = new BufferedImage(rect.width, rect.height,
                    BufferedImage.TYPE_INT_ARGB);
            chartPanel.paint(captureImage.getGraphics());

            File file = new File(fileName);

            try {
                ImageIO.write(captureImage, format, file);

                //write data to file
            } catch (IOException ex) {
                Logger.getLogger(XYLineChart_AWT.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}

From source file:org.apache.hadoop.chukwa.hicc.ImageSlicer.java

public BufferedImage tile(BufferedImage image, int level, XYData quadrant, XYData size, boolean efficient)
        throws Exception {
    double scale = Math.pow(2, level);
    if (efficient) {
        /* efficient: crop out the area of interest first, then scale and copy it */
        XYData inverSize = new XYData((int) (image.getWidth(null) / (size.getX() * scale)),
                (int) (image.getHeight(null) / (size.getY() * scale)));
        XYData topLeft = new XYData(quadrant.getX() * size.getX() * inverSize.getX(),
                quadrant.getY() * size.getY() * inverSize.getY());
        XYData newSize = new XYData((size.getX() * inverSize.getX()), (size.getY() * inverSize.getY()));
        if (inverSize.getX() < 1.0 || inverSize.getY() < 1.0) {
            throw new Exception("Requested zoom level (" + level + ") is too high.");
        }/*from www  .  j  a va 2 s.c o  m*/
        image = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(), newSize.getY());
        BufferedImage zoomed = new BufferedImage(size.getX(), size.getY(), BufferedImage.TYPE_INT_RGB);
        zoomed.getGraphics().drawImage(image, 0, 0, size.getX(), size.getY(), null);
        if (level > maxLevel) {
            maxLevel = level;
        }
        return zoomed;
    } else {
        /* inefficient: copy the whole image, scale it and then crop out the area of interest */
        XYData newSize = new XYData((int) (size.getX() * scale), (int) (size.getY() * scale));
        XYData topLeft = new XYData(quadrant.getX() * size.getX(), quadrant.getY() * size.getY());
        if (newSize.getX() > image.getWidth(null) || newSize.getY() > image.getHeight(null)) {
            throw new Exception("Requested zoom level (" + level + ") is too high.");
        }
        AffineTransform tx = new AffineTransform();
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        tx.scale(scale, scale);
        image = op.filter(image, null);
        BufferedImage zoomed = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(),
                newSize.getY());
        if (level > maxLevel) {
            maxLevel = level;
        }
        return zoomed;
    }
}

From source file:org.b3log.symphony.service.AvatarQueryService.java

/**
 * Creates a avatar image with the specified hash string and size.
 *
 * <p>//from  w  w w. j a v a 2 s  .c o m
 * Refers to: https://github.com/superhj1987/awesome-identicon
 * </p>
 *
 * @param hash the specified hash string
 * @param size the specified size
 * @return buffered image
 */
public BufferedImage createAvatar(final String hash, final int size) {
    final boolean[][] array = new boolean[6][5];

    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 5; j++) {
            array[i][j] = false;
        }
    }

    for (int i = 0; i < hash.length(); i += 2) {
        final int s = i / 2;

        final boolean v = Math.random() > 0.5;
        if (s % 3 == 0) {
            array[s / 3][0] = v;
            array[s / 3][4] = v;
        } else if (s % 3 == 1) {
            array[s / 3][1] = v;
            array[s / 3][3] = v;
        } else {
            array[s / 3][2] = v;
        }
    }

    final int ratio = Math.round(size / 5);

    final BufferedImage ret = new BufferedImage(ratio * 5, ratio * 5, BufferedImage.TYPE_3BYTE_BGR);
    final Graphics graphics = ret.getGraphics();

    graphics.setColor(new Color(Integer.parseInt(String.valueOf(hash.charAt(0)), 16) * 16,
            Integer.parseInt(String.valueOf(hash.charAt(1)), 16) * 16,
            Integer.parseInt(String.valueOf(hash.charAt(2)), 16) * 16));
    graphics.fillRect(0, 0, ret.getWidth(), ret.getHeight());

    graphics.setColor(new Color(Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 1)), 16) * 16,
            Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 2)), 16) * 16,
            Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 3)), 16) * 16));
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 5; j++) {
            if (array[i][j]) {
                graphics.fillRect(j * ratio, i * ratio, ratio, ratio);
            }
        }
    }

    return ret;
}

From source file:org.apache.hadoop.chukwa.hicc.ImageSlicer.java

public BufferedImage subdivide(BufferedImage image, int level, XYData quadrant, XYData size, String prefix) {
    if (image.getWidth() <= size.getX() * Math.pow(2, level)) {
        try {/*from  w  w  w  .j a  va  2s.c o  m*/
            BufferedImage outputImage = tile(image, level, quadrant, size, true);
            write(outputImage, level, quadrant, prefix);
            return outputImage;
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
    }

    BufferedImage zoomed = new BufferedImage(size.getX() * 2, size.getY() * 2, BufferedImage.TYPE_INT_RGB);
    Graphics g = zoomed.getGraphics();
    XYData newQuadrant = new XYData(quadrant.getX() * 2 + 0, quadrant.getY() * 2 + 0);
    g.drawImage(subdivide(image, level + 1, newQuadrant, size, prefix), 0, 0, null);
    newQuadrant = new XYData(quadrant.getX() * 2 + 0, quadrant.getY() * 2 + 1);
    g.drawImage(subdivide(image, level + 1, newQuadrant, size, prefix), 0, size.getY(), null);
    newQuadrant = new XYData(quadrant.getX() * 2 + 1, quadrant.getY() * 2 + 0);
    g.drawImage(subdivide(image, level + 1, newQuadrant, size, prefix), size.getX(), 0, null);
    newQuadrant = new XYData(quadrant.getX() * 2 + 1, quadrant.getY() * 2 + 1);
    g.drawImage(subdivide(image, level + 1, newQuadrant, size, prefix), size.getX(), size.getY(), null);
    BufferedImage outputImage = new BufferedImage(size.getX(), size.getY(), BufferedImage.TYPE_INT_RGB);
    outputImage.getGraphics().drawImage(zoomed, 0, 0, size.getX(), size.getY(), null);
    write(outputImage, level, quadrant, prefix);
    return outputImage;
}

From source file:de.uni_siegen.wineme.come_in.thumbnailer.thumbnailers.PDFBoxThumbnailer.java

private BufferedImage convertToImage(final PDPage page, final int imageType, final int thumbWidth,
        final int thumbHeight)/*     */ throws IOException
/*     */ {//from w ww  .  j  a  v  a2s .  c  om
    /* 707 */ final PDRectangle mBox = page.findMediaBox();
    /* 708 */ final float widthPt = mBox.getWidth();
    /* 709 */ final float heightPt = mBox.getHeight();
    /* 711 */ final int widthPx = thumbWidth;
    // Math.round(widthPt * scaling);
    /* 712 */ final int heightPx = thumbHeight;
    // Math.round(heightPt * scaling);
    /* 710 */ final double scaling = Math.min((double) thumbWidth / widthPt, (double) thumbHeight / heightPt);
    // resolution / 72.0F;
    /*     */
    /* 714 */ final Dimension pageDimension = new Dimension((int) widthPt, (int) heightPt);
    /*     */
    /* 716 */ final BufferedImage retval = new BufferedImage(widthPx, heightPx, imageType);
    /* 717 */ final Graphics2D graphics = (Graphics2D) retval.getGraphics();
    /* 718 */ graphics.setBackground(PDFBoxThumbnailer.TRANSPARENT_WHITE);
    /* 719 */ graphics.clearRect(0, 0, retval.getWidth(), retval.getHeight());
    /* 720 */ graphics.scale(scaling, scaling);
    /* 721 */ final PageDrawer drawer = new PageDrawer();
    /* 722 */ drawer.drawPage(graphics, page, pageDimension);
    /*     */ try
    /*     */ {
        /* 728 */ final int rotation = page.findRotation();
        /* 729 */ if (rotation == 90 || rotation == 270)
        /*     */ {
            /* 731 */ final int w = retval.getWidth();
            /* 732 */ final int h = retval.getHeight();
            /* 733 */ final BufferedImage rotatedImg = new BufferedImage(w, h, retval.getType());
            /* 734 */ final Graphics2D g = rotatedImg.createGraphics();
            /* 735 */ g.rotate(Math.toRadians(rotation), w / 2, h / 2);
            /* 736 */ g.drawImage(retval, null, 0, 0);
            /*     */ }
        /*     */ }
    /*     */ catch (final ImagingOpException e)
    /*     */ {
        /* 741 */ //log.warn("Unable to rotate page image", e);
        /*     */ }
    /*     */
    /* 744 */ return retval;
    /*     */ }