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:org.shredzone.cilla.admin.AbstractImageBean.java

/**
 * Creates a {@link StreamedContent} for the given {@link DataHandler}, with the image
 * having the given width and height. The aspect ratio is kept. A PNG type image is
 * returned.// w  ww.j  a  v a2  s .  c o  m
 * <p>
 * <em>NOTE:</em> The scaled image is cached related to the {@link DataHandler}. Thus,
 * it is not possible to create different sizes of the same {@link DataHandler} using
 * this method. A weak cache is used, to keep the memory footprint as small as
 * possible.
 *
 * @param dh
 *            {@link DataHandler} to stream
 * @param process
 *            Width, height and image type to be used
 * @return {@link StreamedContent} containing that image
 */
protected StreamedContent createStreamedContent(DataHandler dh, ImageProcessing process) {
    byte[] scaledData = null;
    if (dh != null) {
        scaledData = weakScaleCache.get(dh);
        if (scaledData == null) {
            try {
                BufferedImage image = ImageIO.read(dh.getInputStream());
                if (image != null) {
                    BufferedImage scaled = scale(image, process.getWidth(), process.getHeight());
                    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                        ImageIO.write(scaled, process.getType().getFormatName(), bos);
                        scaledData = bos.toByteArray();
                    }
                    if (weakScaleCache.size() < maxCache) {
                        weakScaleCache.put(dh, scaledData);
                    }
                }
            } catch (IOException ex) {
                log.error("Exception while streaming scaled content: " + dh.getName(), ex);
            }
        }
    }

    if (scaledData != null) {
        return new DefaultStreamedContent(new ByteArrayInputStream(scaledData),
                process.getType().getContentType());
    } else {
        return createEmptyStreamedContent();
    }
}

From source file:edu.osu.netmotifs.warswap.ui.GenerateMotifImages.java

public void generateImagesSize3(Graph<Integer, String> g, String fileName) {
    Transformer<Integer, Point2D> locationTransformer = new TransformerMotif(motifSize);
    Layout<Integer, String> layout = new StaticLayout<Integer, String>(g, locationTransformer);
    layout.setSize(new Dimension(100, 100));
    BasicVisualizationServer<Integer, String> vv = new BasicVisualizationServer<Integer, String>(layout);
    vv.setPreferredSize(new Dimension(120, 120));
    Transformer<Integer, Paint> vertexPaint = new Transformer<Integer, Paint>() {
        public Paint transform(Integer i) {
            return colPerGraphHash.get(i);
        }//  w  w w .j  a v a 2  s.  co  m
    };
    Transformer<Integer, Paint> vertexDrawPaint = new Transformer<Integer, Paint>() {
        public Paint transform(Integer i) {
            return colPerGraphHash.get(i);
        }
    };
    Transformer<Integer, Shape> vertexSize = new Transformer<Integer, Shape>() {
        public Shape transform(Integer i) {
            Ellipse2D circle = new Ellipse2D.Double(-10, -10, 20, 20);
            return AffineTransform.getScaleInstance(0.6, 0.6).createTransformedShape(circle);
        }
    };
    vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
    vv.getRenderContext().setVertexDrawPaintTransformer(vertexDrawPaint);
    vv.getRenderContext().setVertexShapeTransformer(vertexSize);

    JPanel jPanel = new JPanel();
    jPanel.add(vv);
    BufferedImage bufImage = null;
    bufImage = ScreenImage.createImage((JComponent) jPanel);

    imageOutFile = imagesOutDir + CONF.DIR_SEP + fileName + ".png";
    relativePathToImage = "images" + CONF.DIR_SEP + fileName + ".png";
    try {
        File outFile = new File(imageOutFile);
        ImageIO.write(bufImage, "png", outFile);
        //         System.out.println("wrote image to " + outFile);
    } catch (Exception e) {
        System.err.println("writeToImageFile(): " + e.getMessage());
    }
}

From source file:com.lixiaocong.rest.FileController.java

@RequestMapping(value = "/imagecode")
public void imagecode(HttpSession session, HttpServletResponse response) throws IOException {
    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(codeService.getImage(session), "png", os);
}

From source file:guru.bubl.service.resources.vertex.VertexImageResource.java

