Example usage for java.awt.image BufferedImage TYPE_INT_ARGB

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

Introduction

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

Prototype

int TYPE_INT_ARGB

To view the source code for java.awt.image BufferedImage TYPE_INT_ARGB.

Click Source Link

Document

Represents an image with 8-bit RGBA color components packed into integer pixels.

Usage

From source file:trendgraph.XYLineChart_AWT.java

public XYLineChart_AWT(int yearStart, int yearEnd, String[] creditUnionName, String columnName)
        throws SQLException {
    super("Graph");
    super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    this.yearStart = yearStart;
    this.yearEnd = yearEnd;
    this.creditUnionName = creditUnionName;
    this.columnName = columnName;
    saveGraphButton = new JButton("Save Graph");
    saveGraphButton.setBorderPainted(false);
    saveGraphButton.setFocusPainted(false);

    JFreeChart xylineChart = ChartFactory.createXYLineChart("CU Report", "Year (YYYY)", //X-axis
            columnName, //Y-axis (replace with columnName
            createDataset(), PlotOrientation.VERTICAL, true, true, false);

    ChartPanel chartPanel = new ChartPanel(xylineChart);
    chartPanel.setPreferredSize(new java.awt.Dimension(1000, 800)); //(x, y)
    final XYPlot plot = xylineChart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();

    renderer.setSeriesPaint(0, Color.RED); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(0, new BasicStroke(3.0f)); //Font size

    renderer.setSeriesPaint(1, Color.BLUE); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(1, new BasicStroke(3.0f)); //Font size

    renderer.setSeriesPaint(2, Color.GREEN); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(2, new BasicStroke(3.0f)); //Font size

    renderer.setSeriesPaint(3, Color.yellow); //can be GREEN, YELLOW, ETC.

    renderer.setSeriesStroke(3, new BasicStroke(3.0f)); //Font size

    plot.setRenderer(renderer);//  w  ww . ja  v  a2  s .co  m
    chartPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));
    chartPanel.add(saveGraphButton);
    setContentPane(chartPanel);
    pack();
    RefineryUtilities.centerFrameOnScreen(this);
    setVisible(true);

    saveGraphButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Rectangle rect = chartPanel.getBounds();
            FileChooser chooser = new FileChooser();

            //get chosen path and save the variable
            String path = chooser.getPath();
            path = path.replace("\\", "/");

            String format = "png";
            String fileName = path + "." + format;
            BufferedImage captureImage = new BufferedImage(rect.width, rect.height,
                    BufferedImage.TYPE_INT_ARGB);
            chartPanel.paint(captureImage.getGraphics());

            File file = new File(fileName);

            try {
                ImageIO.write(captureImage, format, file);

                //write data to file
            } catch (IOException ex) {
                Logger.getLogger(XYLineChart_AWT.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}

From source file:nl.b3p.kaartenbalie.service.KBImageTool.java

/** Reads an image from an http input stream.
 *
 * @param is Inputstream/*from  w w w . j a  va2  s  . c o  m*/
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(InputStream is, String mime, ServiceProviderRequest wmsRequest)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int bytesRead = 0;
    byte[] buffer = new byte[2048];
    while (bytesRead != -1) {
        bytesRead = is.read(buffer, 0, buffer.length);
        if (bytesRead > 0)
            baos.write(buffer, 0, bytesRead);
    }

    if (mime.indexOf(";") != -1) {
        mime = mime.substring(0, mime.indexOf(";"));
    }
    String mimeType = getMimeType(mime);
    if (mimeType == null) {
        String message = baos.toString();
        message = message.replaceAll("(\\r|\\n)", "");
        log.error("Response from server not understood (mime = " + mime + "): " + message);
        throw new Exception("Response from server not understood (mime = " + mime + "): " + message);
    }

    ImageReader ir = getReader(mimeType);
    if (ir == null) {
        log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        throw new Exception(
                "no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
    }

    //TODO Make smarter.. Possibly faster... But keep reporting!
    wmsRequest.setBytesReceived(new Long(baos.size()));
    ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
    ir.setInput(stream, true);
    try {
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        BufferedImage i = ir.read(0);
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
        return i;
    } finally {
        ir.dispose();
    }
}

From source file:eu.planets_project.tb.impl.data.util.ImageThumbnail.java

/**
 * Create a scaled jpeg of an image. The width/height ratio is preserved.
 * //  w ww .  jav  a  2  s. c  o  m
 * <p>
 * If image is smaller than thumbWidth x thumbHeight, it will be magnified,
 * otherwise it will be scaled down.
 * </p>
 * 
 * @param image
 *            the image to reduce
 * @param thumbWidth
 *            the maximum width of the thumbnail
 * @param thumbHeight
 *            the maximum heigth of the thumbnail
 * @param quality
 *            the jpeg quality ot the thumbnail
 * @param out
 *            a stream where the thumbnail data is written to
 */
public static void createThumb(Image image, int thumbWidth, int thumbHeight, OutputStream out)
        throws Exception {
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    double thumbRatio = (double) thumbWidth / (double) thumbHeight;
    double imageRatio = (double) imageWidth / (double) imageHeight;
    if (thumbRatio < imageRatio) {
        thumbHeight = (int) (thumbWidth / imageRatio);
    } else {
        thumbWidth = (int) (thumbHeight * imageRatio);
    }
    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
    // save thumbnail image to out stream
    log.debug("Start writing rescaled image...");
    ImageIO.write(thumbImage, "png", out);
    log.debug("DONE writing rescaled image...");
}

From source file:com.igormaznitsa.jhexed.values.HexSVGImageValue.java

@Override
public void prerasterizeIcon(final Shape shape) {
    try {/*from w ww  .j  av  a 2s  .  c  om*/
        final Rectangle r = shape.getBounds();
        final BufferedImage img = this.image.rasterize(r.width, r.height, BufferedImage.TYPE_INT_ARGB);
        final BufferedImage result = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g = result.createGraphics();
        g.setClip(shape);
        g.drawImage(img, 0, 0, null);
        g.dispose();
        this.prerasterized = result;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Composite.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;

    Dimension d = getSize();/*from  w w  w . jav a2 s .  co m*/
    int w = d.width;
    int h = d.height;

    BufferedImage buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D gbi = buffImg.createGraphics();

    g2.setColor(Color.white);
    g2.fillRect(0, 0, d.width, d.height);

    int rectx = w / 4;
    int recty = h / 4;

    gbi.setColor(new Color(0.0f, 0.0f, 1.0f, 1.0f));
    gbi.fill(new Rectangle2D.Double(rectx, recty, 150, 100));
    gbi.setColor(new Color(1.0f, 0.0f, 0.0f, 1.0f));
    gbi.setComposite(ac);
    gbi.fill(new Ellipse2D.Double(rectx + rectx / 2, recty + recty / 2, 150, 100));

    g2.drawImage(buffImg, null, 0, 0);
}

From source file:com.lcdfx.pipoint.PiPoint.java

public PiPoint(String[] args) {

    this.addWindowListener(new WindowAdapter() {
        @Override/*  ww w. j  a  v  a  2 s  .  com*/
        public void windowClosing(WindowEvent ev) {
            shutDown();
        }
    });

    // add logging
    logger = Logger.getLogger(this.getClass().getName());
    logger.log(Level.INFO,
            "PiPoint version " + PiPoint.class.getPackage().getImplementationVersion() + " running under "
                    + System.getProperty("java.vm.name") + " v" + System.getProperty("java.vm.version"));

    // get command line options
    CommandLineParser parser = new BasicParser();
    Map<String, String> cmdOptions = new HashMap<String, String>();
    Options options = new Options();
    options.addOption(new Option("f", "fullscreen", false, "fullscreen mode (no cursor)"));
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        for (Option option : cmd.getOptions()) {
            cmdOptions.put(option.getOpt(), option.getValue());
        }
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar pipoint.jar", options);
        System.exit(0);
    }

    if (cmd.hasOption("f")) {
        setUndecorated(true);
        BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
        Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0),
                "blank cursor");
        getContentPane().setCursor(blankCursor);
    }

    // instantiate the RendererManager
    mgr = new DlnaRendererManager(this);
    mgr.refreshDevices();

    nowPlayingPanel = new NowPlayingPanel(this);
    mgr.getRenderer().addListener(nowPlayingPanel);
    devicePanel = new DevicePanel(this);

    this.getContentPane().setPreferredSize(new Dimension(DISPLAY_WIDTH, DISPLAY_HEIGHT));
    this.getContentPane().add(devicePanel);
}

