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:RasterDemo.java

RasterPanel() {
    setBackground(Color.white);/*from w w  w .  j a  v a 2s  . c  o m*/
    setSize(450, 400);

    Image image = getToolkit().getImage("largeJava2sLogo.jpg");

    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 1);
    try {
        mt.waitForAll();
    } catch (Exception e) {
        System.out.println("Exception while loading image.");
    }

    if (image.getWidth(this) == -1) {
        System.out.println("No jpg file");
        System.exit(0);
    }

    bi1 = new BufferedImage(image.getWidth(this), image.getHeight(this), BufferedImage.TYPE_INT_ARGB);
    Graphics2D big = bi1.createGraphics();
    big.drawImage(image, 0, 0, this);
    bi = bi1;
}

From source file:juicebox.tools.utils.juicer.apa.APAPlotter.java

/**
 * Method for plotting apa data/* ww w .j  a v  a  2  s  .c om*/
 *
 * @param data       for heat map
 * @param axesRange  initial values and increments to annotate axes [x0, dx, y0, dy]
 * @param outputFile where image will saved
 */
public static void plot(RealMatrix data, int[] axesRange, File outputFile, String title) {

    APARegionStatistics apaStats = new APARegionStatistics(data);
    DecimalFormat df = new DecimalFormat("0.000");
    title += ", P2LL = " + df.format(apaStats.getPeak2LL());

    // initialize heat map
    HeatChart map = new HeatChart(data.getData());
    map.setLowValueColour(Color.WHITE);
    map.setHighValueColour(Color.RED);
    map.setXValues(axesRange[0], axesRange[1]);
    map.setYValues(axesRange[2], axesRange[3]);
    map.setTitle(title);

    try {
        // calculate dimensions for plot wrapper
        initializeSizes(map);

        // create blank white image
        BufferedImage apaImage = new BufferedImage(fullWidth, fullHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = apaImage.createGraphics();
        g2.setBackground(Color.WHITE);
        g2.fillRect(0, 0, fullWidth, fullHeight);

        // plot in heat map, color bar, etc
        g2.drawImage(map.getChartImage(), 0, 0, heatmapWidth, fullHeight, null);
        drawHeatMapBorder(g2, map);
        plotColorScaleBar(g2);
        plotColorScaleValues(g2, map);

        // top left, top right, bottom left, bottom right values (from apa)

        drawCornerRegions(g2, map, new Dimension(APA.regionWidth, APA.regionWidth),
                apaStats.getRegionCornerValues());

        // save data
        ImageIO.write(apaImage, "png", outputFile);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.aistor.common.servlet.ValidateCodeServlet.java

private void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    /*/*from  ww w  .ja  va  2  s .c  o  m*/
     * ??
     */
    String width = request.getParameter("width");
    String height = request.getParameter("height");
    if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
        w = NumberUtils.toInt(width);
        h = NumberUtils.toInt(height);
    }

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    /*
     * ?
     */
    createBackground(g);

    /*
     * ?
     */
    String s = createCharacter(g);
    request.getSession().setAttribute("validateCode", s);

    g.dispose();
    OutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    out.close();

}

From source file:apm.common.servlet.ValidateCodeServlet.java

private void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    /*/*from  w w  w  . j a  va  2s .co m*/
     * ??
     */
    String width = request.getParameter("width");
    String height = request.getParameter("height");
    if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
        w = NumberUtils.toInt(width);
        h = NumberUtils.toInt(height);
    }

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    /*
     * ?
     */
    createBackground(g);

    /*
     * ?
     */
    String s = createCharacter(g);
    request.getSession().setAttribute(VALIDATE_CODE, s);

    g.dispose();
    OutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    out.close();

}

From source file:com.igormaznitsa.sciareto.ui.UiUtils.java

