Example usage for java.awt Graphics2D setBackground

List of usage examples for java.awt Graphics2D setBackground

Introduction

In this page you can find the example usage for java.awt Graphics2D setBackground.

Prototype

public abstract void setBackground(Color color);

Source Link

Document

Sets the background color for the Graphics2D context.

Usage

From source file:Main.java

public static 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 {/*from  w  ww.j a  va  2s. c om*/
        height = imgHeight * width / imgWidth;
    }
    BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    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;
}

From source file:com.sketchy.utils.image.SketchyImage.java

public static BufferedImage toByteImage(BufferedImage image) {
    BufferedImage newImage = createByteImage(image.getWidth(), image.getHeight());
    Graphics2D graphics = newImage.createGraphics();
    graphics.setBackground(Color.white);
    graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
    graphics.drawImage(image, 0, 0, null);
    return newImage;
}

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

/**
 * Method for plotting apa data/*from  w  w  w. j  av  a 2  s  .c  o m*/
 *
 * @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.mikenimer.familydam.services.photos.ThumbnailService.java

/**
 * using the metadata orientation transformation information rotate the image.
 * @param image//from  w  w  w .j  a va  2 s . c o  m
 * @param transform
 * @return
 * @throws Exception
 */
public static BufferedImage transformImage(BufferedImage image, AffineTransform transform) throws Exception {

    AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);

    BufferedImage destinationImage = op.createCompatibleDestImage(image,
            (image.getType() == BufferedImage.TYPE_BYTE_GRAY) ? image.getColorModel() : null);
    Graphics2D g = destinationImage.createGraphics();
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, destinationImage.getWidth(), destinationImage.getHeight());
    destinationImage = op.filter(image, destinationImage);
    return destinationImage;
}

From source file:edu.umn.cs.spatialHadoop.nasa.MultiHDFPlot.java

/**
 * Draws a scale used with the heat map//  ww  w. ja v a  2 s. c om
 * @param output
 * @param valueRange
 * @param width
 * @param height
 * @throws IOException
 */
private static void drawVerticalScale(Path output, double min, double max, int width, int height,
        OperationsParams params) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);

    // fix this part to work according to color1, color2 and gradient type
    HDFPlot.HDFRasterizer gradient = new HDFPlot.HDFRasterizer();
    gradient.configure(params);
    HDFRasterLayer gradientLayer = (HDFRasterLayer) gradient.createCanvas(0, 0, new Rectangle());
    for (int y = 0; y < height; y++) {
        Color color = gradientLayer.calculateColor(height - y, 0, height);
        g.setColor(color);
        g.drawRect(width * 3 / 4, y, width / 4, 1);
    }

    int fontSize = 24;
    g.setFont(new Font("Arial", Font.BOLD, fontSize));
    double step = (max - min) * fontSize * 5 / height;
    step = (int) (Math.pow(10.0, Math.round(Math.log10(step))));
    double min_value = Math.floor(min / step) * step;
    double max_value = Math.floor(max / step) * step;

    g.setColor(Color.WHITE);
    for (double value = min_value; value <= max_value; value += step) {
        double y = ((value - min) + (max - value) * (height - fontSize)) / (max - min);
        g.drawString(String.valueOf((int) value), 5, (int) y);
    }

    g.dispose();

    FileSystem fs = output.getFileSystem(new Configuration());
    FSDataOutputStream outStream = fs.create(output, true);
    ImageIO.write(image, "png", outStream);
    outStream.close();
}

From source file:edu.umn.cs.spatialHadoop.nasa.MultiHDFPlot.java

/**
 * Draws a scale used with the heat map//ww w  .  ja  va  2  s.c  o  m
 * @param output
 * @param valueRange
 * @param width
 * @param height
 * @throws IOException
 */
private static void drawHorizontalScale(Path output, double min, double max, int width, int height,
        OperationsParams params) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);

    int fontSize = 24;
    // fix this part to work according to color1, color2 and gradient type
    HDFPlot.HDFRasterizer gradient = new HDFPlot.HDFRasterizer();
    gradient.configure(params);
    HDFRasterLayer gradientLayer = (HDFRasterLayer) gradient.createCanvas(0, 0, new Rectangle());
    for (int x = 0; x < width; x++) {
        Color color = gradientLayer.calculateColor(x, 0, width);
        g.setColor(color);
        g.drawRect(x, height - (fontSize - 5), 1, fontSize - 5);
    }

    g.setFont(new Font("Arial", Font.BOLD, fontSize));
    double step = (max - min) * fontSize * 5 / width;
    step = (int) (Math.pow(10.0, Math.round(Math.log10(step))));
    double min_value = Math.floor(min / step) * step;
    double max_value = Math.floor(max / step) * step;

    g.setColor(Color.WHITE);
    for (double value = min_value; value <= max_value; value += step) {
        double x = ((value - min) * (width - fontSize) + (max - value)) / (max - min);
        g.drawString(String.valueOf((int) value), (int) x, fontSize);
    }

    g.dispose();

    FileSystem fs = output.getFileSystem(new Configuration());
    FSDataOutputStream outStream = fs.create(output, true);
    ImageIO.write(image, "png", outStream);
    outStream.close();
}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

