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:pt.ist.expenditureTrackingSystem.presentationTier.actions.statistics.ChartGenerator.java

protected static byte[] createBarChartImage(final ChartData chartData) throws RuntimeException, IOException {
    final JFreeChart chart = createBarChart(chartData.getDataset(), chartData.getTitle());
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final BufferedImage bufferedImage = chart.createBufferedImage(625, 475);
    ImageIO.write(bufferedImage, "png", outputStream);
    bufferedImage.flush();/*from   w w w.  jav a2  s . c  o  m*/
    outputStream.close();
    return outputStream.toByteArray();
}

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

public static JSONObject createThumbnail(File projectDir, File pyramidDir, String imageName,
        BufferedImage refImage) throws IOException, JSONException {
    final Path projectScope = projectDir.toPath();
    final BufferedImage tmbImage = toThumbnailSize(refImage);

    final File thumbnailDir = new File(pyramidDir.getParentFile(), ".thumbnail");
    thumbnailDir.mkdir();//  www  .ja v a 2  s.  c o  m
    final File refFile = File.createTempFile(imageName + ".", ".jpg", thumbnailDir);
    final File tmbFile = tmbImage != refImage ? File.createTempFile(imageName + ".tmb.", ".jpg", thumbnailDir)
            : refFile;

    final JSONObject thumbnail = new JSONObject();
    thumbnail.put("scope", "Project");
    thumbnail.put("width", tmbImage.getWidth());
    thumbnail.put("height", tmbImage.getHeight());
    thumbnail.put("src", toRef(projectScope, tmbFile.toPath()));
    ImageIO.write(refImage, "JPEG", refFile);
    if (tmbFile != refFile) {
        thumbnail.put("ref", toRef(projectScope, refFile.toPath()));
        ImageIO.write(tmbImage, "JPEG", tmbFile);
    }
    return thumbnail;
}

From source file:com.sunflower.petal.controller.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    log.debug("uploadPost called");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;//from  w ww .  j ava2  s. c o  m
    List<Image> list = new LinkedList<Image>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        log.debug("Uploading {}", mpf.getOriginalFilename());

        String newFilenameBase = UUID.randomUUID().toString();
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = newFilenameBase + originalFileExtension;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + newFilename);
        try {
            mpf.transferTo(newFile);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
            String thumbnailFilename = newFilenameBase + "-thumbnail.png";
            File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename);
            ImageIO.write(thumbnail, "png", thumbnailFile);

            Image image = new Image();
            image.setName(mpf.getOriginalFilename());
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image = imageService.create(image);

            image.setUrl("/picture/" + image.getId());
            image.setThumbnailUrl("/thumbnail/" + image.getId());
            image.setDeleteUrl("/delete/" + image.getId());
            image.setDeleteType("DELETE");

            list.add(image);

        } catch (IOException e) {
            log.error("Could not upload file " + mpf.getOriginalFilename(), e);
        }

    }

    Map<String, Object> files = new HashMap<String, Object>();
    files.put("files", list);
    return files;
}

From source file:com.esofthead.mycollab.module.ecm.service.impl.ResourceServiceImpl.java

@Override
public void saveContent(Content content, String createdUser, InputStream refStream, Integer sAccountId) {
    Integer fileSize = 0;/*from   w  ww.  j  a  v a 2 s  .c  o  m*/
    if (sAccountId != null) {
        try {
            fileSize = refStream.available();
            billingPlanCheckerService.validateAccountCanUploadMoreFiles(sAccountId, fileSize);
        } catch (IOException e) {
            LOG.error("Can not get available bytes", e);
        }
    }

    // detect mimeType and set to content
    String mimeType = MimeTypesUtil.detectMimeType(content.getPath());
    content.setMimeType(mimeType);
    content.setSize(Long.valueOf(fileSize));

    String contentPath = content.getPath();
    rawContentService.saveContent(contentPath, refStream);

    if (MimeTypesUtil.isImage(mimeType)) {
        try (InputStream newInputStream = rawContentService.getContentStream(contentPath)) {
            BufferedImage image = ImageUtil.generateImageThumbnail(newInputStream);
            if (image != null) {
                String thumbnailPath = String.format(".thumbnail/%d/%s.%s", sAccountId,
                        StringUtils.generateSoftUniqueId(), "png");
                File tmpFile = File.createTempFile("tmp", "png");
                ImageIO.write(image, "png", new FileOutputStream(tmpFile));
                rawContentService.saveContent(thumbnailPath, new FileInputStream(tmpFile));
                content.setThumbnail(thumbnailPath);
            }
        } catch (IOException e) {
            LOG.error("Error when generating thumbnail", e);
        }
    }

    contentJcrDao.saveContent(content, createdUser);

    SaveContentCommand saveContentCommand = CamelProxyBuilderUtil.build(EcmEndPoints.SAVE_CONTENT_ENDPOINT,
            SaveContentCommand.class);
    saveContentCommand.saveContent(content, createdUser, sAccountId);
}

From source file:inflor.core.utils.ChartUtils.java