@Nonnull
public static Image iconToImage(@Nonnull Component context, @Nullable final Icon icon) {
    if (icon instanceof ImageIcon) {
        return ((ImageIcon) icon).getImage();
    }/*from w  ww .j a v a  2  s .  com*/
    final int width = icon == null ? 16 : icon.getIconWidth();
    final int height = icon == null ? 16 : icon.getIconHeight();
    final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    if (icon != null) {
        final Graphics g = image.getGraphics();
        try {
            icon.paintIcon(context, g, 0, 0);
        } finally {
            g.dispose();
        }
    }
    return image;
}

From source file:kz.supershiny.core.services.ImageService.java

/**
 * Creates thumb for image.//from  w  ww .ja v a2  s.  c  o m
 *
 * @param originalData original image in byte array
 * @param type original - 0, large - 1, small - 2
 * @return resized image in byte array
 */
public static byte[] resizeImage(byte[] originalData, ImageSize type) {
    //if original flag, then return original
    if (type.equals(ImageSize.ORIGINAL)) {
        return originalData;
    }

    BufferedImage originalImage = null;
    BufferedImage resizedImage = null;
    byte[] result = null;
    //convert bytes to BufferedImage
    try (InputStream in = new ByteArrayInputStream(originalData)) {
        originalImage = ImageIO.read(in);
    } catch (IOException ex) {
        LOG.error("Cannot convert byte array to BufferedImage!", ex);
        return null;
    }
    //get original size
    int scaledHeight = originalImage.getHeight();
    int scaledWidth = originalImage.getWidth();

    switch (type) {
    case LARGE:
        scaledWidth = LARGE_WIDTH;
        scaledHeight = LARGE_HEIGHT;
        break;
    case SMALL:
        scaledWidth = SMALL_WIDTH;
        scaledHeight = SMALL_HEIGHT;
        break;
    default:
        break;
    }
    //calculate aspect ratio
    float ratio = 1.0F * originalImage.getWidth() / originalImage.getHeight();
    if (ratio > 1.0F) {
        scaledHeight = (int) (scaledHeight / ratio);
    } else {
        scaledWidth = (int) (scaledWidth * ratio);
    }
    //resize with hints
    resizedImage = new BufferedImage(scaledWidth, scaledHeight,
            originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType());

    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    g.setComposite(AlphaComposite.Src);

    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    //convert BufferedImage to bytes
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(resizedImage, "png", baos);
        baos.flush();
        result = baos.toByteArray();
    } catch (IOException ex) {
        LOG.error("Cannot convert BufferedImage to byte array!", ex);
    }
    return result;
}

From source file:examples.utils.CifarReader.java

public static BufferedImage getImageFromArray(double[] pixels, int width, int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    for (int i = 0; i < pixels.length / IMAGE_DEPTH; ++i) {
        int rgb = new Color(Double.valueOf(pixels[i]).intValue(), Double.valueOf(pixels[i + 1024]).intValue(),
                Double.valueOf(pixels[i + 2048]).intValue()).getRGB();
        image.setRGB(i % IMAGE_WIDTH, i / IMAGE_HIGHT, rgb);
    }// w w w  .  j  a va2 s  .  co m
    return image;
}

From source file:mod.rankshank.arbitraria.client.texture.TextureTiled.java

