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:ar.com.zauber.common.image.impl.AbstractImage.java

/**
 * Creates a thumbnail//from  w w  w .j  a  v a2s . com
 * 
 * @param is data source
 * @param os data source
 * @throws IOException if there is a problem reading is
 */
public static void createThumbnail(final InputStream is, final OutputStream os, final int target)
        throws IOException {
    final float compression = 0.85F;
    ImageWriter writer = null;
    MemoryCacheImageOutputStream mos = null;
    Graphics2D graphics2D = null;
    try {
        final BufferedImage bi = ImageIO.read(is);
        final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("JPG");
        if (!iter.hasNext()) {
            throw new IllegalStateException("can't find JPG subsystem");
        }

        int w = bi.getWidth(), h = bi.getHeight();
        if (w < target && h < target) {
            // nothing to recalculate, ya es chiquita.
        } else {
            if (w > h) {
                h = target * bi.getHeight() / bi.getWidth();
                w = target;
            } else {
                w = target * bi.getWidth() / bi.getHeight();
                h = target;
            }
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        final BufferedImage thumbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(bi, 0, 0, w, h, null);

        writer = (ImageWriter) iter.next();
        final ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(compression);
        mos = new MemoryCacheImageOutputStream(os);
        writer.setOutput(mos);
        writer.write(null, new IIOImage(thumbImage, null, null), iwp);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (mos != null) {
            mos.close();
        }
        if (graphics2D != null) {
            graphics2D.dispose();
        }
        is.close();
        os.close();
    }
}

From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java

@Override
public BufferedImage createCaptcha(char[] text) {
    if (text == null || text.length == 0) {
        throw new IllegalArgumentException("No captcha text given");
    }/*from ww  w. jav  a2s. com*/

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setBackground(Color.WHITE);
    g2d.setColor(Color.BLACK);

    clearCanvas(g2d);

    if (showGrid) {
        drawGrid(g2d);
    }

    int charMaxWidth = width / text.length;
    int xPos = 0;
    for (char ch : text) {
        drawCharacter(g2d, ch, xPos, charMaxWidth);
        xPos += charMaxWidth;
    }

    g2d.dispose();
    return image;
}

From source file:mobac.program.tiledatawriter.TileImageJpegDataWriter.java

public static boolean performOpenJDKJpegTest() {
    try {//from ww w. j a  v a  2s  .  c o  m
        TileImageJpegDataWriter writer = new TileImageJpegDataWriter(0.99d);
        writer.initialize();
        OutputStream out = new NullOutputStream();
        BufferedImage image = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
        writer.processImage(image, out);
        return true;
    } catch (Exception e) {
        log.debug("Jpeg test failed", e);
        return false;
    }
}

From source file:TrackerPanel.java

public TrackerPanel() {
    setBackground(Color.GRAY);// w  w w  .java2s.com

    df = new DecimalFormat("0.#"); // 1 dp
    msgFont = new Font("SansSerif", Font.BOLD, 13);

    configOpenNI();

    histogram = new float[MAX_DEPTH_SIZE];

    imWidth = depthMD.getFullXRes();
    imHeight = depthMD.getFullYRes();
    setSize(imWidth * 2, imHeight);
    System.out.println("Image dimensions (" + imWidth + ", " + imHeight + ")");
    // create empty image bytes array of correct size and type
    imgbytes = new byte[imWidth * imHeight * 3];
    hideBGPixel = new Color(0, 0, 255, 0).getRGB();

    // create d.s for holding camera pixels and image
    cameraPixels = new int[imWidth * imHeight];
    cameraImage = new BufferedImage(imWidth, imHeight, BufferedImage.TYPE_INT_ARGB);
    // the image must have an alpha channel for the transparent blue pixels

    new Thread(this).start(); // start updating the panel
}

From source file:org.n52.server.io.DiagramGenerator.java

/**
 * Creates a time series chart diagram and writes it to the OutputStream.
 *///from  w w  w  .jav a2s. c  o  m
public void producePresentation(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        FileOutputStream out, boolean compress) throws OXFException, IOException {

    // render features:
    int width = options.getWidth();
    int height = options.getHeight();
    Calendar begin = Calendar.getInstance();
    begin.setTimeInMillis(options.getBegin());
    Calendar end = Calendar.getInstance();
    end.setTimeInMillis(options.getEnd());

    DiagramRenderer renderer = new DiagramRenderer(false);

    JFreeChart diagramChart = renderer.renderChart(entireCollMap, options, begin, end, compress);
    diagramChart.removeLegend();

    // draw chart into image:
    BufferedImage diagramImage = new BufferedImage(width, height, TYPE_INT_RGB);
    Graphics2D chartGraphics = diagramImage.createGraphics();
    chartGraphics.setColor(Color.white);
    chartGraphics.fillRect(0, 0, width, height);

    diagramChart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));

    JPEGImageWriteParam p = new JPEGImageWriteParam(null);
    p.setCompressionMode(JPEGImageWriteParam.MODE_DEFAULT);
    write(diagramImage, FORMAT, out);
}

