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:com.uimirror.image.endpoint.UimImageEndPoint.java

@GET
@Produces(CONTENT_TYPE_IMAGE)/*from  w w  w.j a  va2s.  c  om*/
@Path(GET_PATH)
public Object getPicture(@BeanParam UimImageFormParam param) {

    boolean isExpiredToken = false;

    isExpiredToken = DateTimeUtil.isBefore(param.getToken());

    BufferedImage img = null;
    if (isExpiredToken) {
        return Response.status(Status.NOT_FOUND).build();
    } else {
        UimSnap transform = requestParamToUimSnapTransformer.transform(param);
        img = imageReadProcessor.invoke(transform);
        //getImageService().getImage(profPath, param.getSize(), param.getImage(), param.getFbt());

        byte[] imageData = null;

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(img, "png", baos);
            imageData = baos.toByteArray();

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

        ResponseBuilder rb = Response.ok(new ByteArrayInputStream(imageData)).status(200)
                .header(HttpHeaders.CONTENT_LENGTH, 1024).header("Content-type", "image/png");
        CacheControl cc = new CacheControl();
        cc.setMaxAge(CACHE_AGE);
        cc.setNoCache(false);
        return rb.cacheControl(cc).build();
    }
}

From source file:com.greenpepper.confluence.macros.historic.AbstractChartBuilder.java

@SuppressWarnings("deprecated")
protected String getDownloadPath(BufferedImage chartImage) throws IOException {
    File imageOutputFile = ExportDownload.createTempFile("chart", ".png");

    ImageIO.write(chartImage, "png", imageOutputFile);

    return ExportDownload.getUrl(imageOutputFile, "image/png");
}

From source file:net.pkhsolutions.pecsapp.boundary.PictureServiceBean.java

@Override
public @NotNull Optional<InputStream> downloadPictureForLayout(@NotNull PictureDescriptor descriptor,
        @NotNull PageLayout layout) {/* w  ww .  j  a va  2 s. c om*/
    LOGGER.debug("Downloading picture for descriptor {} and layout {}", descriptor, layout);
    try {
        Optional<BufferedImage> image = scalingPictureFileStorage.loadForLayout(descriptor, layout);
        if (image.isPresent()) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image.get(), descriptor.getMimeType().getSubtype(), baos);
            return Optional.of(new ByteArrayInputStream(baos.toByteArray()));
        } else {
            return Optional.empty();
        }
    } catch (IOException ex) {
        LOGGER.error("Error downloading picture", ex);
        throw new DownloadPictureException("Could not download picture", ex);
    }
}

From source file:apiserver.core.common.ResponseEntityHelper.java

/**
 * return a BufferedImage as byte[] array or as a base64 version of the image bytes
 * @param image/*from w w  w  .ja va 2  s . c o  m*/
 * @param contentType
 * @param returnAsBase64
 * @return
 * @throws java.io.IOException
        
public static ResponseEntity<byte[]> processImage(Object image, String contentType, Boolean returnAsBase64) throws IOException
{
HttpHeaders headers = new HttpHeaders();
        
// set content type
String convertToType = "jpg";
        
if(contentType == null )
{
    contentType = "jpg";
    contentType = contentType.toLowerCase();
}
        
        
if( contentType.contains("jpg") || contentType.contains("jpeg"))
{
    convertToType = "jpg";
    headers.setContentType(MediaType.IMAGE_JPEG);
}
else if( contentType.contains("png"))
{
    convertToType = "png";
    headers.setContentType(MediaType.IMAGE_PNG);
}
else if( contentType.contains("gif"))
{
    convertToType = "gif";
    headers.setContentType(MediaType.IMAGE_GIF);
}
else
{
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
}
        
        
        
if( image instanceof BufferedImage)
{
    //DataBufferByte bytes = (DataBufferByte)((BufferedImage) image).getRaster().getDataBuffer();
        
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write((BufferedImage) image, convertToType, baos);
    byte [] bytes = baos.toByteArray();
        
        
    if (!returnAsBase64)
    {
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
    }
    else
    {
        return new ResponseEntity<byte[]>(Base64.encode(bytes) , headers, HttpStatus.OK);
    }
}
else if(  image instanceof byte[]  )
{
    if (!returnAsBase64)
    {
        return new ResponseEntity<byte[]>( (byte[])image, headers, HttpStatus.OK);
    }
    else
    {
        return new ResponseEntity<byte[]>(Base64.encode((byte[])image) , headers, HttpStatus.OK);
    }
}
        
throw new RuntimeException("Invalid Image bytes");
}
 */

public static ResponseEntity<byte[]> processImage(BufferedImage image, String contentType,
        Boolean returnAsBase64) throws IOException {
    // set content type
    String convertToType = "png";

    if (contentType == null) {
        contentType = "application/octet-stream";
        contentType = contentType.toLowerCase();
    } else {
        convertToType = MimeType.getMimeType(contentType).getExtension();
    }

    //
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(contentType));

    if (returnAsBase64) {
        headers.set("Content-Transfer-Encoding", "base64");
    }

    if (image instanceof BufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, convertToType, baos);
        byte[] bytes = baos.toByteArray();

        return processFile(bytes, contentType, returnAsBase64);
    }
    throw new RuntimeException("Invalid Image bytes");
}