@Override
public void loadTexture(IResourceManager resourceManager) throws IOException {
    this.deleteGlTexture();
    IResource iresource = null;/*from ww w .j a v  a2  s  .  c o m*/
    try {
        iresource = resourceManager.getResource(tileSource);
        BufferedImage img = TextureUtil.readBufferedImage(iresource.getInputStream());
        boolean blur = false;
        boolean clamp = false;

        if (iresource.hasMetadata()) {
            try {
                TextureMetadataSection texturemetadatasection = iresource.getMetadata("texture");

                if (texturemetadatasection != null) {
                    blur = texturemetadatasection.getTextureBlur();
                    clamp = texturemetadatasection.getTextureClamp();
                }
            } catch (RuntimeException runtimeexception) {
                Arbitraria.error(new Throwable(
                        String.format("Issue loading tiled texture for %s, aborting", tileSource.toString()),
                        runtimeexception));
            }
        }

        int width = img.getWidth();
        int height = img.getHeight();
        if (width != height) {
            Arbitraria.error(new Throwable(String.format("Tiled image failed for %s [Width = %s, Height = %s",
                    tileSource, width, height)));
            return;
        }
        int factor = targetTile / width;

        BufferedImage finalImg = new BufferedImage(width * factor, height * factor, img.getType());

        int num = 0;
        for (int i = 0; i < factor; i++) {
            for (int j = 0; j < factor; j++) {
                finalImg.createGraphics().drawImage(img, width * j, height * i, null);
                num++;
            }
        }
        TextureUtil.uploadTextureImageAllocate(this.getGlTextureId(), finalImg, blur, clamp);
    } finally {
        IOUtils.closeQuietly(iresource);
    }
}

From source file:com.openbravo.pos.util.ThumbNailBuilder.java

public Image getThumbNailText(Image img, String text) {
    /*/*from w  w  w. j  av a 2s  . c  o  m*/
     * Create an image containing a thumbnail of the product image,
     * or default image.
     * 
     * Then apply the text of the product name. Use text wrapping.
     * 
     * If the product name is too big for the label, ensure that
     * the first part is displayed.
     */

    img = getThumbNail(img);

    BufferedImage imgtext = new BufferedImage(img.getWidth(null), img.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = imgtext.createGraphics();

    // The text
    // <p style="width: 100px"> DOES NOT WORK PROPERLY.
    // use width= instead.
    String html = "<html><p style=\"text-align:center\" width=\"" + imgtext.getWidth() + "\">"
            + StringEscapeUtils.escapeHtml(text) + "</p>";

    JLabel label = new JLabel(html);
    label.setOpaque(false);
    //label.setText("<html><center>Line1<br>Line2");
    label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    label.setVerticalAlignment(javax.swing.SwingConstants.TOP);
    Dimension d = label.getPreferredSize();
    label.setBounds(0, 0, imgtext.getWidth(), d.height);

    // The background
    Color c1 = new Color(0xff, 0xff, 0xff, 0x40);
    Color c2 = new Color(0xff, 0xff, 0xff, 0xd0);

    //        Point2D center = new Point2D.Float(imgtext.getWidth() / 2, label.getHeight());
    //        float radius = imgtext.getWidth() / 3;
    //        float[] dist = {0.1f, 1.0f};
    //        Color[] colors = {c2, c1};        
    //        Paint gpaint = new RadialGradientPaint(center, radius, dist, colors);
    Paint gpaint = new GradientPaint(new Point(0, 0), c1, new Point(label.getWidth() / 2, 0), c2, true);

    g2d.drawImage(img, 0, 0, null);
    int ypos = imgtext.getHeight() - label.getHeight();
    int ypos_min = -4; // todo: configurable
    if (ypos < ypos_min)
        ypos = ypos_min; // Clamp label
    g2d.translate(0, ypos);
    g2d.setPaint(gpaint);
    g2d.fillRect(0, 0, imgtext.getWidth(), label.getHeight());
    label.paint(g2d);

    g2d.dispose();

    return imgtext;
}

From source file:dk.netdesign.common.osgi.config.osgi.OCD.java

public BufferedImage scaleImage(BufferedImage img, int width, int height, Color background) {
    int imgWidth = img.getWidth();
    int imgHeight = img.getHeight();
    if (imgWidth * height < imgHeight * width) {
        width = imgWidth * height / imgHeight;
    } else {//w  w  w  . ja v a2s.co  m
        height = imgHeight * width / imgWidth;
    }
    BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = newImage.createGraphics();
    try {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setBackground(background);
        g.clearRect(0, 0, width, height);
        g.drawImage(img, 0, 0, width, height, null);
    } finally {
        g.dispose();
    }
    return newImage;
}