Example usage for javax.imageio ImageIO write

List of usage examples for javax.imageio ImageIO write

Introduction

In this page you can find the example usage for javax.imageio ImageIO write.

Prototype

public static boolean write(RenderedImage im, String formatName, OutputStream output) throws IOException 

Source Link

Document

Writes an image using an arbitrary ImageWriter that supports the given format to an OutputStream .

Usage

From source file:net.sf.jooreports.web.samples.SalesReportGenerator.java

private RenderedImage createChart(Object model) {
    List lines = (List) ((Map) model).get("lines");
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (Iterator it = lines.iterator(); it.hasNext();) {
        ReportLine line = (ReportLine) it.next();
        dataset.addValue(line.getValue(), "sales", line.getMonth());
    }//from www.  ja  va  2  s  . c  o  m
    JFreeChart chart = ChartFactory.createBarChart("Monthly Sales", "Month", "Sales", dataset,
            PlotOrientation.VERTICAL, false, false, false);
    chart.setTitle((String) null);
    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = chart.getCategoryPlot();
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    GradientPaint paint = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    renderer.setSeriesPaint(0, paint);
    BufferedImage image = chart.createBufferedImage(400, 300);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, "png", outputStream);
    } catch (IOException ioException) {
        throw new RuntimeException("should never happen: " + ioException.getMessage());
    }
    return image;
}

From source file:gsn.vsensor.DemoVSensor.java

public void dataAvailable(String inputStreamName, StreamElement data) {
    if (inputStreamName.equalsIgnoreCase("SSTREAM")) {
        String action = (String) data.getData("STATUS");
        /**//from   ww w.  j  a  va  2s.c  o m
         * 
         */
        String moteId = (String) data.getData("ID");
        if (moteId.toLowerCase().indexOf("mica") < 0)
            return;
        if (action.toLowerCase().indexOf("add") >= 0)
            counter++;
        if (action.toLowerCase().indexOf("remove") >= 0)
            counter--;
    }
    if (inputStreamName.equalsIgnoreCase("CSTREAM")) {

        BufferedImage bufferedImage = null;
        outputStream.reset();
        byte[] rawData = (byte[]) data.getData("IMAGE");
        input = new ByteArrayInputStream(rawData);
        try {
            bufferedImage = ImageIO.read(input);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        int size = 30;
        int locX = 0;
        int locY = 0;
        if (counter < 0)
            counter = 0;
        switch (counter) {
        case 0:
            graphics.setColor(Color.RED);
            break;
        case 1:
            graphics.setColor(Color.ORANGE);
            break;

        case 2:
            graphics.setColor(Color.YELLOW);
            break;

        case 3:
            graphics.setColor(Color.GREEN);
            break;
        default:
            logger.warn(
                    new StringBuilder().append("Shouldn't happen.>").append(counter).append("<").toString());
        }
        graphics.fillOval(locX, locY, size, size);
        try {
            ImageIO.write(bufferedImage, "jpeg", outputStream);
            outputStream.close();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        StreamElement outputSE = new StreamElement(OUTPUT_FIELDS, OUTPUT_TYPES,
                new Serializable[] { outputStream.toByteArray() }, data.getTimeStamp());
        dataProduced(outputSE);
    }
    logger.info(
            new StringBuilder().append("Data received under the name: ").append(inputStreamName).toString());
}

From source file:dk.dma.msinm.web.OsmStaticMap.java

/**
 * Main GET method/*from  www . j a v  a2s.  c  om*/
 *
 * @param request  servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Sanity checks
    if (StringUtils.isBlank(request.getParameter("zoom")) || StringUtils.isBlank(request.getParameter("center"))
            || StringUtils.isBlank(request.getParameter("size"))) {
        throw new IllegalArgumentException("Must provide zoom, size and center parameters");
    }

    MapImageCtx ctx = new MapImageCtx();

    parseParams(ctx, request);
    if (useMapCache) {
        // use map cache, so check cache for map
        if (!checkMapCache(ctx)) {
            // map is not in cache, needs to be build
            BufferedImage image = makeMap(ctx);

            Path path = repositoryService.getRepoRoot().resolve(mapCacheIDToFilename(ctx));
            Files.createDirectories(path.getParent());
            ImageIO.write(image, "png", path.toFile());

            // And write to response
            sendHeader(response);
            ImageIO.write(image, "png", response.getOutputStream());

        } else {
            // map is in cache
            sendHeader(response);
            Path path = repositoryService.getRepoRoot().resolve(mapCacheIDToFilename(ctx));
            response.setContentLength((int) path.toFile().length());

            FileInputStream fileInputStream = new FileInputStream(path.toFile());
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                responseOutputStream.write(bytes);
            }
        }

    } else {
        // no cache, make map, send headers and deliver png
        BufferedImage image = makeMap(ctx);
        sendHeader(response);
        ImageIO.write(image, "png", response.getOutputStream());
    }
}