private static void enforceBorderColors(BufferedImage inputImage) {
    Graphics2D g = inputImage.createGraphics();
    g.setBackground(new Color(0, 0, 0, 0));
    g.clearRect(1, 1, inputImage.getWidth() - 2, inputImage.getHeight() - 2);
    g.dispose();//from   w  w w.  j a v a  2 s.c  om
    int w = inputImage.getWidth();
    int h = inputImage.getHeight();
    int[] rgb = new int[w * h];

    inputImage.getRGB(0, 0, w, h, rgb, 0, w);

    for (int i = 0; i < rgb.length; i++) {
        if ((0xff000000 & rgb[i]) != 0) {
            rgb[i] = 0xff000000;
        }
    }
    inputImage.setRGB(0, 0, w, h, rgb, 0, w);
}

From source file:net.sf.webphotos.tools.Thumbnail.java

private static Image estampar(Image im) {
    try {//  w ww  .  ja  va 2s  .co  m
        Image temp = new ImageIcon(im).getImage();

        BufferedImage buf = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = (Graphics2D) buf.getGraphics();

        g2.drawImage(temp, 0, 0, null);
        g2.setBackground(Color.BLUE);

        Dimension dimensaoFoto = new Dimension(im.getWidth(null), im.getHeight(null));

        // aplicar texto
        if (texto != null) {
            Util.out.println("aplicando texto " + texto);

            Font fonte = new Font(txFamilia, txEstilo, txTamanho);
            g2.setFont(fonte);
            FontMetrics fm = g2.getFontMetrics(fonte);
            Dimension dimensaoTexto = new Dimension(fm.stringWidth(texto), fm.getHeight());
            Point posTexto = calculaPosicao(dimensaoFoto, dimensaoTexto, txMargem, txPosicao);

            g2.setPaint(txCorFundo);
            g2.drawString(texto, (int) posTexto.getX() + 1, (int) posTexto.getY() + 1 + fm.getHeight());
            g2.setPaint(txCorFrente);
            g2.drawString(texto, (int) posTexto.getX(), (int) posTexto.getY() + fm.getHeight());
        }

        // aplicar marca dagua
        if (marcadagua != null) {
            Image marca = new ImageIcon(marcadagua).getImage();
            int rule = AlphaComposite.SRC_OVER;
            float alpha = (float) mdTransparencia / 100;
            Point pos = calculaPosicao(dimensaoFoto, new Dimension(marca.getWidth(null), marca.getHeight(null)),
                    mdMargem, mdPosicao);

            g2.setComposite(AlphaComposite.getInstance(rule, alpha));
            g2.drawImage(marca, (int) pos.getX(), (int) pos.getY(), null);
        }

        g2.dispose();
        //return (Image) buf;
        return Toolkit.getDefaultToolkit().createImage(buf.getSource());
    } catch (Exception e) {
        Util.err.println("[Thumbnail.estampar]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
        return im;
    }
}

From source file:iqq.util.ImageUtil.java

/**
 * //from   w w w.  j av a  2s .  co m
 *
 * @param srcFile ?
 * @param destFile 
 * @param destWidth 
 * @param destHeight 
 */
public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    if (type == Type.jdk) {
        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 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);
            graphics2D.dispose();

            FileOutputStream out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(destBufferedImage);
            param.setQuality((float) DEST_QUALITY / 100, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(destBufferedImage);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 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();
            }
        }
    }
}

From source file:net.shopxx.util.ImageUtil.java

/**
 * //from  w  w  w. ja v  a2  s.c  o  m
 * @param srcFile ?
 * @param destFile 
 * @param destWidth 
 * @param destHeight 
 */
public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
        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 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);
            graphics2D.dispose();

            FileOutputStream out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(destBufferedImage);
            param.setQuality((float) DEST_QUALITY / 100, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(destBufferedImage);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 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();
            }
        }
    }
}