Example usage for java.awt.image BufferedImage BufferedImage

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

Introduction

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

Prototype

public BufferedImage(int width, int height, int imageType) 

Source Link

Document

Constructs a BufferedImage of one of the predefined image types.

Usage

From source file:filters.collage.CropFilter.java

@Override
protected void doFilter(BufferedImage image, OutputStream output, FilterOptions options, String format)
        throws IOException {

    com.jhlabs.image.CropFilter cropFilter = new com.jhlabs.image.CropFilter(
            options.get(FilterOption.X, Integer.class), options.get(FilterOption.Y, Integer.class),
            options.get(FilterOption.WIDTH, Integer.class), options.get(FilterOption.HEIGHT, Integer.class));

    BufferedImage outputImage = new BufferedImage(options.get(FilterOption.WIDTH, Integer.class),
            options.get(FilterOption.HEIGHT, Integer.class), BufferedImage.TYPE_INT_RGB);

    cropFilter.filter(image, outputImage);
    ImageIO.write(outputImage, format, output);
}

From source file:com.webpagebytes.cms.DefaultImageProcessor.java

public boolean resizeImage(WPBFileStorage cloudStorage, WPBFilePath cloudFile, int desiredSize,
        String outputFormat, OutputStream os) throws WPBException {
    InputStream is = null;//from w  w  w  .ja v a 2  s  .  c o m
    try {
        //get the file content
        WPBFileInfo fileInfo = cloudStorage.getFileInfo(cloudFile);
        String type = fileInfo.getContentType().toLowerCase();
        if (!type.startsWith("image")) {
            return false;
        }
        is = cloudStorage.getFileContent(cloudFile);
        BufferedImage bufImg = ImageIO.read(is);
        Dimension<Integer> newSize = getResizeSize(bufImg.getWidth(), bufImg.getHeight(), desiredSize);
        BufferedImage bdest = new BufferedImage(newSize.getX(), newSize.getY(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bdest.createGraphics();
        Dimension<Double> scale = getResizeScale(bufImg.getHeight(), bufImg.getWidth(), desiredSize);
        AffineTransform at = AffineTransform.getScaleInstance(scale.getX(), scale.getY());
        g.drawRenderedImage(bufImg, at);
        ImageIO.write(bdest, outputFormat, os);
        return true;
    } catch (Exception e) {
        throw new WPBException("Cannot resize image ", e);
    } finally {
        IOUtils.closeQuietly(is);
    }

}

From source file:org.wkm.mtool.service.QRCodeService.java

/**
 * ??(QRCode)//from ww  w . j  a v a  2s.  c om
 * @param content
 * @param imgFile
 */
private void encoderQRCode(String content, File imgFile) {
    try {
        Qrcode qrcodeHandler = new Qrcode();
        qrcodeHandler.setQrcodeErrorCorrect('M');
        qrcodeHandler.setQrcodeEncodeMode('B');
        qrcodeHandler.setQrcodeVersion(7);

        System.out.println(content);
        byte[] contentBytes = content.getBytes(Consts.UTF_8.name());

        BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);

        Graphics2D gs = bufImg.createGraphics();

        gs.setBackground(Color.WHITE);
        gs.clearRect(0, 0, 140, 140);

        // ? > BLACK
        gs.setColor(Color.BLACK);

        // ??? ???
        int pixoff = 2;
        //  > ?
        if (contentBytes.length > 0 && contentBytes.length < 120) {
            boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
            for (int i = 0; i < codeOut.length; i++) {
                for (int j = 0; j < codeOut.length; j++) {
                    if (codeOut[j][i]) {
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        } else {
            System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
        }

        gs.dispose();
        bufImg.flush();

        // ??QRCode
        ImageIO.write(bufImg, "png", imgFile);

    } catch (Exception e) {
        log.info("Exception:" + e.getMessage());
    }
}

From source file:io.warp10.script.processing.Pencode.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
    Object top = stack.pop();/*from w  ww.j a v  a  2  s. c o m*/

    if (!(top instanceof processing.core.PGraphics)) {
        throw new WarpScriptException(getName() + " operates on a PGraphics instance.");
    }

    processing.core.PGraphics pg = (processing.core.PGraphics) top;

    pg.endDraw();

    BufferedImage bimage = new BufferedImage(pg.pixelWidth, pg.pixelHeight, BufferedImage.TYPE_INT_ARGB);
    bimage.setRGB(0, 0, pg.pixelWidth, pg.pixelHeight, pg.pixels, 0, pg.pixelWidth);
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png");
    ImageWriter writer = null;
    if (iter.hasNext()) {
        writer = iter.next();
    }
    ImageWriteParam param = writer.getDefaultWriteParam();
    IIOMetadata metadata = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedOutputStream output = new BufferedOutputStream(baos);

    try {
        writer.setOutput(ImageIO.createImageOutputStream(output));
        writer.write(metadata, new IIOImage(bimage, null, metadata), param);
    } catch (IOException ioe) {
        throw new WarpScriptException(getName() + " error while encoding PGraphics.", ioe);
    }

    writer.dispose();

    StringBuilder sb = new StringBuilder("data:image/png;base64,");
    sb.append(Base64.encodeBase64String(baos.toByteArray()));

    stack.push(sb.toString());

    //
    // Re-issue a 'beginDraw' so we can continue using the PGraphics instance
    //

    pg.beginDraw();

    return stack;
}

From source file:Main.java

/**
 * This method returns a buffered image with the contents of an image
 * This snippet was taken from: http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html
 * @param image/*from   w  w  w . j a va 2s  . co  m*/
 * @return The buffered image
 */
public static BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }

    // This code ensures that all the pixels in the image are loaded
    image = new ImageIcon(image).getImage();

    // Determine if the image has transparent pixels; for this method's
    // implementation, see e661 Determining If an Image Has Transparent Pixels
    boolean hasAlpha = hasAlpha(image);

    // Create a buffered image with a format that's compatible with the screen
    BufferedImage bimage = null;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try {
        // Determine the type of transparency of the new buffered image
        int transparency = Transparency.OPAQUE;
        if (hasAlpha) {
            transparency = Transparency.BITMASK;
        }

        // Create the buffered image
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();
        bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
    } catch (HeadlessException e) {
        // The system does not have a screen
    }

    if (bimage == null) {
        // Create a buffered image using the default color model
        int type = BufferedImage.TYPE_INT_RGB;
        if (hasAlpha) {
            type = BufferedImage.TYPE_INT_ARGB;
        }
        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
    }

    // Copy image to buffered image
    Graphics g = bimage.createGraphics();

    // Paint the image onto the buffered image
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bimage;
}

From source file:probe.com.view.body.quantdatasetsoverview.diseasegroupsfilters.heatmap.HeatMapImgGenerator.java

public String generateHeatmap(String[] rows, String[] columns, String[][] data) {

    JPanel heatmapPanelLayout = new JPanel();
    heatmapPanelLayout.setLayout(null);/*from w w  w  .jav a 2 s .  c  o  m*/
    heatmapPanelLayout.setVisible(true);

    int width = (columns.length + 1) * 50;
    int height = (rows.length + 1) * 50;
    heatmapPanelLayout.setSize(width, height);
    JPanel cornerCell = initCell("#ffffff", 0, 0);
    int x = 50;
    int y = 0;
    heatmapPanelLayout.add(cornerCell);

    for (String headerCell : columns) {
        JPanel cell = initCell(headerCell, x, y);
        x += 50;
        heatmapPanelLayout.add(cell);

    }
    y = 50;
    for (String headerCell : rows) {
        JPanel cell = initCell(headerCell, 0, y);
        y += 50;
        heatmapPanelLayout.add(cell);

    }
    x = 50;
    y = 50;
    for (String[] row : data) {
        for (String color : row) {
            JPanel cell = initCell(color, x, y);
            heatmapPanelLayout.add(cell);
            x += 50;
        }
        x = 50;
        y += 50;
    }

    BufferedImage image = new BufferedImage(width + 10, height + 10, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    graphics.setBackground(Color.WHITE);
    heatmapPanelLayout.paint(graphics);
    byte[] imageData = null;

    try {

        ImageEncoder in = ImageEncoderFactory.newInstance(ImageFormat.PNG, new Float(0.084666f));
        imageData = in.encode(image);
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
    }

    String base64 = Base64.encodeBytes(imageData);
    base64 = "data:image/png;base64," + base64;
    return base64;

}

From source file:org.chos.transaction.passport.controller.CaptchaController.java

@RequestMapping(value = "/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedImage bi = new BufferedImage(40, 18, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    String c = generate();//from  w  w w.ja v a2  s  .  c o  m
    g.setColor(Color.white);
    g.fillRect(1, 1, 38, 16);

    g.setColor(generateColor());
    g.drawString(c, 4, 13);
    response.setContentType("image/jpeg");
    ServletOutputStream os = response.getOutputStream();
    //      os.write(b)
    //      ImageIO.createImageOutputStream(os);
    ImageIO.write(bi, "jpg", os);
    os.flush();
    os.close();
    request.getSession().setAttribute("captcha", c);
}

From source file:com.fusesource.forge.jmstest.persistence.rrd.RrdGraphPostProcessor.java

private void createThumbnail(BufferedImage image, String name, int thumbWidth, int thumbHeight) {

    double thumbRatio = (double) thumbWidth / (double) thumbHeight;
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    double imageRatio = (double) imageWidth / (double) imageHeight;

    if (thumbRatio < imageRatio) {
        thumbHeight = (int) (thumbWidth / imageRatio);
    } else {/*w w w  . j  a v  a2 s  .c  om*/
        thumbWidth = (int) (thumbHeight * imageRatio);
    }

    BufferedImage thumbImage = new BufferedImage(thumbWidth,

            thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

    File thumbFile = new File(getWorkDir().getAbsolutePath() + "/" + name + "-thumb.png");

    try {
        ImageIO.write(thumbImage, "PNG", thumbFile);
    } catch (IOException ioe) {
        log().error("Error creating thumbnail for: " + name);
    }
}

From source file:probe.com.model.util.vaadintoimageutil.HeatmapSwingComponent.java

public String generateHeatmap(String[] rows, String[] columns, String[][] data) {

    JPanel heatmapPanelLayout = new JPanel();
    heatmapPanelLayout.setLayout(null);/*from w  ww.  j a  va2s .  c  o m*/
    heatmapPanelLayout.setVisible(true);
    heatmapPanelLayout.setBorder(new LineBorder(Color.BLACK));
    int width = (columns.length + 1) * 50;
    int height = (rows.length + 1) * 50;
    heatmapPanelLayout.setSize(width, height);
    JPanel cornerCell = initCell("#ffffff", 0, 0);
    int x = 50;
    int y = 0;
    heatmapPanelLayout.add(cornerCell);

    for (String headerCell : columns) {
        JPanel cell = initCell(headerCell, x, y);
        x += 50;
        heatmapPanelLayout.add(cell);

    }
    y = 50;
    for (String headerCell : rows) {
        JPanel cell = initCell(headerCell, 0, y);
        y += 50;
        heatmapPanelLayout.add(cell);

    }
    x = 50;
    y = 50;
    for (String[] row : data) {
        for (String color : row) {
            JPanel cell = initCell(color, x, y);
            heatmapPanelLayout.add(cell);
            x += 50;
        }
        x = 50;
        y += 50;
    }

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    heatmapPanelLayout.paint(graphics);
    //        super.paint(graphics);
    byte[] imageData = null;

    try {

        ImageEncoder in = ImageEncoderFactory.newInstance(ImageFormat.PNG, new Float(0.084666f));
        imageData = in.encode(image);
    } catch (Exception e) {
        System.out.println(e.getLocalizedMessage());
    }

    String base64 = Base64.encodeBytes(imageData);
    base64 = "data:image/png;base64," + base64;
    return base64;
    //
    //        JFrame frame = new JFrame();
    //        frame.setSize(1000, 1000);
    //        frame.add(heatmapPanelLayout);
    //        frame.setVisible(true);

    //        return "";
}

From source file:de.laures.cewolf.util.ImageHelper.java

public static BufferedImage loadBufferedImage(String fileName) {
    Image image = loadImage(fileName);
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }// w  w w  .  j a  v  a2 s.  c  o  m
    /*        final boolean hasAlpha = hasAlpha(image);
    int transparency = Transparency.OPAQUE;
    if (hasAlpha) {
    transparency = Transparency.BITMASK;
    }*/
    int width = (int) Math.max(1.0, image.getWidth(null));
    int height = (int) Math.max(1.0, image.getHeight(null));
    // BufferedImage bimage = GRAPHICS_CONV.createCompatibleImage(width, height, transparency);
    BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    final Graphics g = bimage.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return bimage;
}