From source file:com.devbury.mkremote.server.QuickLaunchServiceImpl.java

public ArrayList<LaunchItem> list(String dir) {
    Base64 base64 = new Base64();
    JFileChooser chooser = new JFileChooser();
    File new_dir = newFileDir(dir);
    logger.debug("Looking for files in {}", new_dir.getAbsolutePath());
    ArrayList<LaunchItem> items = new ArrayList<LaunchItem>();
    if (isSupported()) {
        if (new_dir.isDirectory()) {
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return !name.startsWith(".");
                }//from  w w w.  j av a 2s . c o m
            };
            for (File f : new_dir.listFiles(filter)) {
                if (!f.isHidden()) {
                    LaunchItem item = new LaunchItem();
                    item.setName(f.getName());
                    item.setPath(dir);
                    if (f.isDirectory()) {
                        if (isMac() && f.getName().endsWith(".app")) {
                            item.setType(LaunchItem.FILE_TYPE);
                            item.setName(f.getName().substring(0, f.getName().length() - 4));
                        } else {
                            item.setType(LaunchItem.DIR_TYPE);
                        }
                    } else {
                        item.setType(LaunchItem.FILE_TYPE);
                    }
                    Icon icon = chooser.getIcon(f);
                    BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                            BufferedImage.TYPE_INT_RGB);
                    icon.paintIcon(null, bi.createGraphics(), 0, 0);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(bi, "png", os);
                        item.setIcon(base64.encodeToString(os.toByteArray()));
                    } catch (IOException e) {
                        logger.debug("could not write image {}", e);
                        item.setIcon(null);
                    }
                    logger.debug("Adding LaunchItem : {}", item);
                    items.add(item);
                } else {
                    logger.debug("Skipping hidden file {}", f.getName());
                }
            }
        }
    } else {
        new Thread() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null,
                        "We are sorry but quick launch is not supported on your platform",
                        "Quick Launch Not Supported", JOptionPane.ERROR_MESSAGE);
            }
        }.start();
    }
    return items;
}

From source file:ImageDrawingComponent.java

public ImageDrawingComponent(URL imageSrc) {
    try {//from   w ww .  j  ava2  s .  c  o m
        bi = ImageIO.read(imageSrc);
        w = bi.getWidth(null);
        h = bi.getHeight(null);
        if (bi.getType() != BufferedImage.TYPE_INT_RGB) {
            BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics big = bi2.getGraphics();
            big.drawImage(bi, 0, 0, null);
            bi = bi2;
        }
    } catch (IOException e) {
        System.out.println("Image could not be read");
        System.exit(1);
    }
}

From source file:org.jfree.data.general.HeatMapUtils.java

/**
 * Creates an image that displays the values from the specified dataset.
 *
 * @param dataset  the dataset ({@code null} not permitted).
 * @param paintScale  the paint scale for the z-values ({@code null}
 *         not permitted).//from   w  w w  .  j  a v a  2  s . co  m
 *
 * @return A buffered image.
 */