From source file:com.devbury.mkremote.server.QuickLaunchServiceImpl.java

public ArrayList<LaunchItem> list(String dir) {
    Base64 base64 = new Base64();
    JFileChooser chooser = new JFileChooser();
    File new_dir = newFileDir(dir);
    logger.debug("Looking for files in {}", new_dir.getAbsolutePath());
    ArrayList<LaunchItem> items = new ArrayList<LaunchItem>();
    if (isSupported()) {
        if (new_dir.isDirectory()) {
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return !name.startsWith(".");
                }//w ww. j  a  v a  2  s. c o  m
            };
            for (File f : new_dir.listFiles(filter)) {
                if (!f.isHidden()) {
                    LaunchItem item = new LaunchItem();
                    item.setName(f.getName());
                    item.setPath(dir);
                    if (f.isDirectory()) {
                        if (isMac() && f.getName().endsWith(".app")) {
                            item.setType(LaunchItem.FILE_TYPE);
                            item.setName(f.getName().substring(0, f.getName().length() - 4));
                        } else {
                            item.setType(LaunchItem.DIR_TYPE);
                        }
                    } else {
                        item.setType(LaunchItem.FILE_TYPE);
                    }
                    Icon icon = chooser.getIcon(f);
                    BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                            BufferedImage.TYPE_INT_RGB);
                    icon.paintIcon(null, bi.createGraphics(), 0, 0);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(bi, "png", os);
                        item.setIcon(base64.encodeToString(os.toByteArray()));
                    } catch (IOException e) {
                        logger.debug("could not write image {}", e);
                        item.setIcon(null);
                    }
                    logger.debug("Adding LaunchItem : {}", item);
                    items.add(item);
                } else {
                    logger.debug("Skipping hidden file {}", f.getName());
                }
            }
        }
    } else {
        new Thread() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null,
                        "We are sorry but quick launch is not supported on your platform",
                        "Quick Launch Not Supported", JOptionPane.ERROR_MESSAGE);
            }
        }.start();
    }
    return items;
}

From source file:com.hyeb.back.controller.CommonController.java

/**
 * ??/*from   w  ww  .  j ava 2 s  .  co m*/
 */
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtils.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }
    String pragma = new StringBuffer().append("PowderBy").toString();
    String value = new StringBuffer().append("hyeb").toString();
    response.addHeader(pragma, value);
    response.setHeader("Pragma", "no-cache");//HTTP1.0Pragma ??Pragmano-cache,??????? Pragma
    response.setHeader("Cache-Control", "no-cache");// HTTP1.1?Cache-Control ???,no-cache?????
    response.setHeader("Cache-Control", "no-store");//HTTP1.1?Cache-Control ???no-store????
    response.setDateHeader("Expires", 0);//Expires?GMT????????
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        BufferedImage bufferedImage = captchaService.buildImage(captchaId);
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}

From source file:com.netsteadfast.greenstep.bsc.command.PerspectivesDashboardExcelCommand.java