From source file:OffScreenTest.java

public void init() {
    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    BufferedImage bImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);

    ImageComponent2D buffer = new ImageComponent2D(ImageComponent.FORMAT_RGBA, bImage);
    buffer.setCapability(ImageComponent2D.ALLOW_IMAGE_READ);

    Raster drawRaster = new Raster(new Point3f(0.0f, 0.0f, 0.0f), Raster.RASTER_COLOR, 0, 0, 200, 200, buffer,
            null);/*from   w ww  .  ja v  a 2s. c o m*/

    drawRaster.setCapability(Raster.ALLOW_IMAGE_WRITE);

    // create the main scene graph
    BranchGroup scene = createSceneGraph(drawRaster);

    // create the on-screen canvas
    OnScreenCanvas3D d = new OnScreenCanvas3D(config, false);
    add("Center", d);

    // create a simple universe
    u = new SimpleUniverse(d);

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    u.getViewingPlatform().setNominalViewingTransform();

    // create an off Screen Canvas

    OffScreenCanvas3D c = new OffScreenCanvas3D(config, true, drawRaster);

    // set the offscreen to match the onscreen
    Screen3D sOn = d.getScreen3D();
    Screen3D sOff = c.getScreen3D();
    sOff.setSize(sOn.getSize());
    sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth());
    sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight());

    // attach the same view to the offscreen canvas
    View v = u.getViewer().getView();
    v.addCanvas3D(c);

    // tell onscreen about the offscreen so it knows to
    // render to the offscreen at postswap
    d.setOffScreenCanvas(c);

    u.addBranchGraph(scene);
    v.stopView();
    // Make sure that image are render completely
    // before grab it in postSwap().
    d.setImageReady();
    v.startView();

}

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());/*w  w w  . j av  a 2 s . com*/
        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:ConvertUtil.java

/**
 * Converts the source image to 32-bit colour with transparency (ARGB).
 * /*  ww w.  j a  v a2  s . co m*/
 * @param src
 *            the source image to convert
 * @return a copy of the source image with a 32-bit colour depth.
 */
public static BufferedImage convert32(BufferedImage src) {
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);
    cco.filter(src, dest);
    return dest;
}

From source file:cpcc.core.utils.PngImageStreamResponseTest.java

@Test
public void shouldConvertBufferedImage() throws IOException {
    BufferedImage image = new BufferedImage(2, 2, BufferedImage.TYPE_INT_ARGB);
    Graphics gr = image.getGraphics();
    gr.setColor(Color.GREEN);//from   w w  w .j a  va2s  .co m
    gr.drawLine(0, 0, 1, 1);
    gr.setColor(Color.BLACK);
    gr.drawLine(1, 1, 0, 0);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "PNG", baos);
    byte[] expected = baos.toByteArray();

    StreamResponse response = PngImageStreamResponse.convertImageToStreamResponse(image);

    assertThat(response.getStream()).isNotNull();
    byte[] actual = IOUtils.toByteArray(response.getStream());

    assertThat(actual).isEqualTo(expected);
}