public static BufferedImage createHeatMapImage(HeatMapDataset dataset, PaintScale paintScale) {

    Args.nullNotPermitted(dataset, "dataset");
    Args.nullNotPermitted(paintScale, "paintScale");
    int xCount = dataset.getXSampleCount();
    int yCount = dataset.getYSampleCount();
    BufferedImage image = new BufferedImage(xCount, yCount, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    for (int xIndex = 0; xIndex < xCount; xIndex++) {
        for (int yIndex = 0; yIndex < yCount; yIndex++) {
            double z = dataset.getZValue(xIndex, yIndex);
            Paint p = paintScale.getPaint(z);
            g2.setPaint(p);
            g2.fillRect(xIndex, yCount - yIndex - 1, 1, 1);
        }
    }
    return image;
}

From source file:web.diva.server.model.profileplot.ProfilePlotImgeGenerator.java

public String toImage() {
    image = new BufferedImage(900, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setPaint(Color.WHITE);
    super.forceFullRepaint(graphics);
    //        super.paint(graphics);
    byte[] imageData = null;

    try {//from  w ww .  j a v a  2  s.  c om

        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:fr.gael.dhus.datastore.processing.impl.ProcessingUtils.java

/**
 * Cut the quicklook that have a big width/height ratio.
 * Each sub-part is dispatched on multiple bands.
 *
 * @param quick_look the quick_look to be cut
 * @param max_ratio the maximum ratio between quick_look width and height.
 * @param margin the margin between each band. default 5.
 *//*  w  w  w. ja  v  a  2 s  .  c  om*/
public static RenderedImage cutQuickLook(RenderedImage input_image, double max_ratio, int margin) {
    ColorModel color_model = input_image.getColorModel();
    if ((color_model == null) && (input_image.getSampleModel() != null)) {
        color_model = ColorRenderer.createColorModel(input_image.getSampleModel());
    }

    BufferedImage quick_look;
    try {
        quick_look = PlanarImage.wrapRenderedImage(input_image).getAsBufferedImage(
                new Rectangle(input_image.getWidth(), input_image.getHeight()), color_model);
    } catch (Exception e) {
        logger.error("Problem getting buffered image.", e);
        throw new IllegalArgumentException("Problem getting buffered image", e);
    }

    if ((quick_look != null) && ((quick_look.getWidth() > 0) && (quick_look.getHeight() > 0))) {
        //Compute width/height ratio
        int ql_width = quick_look.getWidth();
        int ql_height = quick_look.getHeight();
        int ratio = (int) Math.sqrt(Math.max(ql_width, ql_height) / Math.min(ql_width, ql_height));

        //Check if the quicklook has a strong width/height ratio
        if ((ratio < max_ratio) || (ratio <= 1))
            return PlanarImage.wrapRenderedImage(quick_look);

        /**
         * Cut the wider side (width or height) into "ratio" bands.
         * Ex: If height = 3 * width then we cut 3 bands along columns
         *     So height' = height / 3   (extract 1 band / 3 from height)
         *        width'  = width  * 3   (dispatch 3 bands along lines)
         */
        int width = ql_width; //width of the bands
        int height = ql_height; //height of the bands

        if (ql_width < ql_height) //cut along height
        {
            width = (ql_width + margin) * ratio;
            height = ql_height / ratio;
        } else //cut along width
        {
            width = ql_width / ratio;
            height = (ql_height + margin) * ratio;
        }

        //Dispatch the sub-parts
        BufferedImage quick_look_cut = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = quick_look_cut.createGraphics();

        for (int k = 0; k < ratio; k++) {
            BufferedImage ql_band = null;
            //Dispatch on columns
            if (ql_width < ql_height) {
                ql_band = quick_look.getSubimage(0, (k * ql_height) / ratio, ql_width, ql_height / ratio);
                g2.drawImage(ql_band, null, k * (ql_width + margin), 0);
            }
            //Dispatch on lines
            else {
                ql_band = quick_look.getSubimage((k * ql_width) / ratio, 0, ql_width / ratio, ql_height);
                g2.drawImage(ql_band, null, 0, k * (ql_height + margin));
            }
        } //for each band

        g2.dispose();
        return PlanarImage.wrapRenderedImage(quick_look_cut);
    }
    return PlanarImage.wrapRenderedImage(quick_look);
}