private byte[] resizeImageToMaxWidth(File image, Integer width) {
    try {//from   w  ww  . j  av  a2 s  .c  o  m
        BufferedImage originalImage = ImageIO.read(image);
        originalImage = originalImage.getWidth() > width
                ? Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_WIDTH, width, width)
                : ImageIO.read(image);
        //To save with original ratio uncomment next line and comment the above.
        //originalImage= Scalr.resize(originalImage, 153, 128);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(originalImage, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();
        return imageInByte;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.adorsys.jwebsane.controller.WebsaneController.java

public void scan() {
    try {/*ww w.j  a v  a2s .co m*/
        openDevice();
        scanOptionsBean.getDevice().getOption(OptionConstants.RESOLUTION)
                .setIntegerValue(scanOptionsBean.getDpi());
        setScanArea(scanOptionsBean.getTopLx(), scanOptionsBean.getTopLy(), scanOptionsBean.getBottomRx(),
                scanOptionsBean.getBottomRy());
        scanOptionsBean.getDevice().getOption(OptionConstants.MODE).setStringValue(scanOptionsBean.getMode());
        File outputfile = File.createTempFile("scan", "png");
        BufferedImage image = scanOptionsBean.getDevice().acquireImage();

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        response.setContentType("image/png");
        response.setHeader("Content-disposition", "attachment; filename=\"name.png\"");

        // Write file to response.
        OutputStream output = response.getOutputStream();
        ImageIO.write(image, "png", output);

        // Inform JSF to not take the response in hands.
        facesContext.responseComplete(); //
        log.debug("Scan image written in: " + outputfile.getAbsolutePath());
    } catch (Exception e) {
        log.error(e);
    } finally {
        closeDevice();
    }
}

From source file:com.comcast.video.dawg.show.video.VideoSnapTest.java

@Test
public void testSaveSnappedImage() throws IOException {
    String deviceId = "000000000001";
    MockHttpSession session = new MockHttpSession();
    MockHttpServletResponse response = new MockHttpServletResponse();
    UniqueIndexedCache<BufferedImage> imgCache = ClientCache.getClientCache(session).getImgCache();
    String imageId = imgCache.storeItem(PC_IMG);

    VideoSnap videoSnap = new VideoSnap();
    videoSnap.saveSnappedImage(imageId, deviceId, response, session);

    String header = response.getHeader("Content-Disposition");
    Assert.assertTrue(header.contains("attachment"), "Response header does not indicates attachment");
    Assert.assertTrue(header.contains(".jpg"), "Attached file is not in jpg format");

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    ImageIO.write(PC_IMG, "jpg", bao);
    Assert.assertEquals(response.getContentAsByteArray(), bao.toByteArray(),
            "Saved image size is not matching with expected size");
}

From source file:com.htmlhifive.pitalium.core.io.FilePersister.java

@Override
public void saveDiffImage(PersistMetadata metadata, BufferedImage image) {
    File file = checkParentFileAvailable(getDiffImageFile(metadata));
    LOG.debug("[Save diff image] ({})", file);
    LOG.trace("[Save diff image] ({})]", metadata);
    try {//  ww w  .j av a  2s  .c o  m
        ImageIO.write(image, "png", file);
    } catch (IOException e) {
        LOG.debug("Failed to save diff image.", e);
        throw new TestRuntimeException(e);
    }
}

From source file:utilities.itext.Turnover.java

private static Image createPieChart(HashMap<String, BigDecimal> map, String title) throws Exception {
    DefaultPieDataset data = new DefaultPieDataset();

    for (String key : map.keySet()) {
        data.setValue(key, map.get(key).doubleValue());
    }/*  ww w .  j a  va 2  s . c  om*/

    JFreeChart pieChart = ChartFactory.createPieChart(title, data, true, false, Locale.GERMAN);
    //        PiePlot plot = (PiePlot) pieChart.getPlot();
    //        plot.setLabelGenerator(null);

    BufferedImage pie = pieChart.createBufferedImage(500, 500);
    File tempPie = File.createTempFile("png", null);
    ImageIO.write(pie, "png", tempPie);
    Image img = Image.getInstance(tempPie.getPath());

    return img;
}