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.igame.app.controller.Image2Controller.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    // HttpSession
    SecUser user = (SecUser) request.getSession().getAttribute("user");
    long appid = user.getAppid();
    log.debug("uploadPost called appid:{}" + appid);
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;//from   w  w  w  . j a  v  a  2  s .com
    List<Image> list = new LinkedList<>();

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

        long id = IDGenerator.getKey();
        // String newFilenameBase = String.valueOf(id);
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = id + originalFileExtension;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + "app-" + appid + "/" + newFilename);

        if (!newFile.getParentFile().exists()) {
            log.debug(" {}" + newFile.getParentFile().getPath());
            newFile.getParentFile().mkdirs();
        }

        try {
            mpf.transferTo(newFile);

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

            Image image = new Image();
            image.setId(id);
            image.setAppid(appid);
            image.setName(mpf.getOriginalFilename());
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image.setThumbnailSize(thumbnailFile.length());
            image = imageService.create(image);

            image.setUrl("app-" + appid + "/" + newFilename);
            image.setThumbnailUrl("app-" + appid + "/" + thumbnailFilename);
            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<>();
    files.put("files", list);
    return files;
}

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

/**
 * Retrieve the image with input image id from cache and stores it in output
 * stream./* w  w w  . j ava 2 s  .  c o m*/
 *
 * @param imgId
 *            Id of captured image
 * @param deviceId
 *            Device mac address
 * @param response
 *            httpservelet response
 * @param session
 *            http sssion
 * @throws IOException
 */
public void saveSnappedImage(String imgId, String deviceId, HttpServletResponse response, HttpSession session)
        throws IOException {

    String suffixName = getCurrentDateAndTime();
    String fileName = deviceId.toUpperCase() + "_" + suffixName + "." + IMG_FORMAT;

    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    BufferedImage img = imgCache.getItem(imgId);
    if (img != null) {
        OutputStream stream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(img, IMG_FORMAT, byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        stream.write(bytes);
        response.flushBuffer();
    } else {
        LOGGER.error("Could not retrieve the captured image!!!");
    }

}

From source file:com.ixxus.IxxusAbstractTest.java

public void saveOsScreenShot(String methodName) throws IOException, AWTException {
    Robot robot = new Robot();
    BufferedImage screenShot = robot
            .createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    ImageIO.write(screenShot, "png", new File("target/webdriver-" + methodName + "_OS" + ".png"));
}

From source file:org.gallery.web.controller.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response)
        throws IOException {
    log.info("UploadPost called...");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;/*w  ww  .  ja  v a  2s  .  c om*/
    List<ImageVO> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        String originalFilename = mpf.getOriginalFilename();
        if (originalFilename == null || StringUtils.isEmpty(originalFilename)) {
            originalFilename = UUID.randomUUID().toString() + ".jpg";
        }
        log.info("Uploading {}", originalFilename);

        String newFilenameBase = "-" + UUID.randomUUID().toString();
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();
        if (contentType == null || StringUtils.isEmpty(contentType)) {
            contentType = "image/jpeg";
        }
        String newFilename = newFilenameBase;
        InputStream in = null;
        try {
            // Save Images
            // mpf.transferTo(newFile);
            in = new ByteArrayInputStream(mpf.getBytes());
            BufferedImage originalImage = ImageIO.read(in);

            // Save Original Image
            String filenameExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1,
                    originalFilename.length());
            ImageIO.write(originalImage, filenameExtension,
                    new File(storageDirectory + File.separatorChar + originalFilename));

            // Small Thumbnails
            BufferedImage thumbnail_small = Scalr.resize(originalImage, ThumbnailSize.SMALL_SIZE.getSize());
            compressImg(thumbnail_small,
                    new File(storageDirectory + File.separatorChar + ThumbnailSize.SMALL_SIZE.getId()
                            + newFilenameBase + "." + ThumbnailSize.SMALL_SIZE.getFormatName()),
                    ThumbnailSize.SMALL_SIZE.getCompressionQuality());

            // Medium Thumbnail
            BufferedImage thumbnail_medium = Scalr.resize(originalImage, ThumbnailSize.MEDIUM_SIZE.getSize());
            compressImg(thumbnail_medium,
                    new File(storageDirectory + File.separatorChar + ThumbnailSize.MEDIUM_SIZE.getId()
                            + newFilenameBase + "." + ThumbnailSize.MEDIUM_SIZE.getFormatName()),
                    ThumbnailSize.MEDIUM_SIZE.getCompressionQuality());

            // Big Thumbnails
            BufferedImage thumbnail_big = Scalr.resize(originalImage, ThumbnailSize.BIG_SIZE.getSize());
            compressImg(thumbnail_big,
                    new File(storageDirectory + File.separatorChar + ThumbnailSize.BIG_SIZE.getId()
                            + newFilenameBase + "." + ThumbnailSize.BIG_SIZE.getFormatName()),
                    ThumbnailSize.BIG_SIZE.getCompressionQuality());

            log.info("EmotionParser...");
            // ImageEntity entity =
            // EmotionParser.parse(ImageIO.read(newFile));
            ImageEntity entity = new ImageEntity();
            entity.setName(originalFilename);
            entity.setNewFilename(newFilename);
            entity.setContentType(contentType);
            entity.setSize(mpf.getSize());
            imageDao.save(entity);

            ImageVO imageVO = new ImageVO(entity);
            imageVO.setId(entity.getId());
            imageVO.setUrl("/picture/" + entity.getId());
            imageVO.setThumbnailUrl("/thumbnail/" + entity.getId());
            imageVO.setDeleteUrl("/delete/" + entity.getId());
            imageVO.setEmotionUrl("/emotion/" + entity.getId());
            imageVO.setDeleteType("DELETE");

            list.add(imageVO);
        } catch (IOException e) {
            log.error("Could not upload file " + originalFilename, e);
        } finally {
            in.close();
        }
    }
    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadVideoRequest.java

