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:com.t3.image.ImageUtil.java

/**
 * Create a copy of the image that is compatible with the current graphics context
 * and scaled to the supplied size//from   w  w w.jav a  2 s.c  o  m
 */
public static BufferedImage createCompatibleImage(Image img, int width, int height, Map<String, Object> hints) {

    width = Math.max(width, 1);
    height = Math.max(height, 1);

    int transparency;
    if (hints != null && hints.containsKey(HINT_TRANSPARENCY)) {
        transparency = (Integer) hints.get(HINT_TRANSPARENCY);
    } else {
        transparency = pickBestTransparency(img);
    }
    BufferedImage compImg = new BufferedImage(width, height, transparency);

    Graphics2D g = null;
    try {
        g = compImg.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        g.drawImage(img, 0, 0, width, height, null);
    } finally {
        if (g != null) {
            g.dispose();
        }
    }

    return compImg;
}

From source file:com.gst.infrastructure.documentmanagement.data.ImageData.java

public void resizeImage(InputStream in, OutputStream out, int maxWidth, int maxHeight) throws IOException {

    BufferedImage src = ImageIO.read(in);
    if (src.getWidth() <= maxWidth && src.getHeight() <= maxHeight) {
        out.write(getContent());/*from w  ww. j  a v  a2  s  .c om*/
        return;
    }
    float widthRatio = (float) src.getWidth() / maxWidth;
    float heightRatio = (float) src.getHeight() / maxHeight;
    float scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio;

    // TODO(lindahl): Improve compressed image quality (perhaps quality
    // ratio)

    int newWidth = (int) (src.getWidth() / scaleRatio);
    int newHeight = (int) (src.getHeight() / scaleRatio);
    int colorModel = fileExtension == ContentRepositoryUtils.IMAGE_FILE_EXTENSION.JPEG
            ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage target = new BufferedImage(newWidth, newHeight, colorModel);
    Graphics2D g = target.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(src, 0, 0, newWidth, newHeight, Color.BLACK, null);
    g.dispose();
    ImageIO.write(target, fileExtension != null ? fileExtension.getValueWithoutDot() : "jpeg", out);
}

From source file:org.tsho.dmc2.core.chart.BasinRenderer.java

public void render(final Graphics2D g2, final Rectangle2D dataArea, final PlotRenderingInfo info) {
    basinComponent.setDataobject(null);//from ww w  . j ava2 s.  com
    attractorsSamplePoints = new Vector();

    state = STATE_RUNNING;

    gridWidth = (int) dataArea.getWidth();
    gridHeight = (int) dataArea.getHeight();

    this.imageX = (int) dataArea.getX() + 1;
    this.imageY = (int) dataArea.getY();

    this.image = new BufferedImage(gridWidth, gridHeight, BufferedImage.TYPE_INT_RGB);
    this.g2 = g2;
    WritableRaster raster = image.getRaster();

    ValueAxis domainAxis = plot.getDomainAxis();
    ValueAxis rangeAxis = plot.getRangeAxis();

    double maxCoordinate = Math.abs(domainAxis.getUpperBound());
    if (Math.abs(domainAxis.getLowerBound()) > maxCoordinate)
        maxCoordinate = Math.abs(domainAxis.getLowerBound());
    if (Math.abs(rangeAxis.getLowerBound()) > maxCoordinate)
        maxCoordinate = Math.abs(rangeAxis.getLowerBound());
    if (Math.abs(rangeAxis.getUpperBound()) > maxCoordinate)
        maxCoordinate = Math.abs(rangeAxis.getUpperBound());
    if (infinity < maxCoordinate)
        infinity = maxCoordinate + 1;

    grid = new Grid(new double[] { domainAxis.getLowerBound(), domainAxis.getUpperBound(),
            rangeAxis.getLowerBound(), rangeAxis.getUpperBound() }, gridHeight, gridWidth);
    imageData = ((DataBufferInt) raster.getDataBuffer()).getData();
    rate = gridHeight * gridWidth / 100;
    attractorsSamplePoints = new Vector();

    BasinsAlgorithm bA = null;
    if (type == FAST_ALGORITHM)
        bA = new FastBasinsAlgorithm(this);
    else if (type == SLOW_ALGORITHM)
        bA = new SlowBasinsAlgorithm(this);
    bA.run();

    /** Now that grid is computed, pass it to the BasinComponent for possible storing */
    int[] tmp = grid.getData();
    grid.setData((int[]) tmp.clone());//from now on, grid data is disconnected from image data
    basinComponent.setDataobject(grid);

    drawImage();
    state = STATE_FINISHED;
}

From source file:org.geotools.renderer.chart.ChartGraphicFactory.java

BufferedImage drawChart(JFreeChart chart, int w, int h) {
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D gr = bi.createGraphics();
    try {/* w w  w.  ja v a2s  . com*/
        chart.draw(gr, new Rectangle2D.Double(0, 0, w, h));
    } finally {
        gr.dispose();
    }

    return bi;
}

From source file:FontAlgo.java