@SuppressWarnings("unchecked")
private int putCharts(XSSFWorkbook wb, XSSFSheet sh, Context context) throws Exception {
    String pieBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("pieCanvasToData"));
    String barBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("barCanvasToData"));
    BufferedImage pieImage = SimpleUtils.decodeToImage(pieBase64Content);
    BufferedImage barImage = SimpleUtils.decodeToImage(barBase64Content);
    ByteArrayOutputStream pieBos = new ByteArrayOutputStream();
    ImageIO.write(pieImage, "png", pieBos);
    pieBos.flush();//  ww  w  .  j a  va  2s  .  c o  m
    ByteArrayOutputStream barBos = new ByteArrayOutputStream();
    ImageIO.write(barImage, "png", barBos);
    barBos.flush();
    SimpleUtils.setCellPicture(wb, sh, pieBos.toByteArray(), 0, 0);
    SimpleUtils.setCellPicture(wb, sh, barBos.toByteArray(), 0, 9);
    int row = 21;

    List<Map<String, Object>> chartDatas = (List<Map<String, Object>>) context.get("chartDatas");
    String year = (String) context.get("year");

    XSSFCellStyle cellHeadStyle = wb.createCellStyle();
    cellHeadStyle.setFillForegroundColor(new XSSFColor(SimpleUtils.getColorRGB4POIColor("#f5f5f5")));
    cellHeadStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    XSSFFont cellHeadFont = wb.createFont();
    cellHeadFont.setBold(true);
    //cellHeadFont.setColor( new XSSFColor( SimpleUtils.getColorRGB4POIColor( "#000000" ) ) );      
    cellHeadStyle.setFont(cellHeadFont);

    int titleRow = row - 1;
    int titleCellSize = 14;
    Row headRow = sh.createRow(titleRow);
    for (int i = 0; i < titleCellSize; i++) {
        Cell headCell = headRow.createCell(i);
        headCell.setCellStyle(cellHeadStyle);
        headCell.setCellValue("Perspectives metrics gauge ( " + year + " )");
    }
    sh.addMergedRegion(new CellRangeAddress(titleRow, titleRow, 0, titleCellSize - 1));

    int cellLeft = 10;
    int rowSpace = 17;
    for (Map<String, Object> data : chartDatas) {
        Map<String, Object> nodeData = (Map<String, Object>) ((List<Object>) data.get("datas")).get(0);
        String pngImageData = SimpleUtils.getPNGBase64Content((String) nodeData.get("outerHTML"));
        BufferedImage imageData = SimpleUtils.decodeToImage(pngImageData);
        ByteArrayOutputStream imgBos = new ByteArrayOutputStream();
        ImageIO.write(imageData, "png", imgBos);
        imgBos.flush();
        SimpleUtils.setCellPicture(wb, sh, imgBos.toByteArray(), row, 0);

        XSSFColor bgColor = new XSSFColor(SimpleUtils.getColorRGB4POIColor((String) nodeData.get("bgColor")));
        XSSFColor fnColor = new XSSFColor(SimpleUtils.getColorRGB4POIColor((String) nodeData.get("fontColor")));

        XSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFillForegroundColor(bgColor);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        XSSFFont cellFont = wb.createFont();
        cellFont.setBold(true);
        cellFont.setColor(fnColor);

        cellStyle.setFont(cellFont);

        int perTitleCellSize = 4;
        Row nowRow = sh.createRow(row);
        for (int i = 0; i < perTitleCellSize; i++) {
            Cell cell1 = nowRow.createCell(cellLeft);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue((String) nodeData.get("name"));
        }
        sh.addMergedRegion(new CellRangeAddress(row, row, cellLeft, cellLeft + perTitleCellSize - 1));

        nowRow = sh.createRow(row + 1);
        Cell cell2 = nowRow.createCell(cellLeft);
        cell2.setCellValue("Target: " + String.valueOf(nodeData.get("target")));

        nowRow = sh.createRow(row + 2);
        Cell cell3 = nowRow.createCell(cellLeft);
        cell3.setCellValue("Min: " + String.valueOf(nodeData.get("min")));

        nowRow = sh.createRow(row + 3);
        Cell cell4 = nowRow.createCell(cellLeft);
        cell4.setCellValue("Score: " + String.valueOf(nodeData.get("score")));

        row += rowSpace;
    }

    return row;
}

From source file:com.od.jtimeseries.net.httpd.handler.ChartPngHandler.java

private NanoHttpResponse createImageResponse(Properties params, IdentifiableTimeSeries h) {
    NanoHttpResponse result;// ww w . j  a va2  s  . com

    MovingWindowXYDataset<IdentifiableTimeSeries> xyDataset = new MovingWindowXYDataset<IdentifiableTimeSeries>();
    xyDataset.addTimeSeries(h.getId(), h);

    JFreeChart chart = ChartFactory.createTimeSeriesChart(h.getId(), "Time", "Value", xyDataset, true, false,
            false);

    int width = Math.min(getIntegerParameter(params, "width", 500), MAX_HORIZONTAL_RESOLUTION);
    int height = Math.min(getIntegerParameter(params, "height", 300), MAX_VERTICAL_RESOLUTION);

    BufferedImage bi = chart.createBufferedImage(width, height);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ImageIO.write(bi, "png", bos);
    } catch (IOException e) {
        e.printStackTrace();
    }

    result = new InputStreamResponse(NanoHTTPD.HTTP_OK, "image/png",
            new ByteArrayInputStream(bos.toByteArray()));
    return result;
}

From source file:mvc.controller.UsuarioController.java

private void setImagePath(List<Usuario> listaUsuarios) throws IOException {

    for (Usuario usuario : listaUsuarios) {

        BufferedImage bImage = ImageIO.read(new File(usuario.getPhoto()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bImage, "jpg", baos);
        baos.flush();/*from   www . j av a  2 s  . c  o  m*/
        byte[] imageInByteArray = baos.toByteArray();
        baos.close();
        String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);
        usuario.setPhoto(b64);

    }

}

From source file:io.narayana.perf.product.BarChart.java

private void writeImageData(JFreeChart chart, String imageFileName, String formatName) throws IOException {
    BufferedImage objBufferedImage = chart.createBufferedImage(600, 300);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(objBufferedImage, "png", baos);
    byte[] byteArray = baos.toByteArray();
    InputStream in = new ByteArrayInputStream(byteArray);
    BufferedImage image = ImageIO.read(in);
    File outputfile = new File(imageFileName);

    ImageIO.write(image, formatName, outputfile);

    System.out.printf("GENERATED IMAGE FILE TO %s%n", outputfile.getCanonicalPath());
}