public static byte[] renderChartToPNG(JFreeChart jfc, int x, int y) throws IOException {
    jfc.setBackgroundPaint(Color.WHITE);
    BufferedImage objBufferedImage = jfc.createBufferedImage(x, y);
    ByteArrayOutputStream bas = new ByteArrayOutputStream();
    ImageIO.write(objBufferedImage, "png", bas);
    return bas.toByteArray();
}

From source file:com.teasoft.teavote.controller.ElectionInfoController.java

@RequestMapping(value = "api/teavote/election-info", method = RequestMethod.POST)
@ResponseBody/*from w  ww  .j  ava 2 s  .  c  o m*/
public JSONResponse saveElectionInfo(@RequestParam("logo") MultipartFile file,
        @RequestParam("commissioner") String commissioner, @RequestParam("orgName") String orgName,
        @RequestParam("electionDate") String electionDate, @RequestParam("startTime") String startTime,
        @RequestParam("endTime") String endTime, @RequestParam("pollingStation") String pollingStation,
        @RequestParam("startTimeInMillis") String startTimeInMillis,
        @RequestParam("endTimeInMillis") String endTimeInMillis, HttpServletRequest request) throws Exception {

    JSONResponse jSONResponse = new JSONResponse();
    //Candidate candidate = new Candidate();
    Map<String, String> errorMessages = new HashMap<>();

    if (!file.isEmpty()) {
        BufferedImage image = ImageIO.read(file.getInputStream());
        Integer width = image.getWidth();
        Integer height = image.getHeight();

        if (Math.abs(width - height) > MAX_IMAGE_DIM_DIFF) {
            errorMessages.put("image", "Invalid Image Dimension - Max abs(Width - height) must be 50 or less");
        } else {
            //Resize image
            BufferedImage originalImage = ImageIO.read(file.getInputStream());
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

            BufferedImage resizeImagePng = resizeImage(originalImage, type);
            ConfigLocation configLocation = new ConfigLocation();
            //String rootPath = request.getSession().getServletContext().getRealPath("/");
            File serverFile = new File(configLocation.getConfigPath() + File.separator + "teavote-logo.jpg");

            switch (file.getContentType()) {
            case "image/png":
                ImageIO.write(resizeImagePng, "png", serverFile);
                break;
            case "image/jpeg":
                ImageIO.write(resizeImagePng, "jpg", serverFile);
                break;
            default:
                ImageIO.write(resizeImagePng, "png", serverFile);
                break;
            }
        }
    } else {
        //            errorMessages.put("image", "File Empty");
    }

    //Load properties
    Properties prop = appProp.getProperties();
    ConfigLocation configLocation = new ConfigLocation();
    prop.load(configLocation.getExternalProperties());

    prop.setProperty("teavote.orgName", orgName);
    prop.setProperty("teavote.commissioner", commissioner);
    prop.setProperty("teavote.electionDate", electionDate);
    prop.setProperty("teavote.startTime", startTime);
    prop.setProperty("teavote.endTime", endTime);
    prop.setProperty("teavote.pollingStation", pollingStation);
    prop.setProperty("teavote.startTimeInMillis", startTimeInMillis);
    prop.setProperty("teavote.endTimeInMillis", endTimeInMillis);

    File f = new File(configLocation.getConfigPath() + File.separator + "application.properties");
    OutputStream out = new FileOutputStream(f);
    DefaultPropertiesPersister p = new DefaultPropertiesPersister();
    p.store(prop, out, "Header Comment");

    if (errorMessages.isEmpty()) {
        return new JSONResponse(true, 0, null, Enums.JSONResponseMessage.SUCCESS.toString());
    }

    return new JSONResponse(false, 0, errorMessages, Enums.JSONResponseMessage.SERVER_ERROR.toString());
}

From source file:com.mycollab.module.ecm.service.impl.ResourceServiceImpl.java

@Override
public void saveContent(Content content, String createdUser, InputStream refStream, Integer sAccountId) {
    Integer fileSize = 0;// w w w. java 2  s . c o  m
    if (sAccountId != null) {
        try {
            fileSize = refStream.available();
            billingPlanCheckerService.validateAccountCanUploadMoreFiles(sAccountId, fileSize);
        } catch (IOException e) {
            LOG.error("Can not get available bytes", e);
        }
    }

    // detect mimeType and set to content
    String mimeType = MimeTypesUtil.detectMimeType(content.getPath());
    content.setMimeType(mimeType);
    content.setSize(Long.valueOf(fileSize));

    String contentPath = content.getPath();
    rawContentService.saveContent(contentPath, refStream);

    if (MimeTypesUtil.isImage(mimeType)) {
        try (InputStream newInputStream = rawContentService.getContentStream(contentPath)) {
            BufferedImage image = ImageUtil.generateImageThumbnail(newInputStream);
            if (image != null) {
                String thumbnailPath = String.format(".thumbnail/%d/%s.%s", sAccountId,
                        StringUtils.generateSoftUniqueId(), "png");
                File tmpFile = File.createTempFile("tmp", "png");
                ImageIO.write(image, "png", new FileOutputStream(tmpFile));
                rawContentService.saveContent(thumbnailPath, new FileInputStream(tmpFile));
                content.setThumbnail(thumbnailPath);
            }
        } catch (IOException e) {
            LOG.error("Error when generating thumbnail", e);
        }
    }

    contentJcrDao.saveContent(content, createdUser);

    SaveContentEvent event = new SaveContentEvent(content, createdUser, sAccountId);
    asyncEventBus.post(event);
}