private static TextualChar getTextualChar(char a_char) throws Throwable {
    BufferedImage bImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    Graphics g = bImg.getGraphics();
    g.setColor(Color.green);//from   w w w  .jav  a  2s  .com
    g.fillRect(0, 0, WIDTH, HEIGHT);

    g.setFont(appliedFont);
    g.setColor(Color.black);
    g.drawString(new String(new char[] { a_char }), 10, g.getFontMetrics().getHeight());
    PixelGrabber p = new PixelGrabber(bImg, 0, 0, WIDTH, HEIGHT, true);

    if (p.grabPixels()) {
        char[][] pattern = new char[WIDTH][HEIGHT];
        int baseColourPixel = 0, contrastColourPixel = 0, x1 = 0, x2 = 0, y1 = 0, y2 = 0;
        int[] pixels = (int[]) p.getPixels();
        baseColourPixel = pixels[0];
        // System.out.println("base: " + base);
        int xCounter = 0, yCounter = 0;
        for (int iPixel : pixels) {
            // System.out.println(iX + " - " + iY);
            if (isReverse) {
                pattern[xCounter][yCounter] = iPixel == baseColourPixel ? CHAR_TO_PATTERN : ' ';
            } else {
                pattern[xCounter][yCounter] = iPixel != baseColourPixel ? CHAR_TO_PATTERN : ' ';
            }

            yCounter++;
            if (yCounter > 49) {
                xCounter++;
                yCounter = 0;
            }

            if (contrastColourPixel == 0 && iPixel != baseColourPixel) {
                contrastColourPixel = iPixel;
                x1 = xCounter - 2;
                y1 = yCounter - 3;
                y2 = yCounter + 3;
            }

            if (contrastColourPixel == iPixel) {
                x2 = xCounter + 3;

                if (y1 > (yCounter - 3)) {
                    y1 = yCounter - 3;
                }

                if (y2 < (yCounter + 3)) {
                    y2 = yCounter + 3;
                }
            }
        }
        return new TextualChar(x1, x2, y1, y2, pattern);
    }
    return null;
}

From source file:com.scramcode.djinn.ui.panels.GraphPanel.java

/**
 * copy the visible part of the graph to a file as a jpeg image
 * @param file//w w w  .  j  a v a  2s. c o  m
 */
public void writeJPEGImage(File file) {
    int width = visualizationViewer.getWidth();
    int height = visualizationViewer.getHeight();

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = bi.createGraphics();
    visualizationViewer.paint(graphics);
    graphics.dispose();

    try {
        ImageIO.write(bi, "jpeg", file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public GradientImage(int width, int height, Color[] colors, int[] positions, int alignment) {
    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
    this.alignment = alignment;
    this.width = width;
    this.height = height;
    this.colors = colors;
    this.positions = positions;
    rgbs = new int[colors.length];
    for (int i = 0; i < rgbs.length; i++) {
        rgbs[i] = colors[i].getRGB();/*from   w w  w .j  a  v  a 2s . co  m*/
    }
    try {
        renderImage();
    } catch (Exception error) {
        error.printStackTrace();
    }
}

From source file:core.service.RubricImageCachingService.java

/**
 * generates image_quantity images for current page the images are resized to image_width * image_height resolution
 * @param p page to take images for/*  w  w  w  .j a v  a  2s . c  om*/
 * @param dst_dir dir where to save resulting images
 * @return false if any error occurs
 */
protected boolean generateImages(Pages p, File dst_dir) {
    boolean succeed = true;
    List<Long> ids = pages_service.getAllActiveChildrenId(p.getId());
    List<Wallpaper> wallpapers = wallpaper_service.getMainImages(ids, image_quantity);

    File src_dir = new File(wallpaper_service.getStorePath(), "full");
    File src;
    File dst;
    BufferedImageHolder holder;
    BufferedImage rez;
    for (Wallpaper wallpaper : wallpapers) {
        src = new File(src_dir, wallpaper.getName());
        dst = new File(dst_dir, wallpaper.getName());
        if (src.exists()) {
            try {
                holder = ImageUtils.readImage(src);
                rez = new BufferedImage(image_width, image_height, BufferedImage.TYPE_3BYTE_BGR);
                ImageUtils.getScaledImageDimmension(holder.getImage(), rez);
                ImageUtils.writeImage(rez, 1, dst);
            } catch (IOException ex) {
                logger.error("error while creating image for rubric; ", ex);
                succeed = false;
            }
        } else {
            logger.error("error while creating image for rubric; " + p.getId() + "; " + p.getName() + "; "
                    + src.getName());
            succeed = false;
        }
    }
    return succeed;
}

From source file:table.FrequencyTablePanel.java

public static BufferedImage createImage(JTable table) {
    JTableHeader tableHeaderComp = table.getTableHeader();
    int totalWidth = tableHeaderComp.getWidth();
    int totalHeight = tableHeaderComp.getHeight() + table.getHeight();
    BufferedImage tableImage = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2D = (Graphics2D) tableImage.getGraphics();
    tableHeaderComp.paint(g2D);/*from ww w .ja v a  2 s  . c  om*/
    g2D.translate(0, tableHeaderComp.getHeight());
    table.paint(g2D);
    return tableImage;
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);/*from   w  ww  .  j av  a2 s  .c o m*/
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}