From source file:com.impetus.client.crud.datatypes.ByteDataTest.java

/**
 * On insert image in cassandra blob object
 * /*  www  . jav a  2  s  . c  om*/
 * @throws Exception
 *             the exception
 */
@Test
public void onInsertBlobImageCassandra() throws Exception {

    PersonCassandra personWithKey = new PersonCassandra();
    personWithKey.setPersonId("111");

    BufferedImage originalImage = ImageIO.read(new File("src/test/resources/nature.jpg"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(originalImage, "jpg", baos);
    baos.flush();
    byte[] imageInByte = baos.toByteArray();

    baos.close();

    personWithKey.setA(imageInByte);
    em.persist(personWithKey);

    em.clear();

    String qry = "Select p from PersonCassandra p where p.personId = 111";
    Query q = em.createQuery(qry);
    List<PersonCassandra> persons = q.getResultList();
    PersonCassandra person = persons.get(0);

    InputStream in = new ByteArrayInputStream(person.getA());
    BufferedImage bImageFromConvert = ImageIO.read(in);

    ImageIO.write(bImageFromConvert, "jpg", new File("src/test/resources/nature-test.jpg"));

    Assert.assertNotNull(person.getA());
    Assert.assertEquals(new File("src/test/resources/nature.jpg").getTotalSpace(),
            new File("src/test/resources/nature-test.jpg").getTotalSpace());
    Assert.assertEquals(String.valueOf(Hex.encodeHex((byte[]) imageInByte)),
            String.valueOf(Hex.encodeHex((byte[]) person.getA())));

}

From source file:common.AbstractGUI.java

protected void writePNG(JFreeChart jFreeChart, File snapshotDir, String name) {
    if (jFreeChart != null) {
        BufferedImage cpuImage = jFreeChart.createBufferedImage(833, 500);
        File cpuFile = new File(snapshotDir.getPath() + File.separatorChar + name);
        try {// w  w  w  . j  a v a 2s  .com
            ImageIO.write(cpuImage, "PNG", cpuFile);
        } catch (IOException e) {
            log(e.getMessage());
        }
    }
}

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);/*from w ww .j av  a2  s  . c om*/
    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:org.perfrepo.web.controller.reports.testgroup.TestGroupChartBean.java

public void drawChart(OutputStream out, Object data) throws IOException {
    if (data instanceof ChartData) {
        ChartData chartData = (ChartData) data;
        JFreeChart chart = ChartFactory.createBarChart(chartData.getTitle(), "Test", "%",
                processDataSet(chartData), PlotOrientation.HORIZONTAL, false, true, false);
        chart.addSubtitle(new TextTitle("Comparison", new Font("Dialog", Font.ITALIC, 10)));
        chart.setBackgroundPaint(Color.white);
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        CustomRenderer renderer = new CustomRenderer();

        plot.setBackgroundPaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        renderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator("{2}%", NumberFormat.getInstance()));
        renderer.setBaseItemLabelsVisible(true);
        renderer.setDrawBarOutline(false);
        renderer.setMaximumBarWidth(1d / (chartData.getTests().length + 4.0));
        plot.setRenderer(renderer);//from w  w w. j  a  v  a 2 s . c o  m

        CategoryAxis categoryAxis = plot.getDomainAxis();
        categoryAxis.setCategoryMargin(0.1);

        categoryAxis.setUpperMargin(0.1);
        categoryAxis.setLowerMargin(0.1);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        rangeAxis.setUpperMargin(0.10);
        BufferedImage buffImg = chart.createBufferedImage(640, chartData.getTests().length * 100 + 100);
        ImageIO.write(buffImg, "gif", out);
    }
}

From source file:bjerne.gallery.service.impl.ImageResizeServiceImpl.java