From source file:com.igormaznitsa.mindmap.plugins.exporters.PNGImageExporter.java

@Override
public void doExport(@Nonnull final MindMapPanel panel, @Nullable final JComponent options,
        @Nullable final OutputStream out) throws IOException {
    for (final Component compo : Assertions.assertNotNull(options).getComponents()) {
        if (compo instanceof JCheckBox) {
            final JCheckBox cb = (JCheckBox) compo;
            if ("unfold".equalsIgnoreCase(cb.getActionCommand())) {
                flagExpandAllNodes = cb.isSelected();
            } else if ("back".equalsIgnoreCase(cb.getActionCommand())) {
                flagSaveBackground = cb.isSelected();
            }/*from w  w  w.  j  a  va2 s  .  c  o m*/
        }
    }

    final MindMapPanelConfig newConfig = new MindMapPanelConfig(panel.getConfiguration(), false);
    newConfig.setDrawBackground(flagSaveBackground);
    newConfig.setScale(1.0f);

    final RenderedImage image = MindMapPanel.renderMindMapAsImage(panel.getModel(), newConfig,
            flagExpandAllNodes);

    if (image == null) {
        if (out == null) {
            LOGGER.error("Can't render map as image");
            panel.getController().getDialogProvider(panel)
                    .msgError(Texts.getString("PNGImageExporter.msgErrorDuringRendering"));
            return;
        } else {
            throw new IOException("Can't render image");
        }
    }

    final ByteArrayOutputStream buff = new ByteArrayOutputStream(128000);
    ImageIO.write(image, "png", buff);//NOI18N

    final byte[] imageData = buff.toByteArray();

    File fileToSaveMap = null;
    OutputStream theOut = out;
    if (theOut == null) {
        fileToSaveMap = MindMapUtils.selectFileToSaveForFileFilter(panel,
                Texts.getString("PNGImageExporter.saveDialogTitle"), ".png",
                Texts.getString("PNGImageExporter.filterDescription"),
                Texts.getString("PNGImageExporter.approveButtonText"));
        fileToSaveMap = MindMapUtils.checkFileAndExtension(panel, fileToSaveMap, ".png");//NOI18N
        theOut = fileToSaveMap == null ? null
                : new BufferedOutputStream(new FileOutputStream(fileToSaveMap, false));
    }
    if (theOut != null) {
        try {
            IOUtils.write(imageData, theOut);
        } finally {
            if (fileToSaveMap != null) {
                IOUtils.closeQuietly(theOut);
            }
        }
    }
}

From source file:com.aquest.emailmarketing.web.controllers.TrackingController.java

/**
 * Gets the image./*w ww.j a  va 2  s  .  com*/
 *
 * @param request the request
 * @param response the response
 * @param trackingId the tracking id
 * @return the image
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws TransformerException the transformer exception
 * @throws ServletException the servlet exception
 * @throws FileUploadException the file upload exception
 */
@RequestMapping(value = "/openTrack", method = RequestMethod.GET)
public void getImage(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("trackingId") String trackingId) throws IOException, FileNotFoundException,
        ParserConfigurationException, TransformerException, ServletException, FileUploadException {
    BufferedImage pixel;
    Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());

    EmailList emailList = emailListService.getEmailListById(trackingId);
    TrackingResponse trackingResponse = new TrackingResponse();
    trackingResponse.setBroadcast_id(emailList.getBroadcast_id());
    trackingResponse.setEmail(emailList.getEmail());
    trackingResponse.setResponse_type("Open");
    trackingResponse.setUnique_id(emailList.getId());
    trackingResponse.setResponse_source("Internal Tracking");
    trackingResponse.setResponse_time(curTimestamp);
    trackingResponse.setProcessed_dttm(curTimestamp);
    trackingResponseService.SaveOrUpdate(trackingResponse);

    System.out.println(trackingId);
    // dodati logiku za ubacivanje response-a.

    pixel = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    pixel.setRGB(0, 0, (0xFF));

    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(pixel, "png", os);
    System.out.println("Neko je pristupio!!!");
}

From source file:org.optaplanner.benchmark.impl.statistic.ProblemStatistic.java

protected File writeChartToImageFile(JFreeChart chart, String fileNameBase) {
    BufferedImage chartImage = chart.createBufferedImage(1024, 768);
    File chartFile = new File(problemBenchmarkResult.getProblemReportDirectory(), fileNameBase + ".png");
    OutputStream out = null;//ww w. j  a  v a  2 s  .c  om
    try {
        out = new FileOutputStream(chartFile);
        ImageIO.write(chartImage, "png", out);
    } catch (IOException e) {
        throw new IllegalArgumentException("Problem writing chartFile: " + chartFile, e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return chartFile;
}