/**
 * Configures the thumbnails for the given uploadId
 * @param uploadId The session id/* ww w . j a v a2s  . c om*/
 * @return Result
 * @throws Exception
 * @throws IOException
 * @throws ClientProtocolException
 */
protected StatusResult configureThumbnail(String uploadId)
        throws Exception, IOException, ClientProtocolException {
    try (FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(videoFile)) {
        frameGrabber.start();
        Java2DFrameConverter converter = new Java2DFrameConverter();

        int width = frameGrabber.getImageWidth();
        int height = frameGrabber.getImageHeight();
        long length = frameGrabber.getLengthInTime();

        BufferedImage bufferedImage;
        if (thumbnailFile == null) {
            bufferedImage = MyImageUtils.deepCopy(converter.convert(frameGrabber.grabImage()));
            thumbnailFile = File.createTempFile("insta", ".jpg");

            log.info("Generated thumbnail: " + thumbnailFile.getAbsolutePath());
            ImageIO.write(bufferedImage, "JPG", thumbnailFile);
        } else {
            bufferedImage = ImageIO.read(thumbnailFile);
        }

        holdOn();

        StatusResult thumbnailResult = api
                .sendRequest(new InstagramUploadPhotoRequest(thumbnailFile, caption, uploadId));
        log.info("Thumbnail result: " + thumbnailResult);

        StatusResult configureResult = api.sendRequest(InstagramConfigureVideoRequest.builder()
                .uploadId(uploadId).caption(caption).duration(length).width(width).height(height).build());

        log.info("Video configure result: " + configureResult);

        return configureResult;
    }
}

From source file:cmsc105_mp2.Panels.java

public void createGraph(Data d, float window, Double threshold) {
    XYSeries data = new XYSeries("data");
    double max = Double.MIN_VALUE;
    for (double num : d.plots) {
        if (max < num)
            max = num;//from ww w  .  j  a  va  2 s . c  om
    }
    max += 1;

    ArrayList<XYSeries> xy = new ArrayList();
    ArrayList<Integer> points = new ArrayList();

    for (int j = (int) (window / 2); j < d.plots.length - (window / 2); j++) {
        data.add(j, d.plots[j]);
        //System.out.println(points.size());
        if (d.plots[j] > threshold) {
            points.add(j);
        } else {
            if (points.size() >= window) {
                //System.out.println("MIN!");
                XYSeries series = new XYSeries("trend");
                for (int n : points) {
                    series.add(n, max);
                }
                xy.add(series);
            }
            points = new ArrayList();
        }
    }
    if (points.size() >= window) {
        XYSeries series = new XYSeries("trend");
        for (int n : points) {
            series.add(n, max);
        }
        xy.add(series);
    }
    XYSeriesCollection my_data_series = new XYSeriesCollection();
    my_data_series.addSeries(data);
    for (XYSeries x : xy) {
        my_data_series.addSeries(x);
    }

    XYSeries thresh = new XYSeries("threshold");
    for (int j = 0; j < d.plots.length; j++) {
        thresh.add(j, threshold);
    }
    my_data_series.addSeries(thresh);

    //System.out.println(d.name);
    JFreeChart XYLineChart = ChartFactory.createXYLineChart(d.name, "Position", "Average", my_data_series,
            PlotOrientation.VERTICAL, true, true, false);
    bImage1 = (BufferedImage) XYLineChart.createBufferedImage(690, 337);
    imageIcon = new ImageIcon(bImage1);
    jLabel1.setIcon(imageIcon);
    jLabel1.revalidate();
    jLabel1.repaint();
    jButton1.setText("Save as PNG");
    jButton1.repaint();
    jButton1.revalidate();
    jButton1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("Documents"));
            int retrival = chooser.showSaveDialog(null);
            if (retrival == JFileChooser.APPROVE_OPTION) {
                try {
                    ImageIO.write(bImage1, "png", new File(chooser.getSelectedFile() + ".png"));
                } catch (IOException ex) {
                    System.out.println("Unable to Print!");
                }
            }
        }
    });
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG2000 encoded bytestream
 *
 * @param bi//from   w  ww .  j a v a 2 s . c  o m
 * @return
 * @throws IOException
 */