@Override
public void resizeImage(File origImage, File newImage, int width, int height) throws IOException {
    LOG.debug("Entering resizeImage(origImage={}, width={}, height={})", origImage, width, height);
    long startTime = System.currentTimeMillis();
    InputStream is = new BufferedInputStream(new FileInputStream(origImage));
    BufferedImage i = ImageIO.read(is);
    IOUtils.closeQuietly(is);/*ww  w. j av a2  s  . c  o m*/
    BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int origWidth = i.getWidth();
    int origHeight = i.getHeight();
    LOG.debug("Original size of image - width: {}, height={}", origWidth, height);
    float widthFactor = ((float) origWidth) / ((float) width);
    float heightFactor = ((float) origHeight) / ((float) height);
    float maxFactor = Math.max(widthFactor, heightFactor);
    int newHeight, newWidth;
    if (maxFactor > 1) {
        newHeight = (int) (((float) origHeight) / maxFactor);
        newWidth = (int) (((float) origWidth) / maxFactor);
    } else {
        newHeight = origHeight;
        newWidth = origWidth;
    }
    LOG.debug("Size of scaled image will be: width={}, height={}", newWidth, newHeight);
    int startX = Math.max((width - newWidth) / 2, 0);
    int startY = Math.max((height - newHeight) / 2, 0);
    Graphics2D scaledGraphics = scaledImage.createGraphics();
    scaledGraphics.setColor(backgroundColor);
    scaledGraphics.fillRect(0, 0, width, height);
    scaledGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    scaledGraphics.drawImage(i, startX, startY, newWidth, newHeight, null);
    OutputStream resultImageOutputStream = new BufferedOutputStream(FileUtils.openOutputStream(newImage));
    String extension = FilenameUtils.getExtension(origImage.getName());
    ImageIO.write(scaledImage, extension, resultImageOutputStream);
    IOUtils.closeQuietly(resultImageOutputStream);
    long duration = System.currentTimeMillis() - startTime;
    LOG.debug("Time in milliseconds to scale {}: {}", newImage.toString(), duration);
}

From source file:ImageUtils.java

/**
 * Saves an image to the disk.//from w ww  .  ja  v a 2  s  .  c  o  m
 * 
 * @param image  The image to save
 * @param toFileName The filename to use
 * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images,
 *  or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
 * @return <code>false</code> if no appropriate writer is found
 */
public static boolean saveImage(BufferedImage image, String toFileName, int type) {
    try {
        return ImageIO.write(image, type == IMAGE_JPEG ? "jpg" : "png", new File(toFileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.tdclighthouse.prototype.services.callbacks.ImageCreationCallBack.java

@Override
public String doInSession(Session session) throws RepositoryException {
    String result = null;//from  w  ww  .  ja v a  2 s.  co  m
    try {
        // FIXME refactor
        Node node = createImageSetNode(session, contentType);
        result = DocumentManager.getHandle(node).getIdentifier();
        String mimeType = new MimetypesFileTypeMap().getContentType(file);
        Node galleryProcessorService = session.getNode(PluginConstants.Paths.GALLERY_PROCESSOR_SERVICE);

        for (NodeIterator sizes = galleryProcessorService.getNodes(); sizes.hasNext();) {
            Node size = sizes.nextNode();
            if (size.isNodeType(PluginConstants.NodeType.FRONTEND_PLUGINCONFIG)) {
                Node subjectNode = getNode(node, size.getName(), PluginConstants.NodeType.HIPPOGALLERY_IMAGE);
                Long height = size.getProperty(PluginConstants.PropertyName.HEIGHT).getLong();
                Long width = size.getProperty(PluginConstants.PropertyName.WIDTH).getLong();
                BufferedImage bufferedImage = ImageIO.read(file);
                InputStream inputStream;
                if (height == 0 && width == 0) {
                    inputStream = new FileInputStream(file);
                    height = (long) bufferedImage.getHeight();
                    width = (long) bufferedImage.getWidth();
                } else {
                    ImageSize scaledSize = getScaledSize(height, width, bufferedImage);
                    BufferedImage scaledImage = ImageUtils.scaleImage(bufferedImage,
                            scaledSize.width.intValue(), scaledSize.height.intValue(),
                            ScalingStrategy.BEST_QUALITY);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    ImageIO.write(scaledImage, "jpg", byteArrayOutputStream);
                    byteArrayOutputStream.flush();
                    inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                    height = (long) scaledImage.getHeight();
                    width = (long) scaledImage.getWidth();
                }
                subjectNode.setProperty(PluginConstants.PropertyName.JCR_DATA,
                        session.getValueFactory().createBinary(inputStream));
                subjectNode.setProperty(PluginConstants.PropertyName.JCR_MIME_TYPE, mimeType);
                subjectNode.setProperty(PluginConstants.PropertyName.JCR_LAST_MODIFIED,
                        new GregorianCalendar());
                subjectNode.setProperty(PluginConstants.PropertyName.HIPPOGALLERY_HEIGHT, height);
                subjectNode.setProperty(PluginConstants.PropertyName.HIPPOGALLERY_WIDTH, width);
            }
        }

    } catch (IOException | WorkflowException e) {
        throw new RepositoryException(e);
    }
    return result;
}