public static byte[] encodeBufferedImageAsJP2(BufferedImage bi) throws IOException {

    byte[] byteStream = null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    ImageIO.write(bi, "jpeg2000", baos);
    baos.flush();
    byteStream = baos.toByteArray();
    baos.close();

    return byteStream;
}

From source file:org.sakuli.services.receiver.database.dao.impl.DaoTestCaseImpl.java

@Deprecated
@Override/*from  ww w.j  a  va 2s  .  co  m*/
public File getScreenShotFromDB(int dbPrimaryKey) {
    try {
        List l = getJdbcTemplate().query("select id, screenshot from sahi_cases where id=" + dbPrimaryKey,
                new RowMapper() {
                    public Object mapRow(ResultSet rs, int i) throws SQLException {
                        Map results = new HashMap();
                        InputStream blobBytes = lobHandler.getBlobAsBinaryStream(rs, "screenshot");
                        results.put("BLOB", blobBytes);
                        return results;
                    }
                });
        HashMap<String, InputStream> map = (HashMap<String, InputStream>) l.get(0);

        //ByteArrayInputStream in = new ByteArrayInputStream(map.get("BLOB"));
        BufferedImage picBuffer = ImageIO.read(map.get("BLOB"));
        File png = new File(testSuite.getAbsolutePathOfTestSuiteFile().substring(0,
                testSuite.getAbsolutePathOfTestSuiteFile().lastIndexOf(File.separator)) + File.separator
                + "temp_junit_test.png");
        png.createNewFile();
        ImageIO.write(picBuffer, "png", png);

        png.deleteOnExit();
        return png;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.groupdocs.viewer.samples.spring.model.Utilities.java

/**
 * Save the rendered images at disk//  w  w w  .  ja  v a 2 s.  com
 * @param path         the path
 * @param imageName    Save as provided string
 * @param imageContent stream of image contents
 */
public static void saveAsImage(String path, String imageName, InputStream imageContent) {
    try {
        //ExStart:SaveAsImage
        // extract the image from stream
        BufferedImage img = ImageIO.read(imageContent);
        //save the image in the form of jpeg
        ImageIO.write(img, "png", Utilities.makeImagePath(path, imageName));
        //ExEnd:SaveAsImage
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.truven.report.reporter.Reporter.java

/**
 * Save screen shot.//  w w  w .  j  a  v a  2s . co m
 *
 * @param reportFolderLocation the report folder location
 * @return the string
 */
private String saveScreenShot(final String reportFolderLocation) {

    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
    String timestamp = sdf.format(date);
    Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture;
    String screenShotFile = timestamp + ".png";
    String screenShotImgFolder = reportFolderLocation + File.separator + "images";
    try {
        capture = new Robot().createScreenCapture(screenRect);
        File screenShotImgFolderFile = new File(screenShotImgFolder);

        if (!screenShotImgFolderFile.exists() && !screenShotImgFolderFile.mkdirs()) {

            throw new RuntimeException(
                    "Cannot create new folder in location " + screenShotImgFolderFile.getAbsolutePath());
        }
        File screenShotImg = new File(screenShotImgFolder + File.separator + screenShotFile);
        ImageIO.write(capture, "png", screenShotImg);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (AWTException e1) {
        e1.printStackTrace();
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    return screenShotFile;
}