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.mirth.connect.server.util.DICOMUtil.java

private static String returnOtherImageFormat(MessageObject message, String format, boolean autoThreshold) {
    // use new method for jpegs
    if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg")) {
        return new String(Base64.encodeBase64Chunked(dicomToJpg(1, message, autoThreshold)));
    }//w w w  . j a  v a2 s  .c  om

    byte[] rawImage = Base64.decodeBase64(getDICOMRawData(message).getBytes());
    ByteArrayInputStream bais = new ByteArrayInputStream(rawImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        DICOM dicom = new DICOM(bais);
        dicom.run(message.getType());
        BufferedImage image = new BufferedImage(dicom.getWidth(), dicom.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.createGraphics();
        graphics.drawImage(dicom.getImage(), 0, 0, null);
        graphics.dispose();
        ImageIO.write(image, format, baos);
        return new String(Base64.encodeBase64Chunked(baos.toByteArray()));
    } catch (IOException e) {
        logger.error("Error Converting DICOM image", e);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
    }

    return StringUtils.EMPTY;
}

From source file:ac.kaist.ccs.presentation.CCSHubSelectionCost.java

public CCSHubSelectionCost(final String title, Map<Integer, List<Double>> data) {

    super(title);
    this.title = title;
    final XYDataset dataset = createDataset(data);
    final JFreeChart chart = createChart(dataset);
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    final ChartPanel chartPanel = new ChartPanel(chart);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BorderLayout());
    JButton buttonExport = new JButton("Export");
    buttonPanel.add("East", buttonExport);
    buttonExport.addActionListener(new ActionListener() {
        ChartPanel chartPanel;//www . j a va  2s . c  o  m

        public ActionListener init(ChartPanel chartPanel) {
            this.chartPanel = chartPanel;
            return this;
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            Dimension size = chartPanel.getSize();

            try {
                //String outPath = textFieldSelectPath.getText();
                //String filename = "chromatography.png";
                //String path = outPath+"/"+filename;
                JFileChooser fileChooser = new JFileChooser();

                fileChooser.setCurrentDirectory(new File("/Users/mac/Desktop"));

                fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JPEG", "jpeg"));

                int returnVal = fileChooser.showDialog(new JFrame(), "Open File Path");

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    String inputPath = fileChooser.getSelectedFile().getAbsolutePath();
                    if (!inputPath.endsWith(".jpeg"))
                        inputPath = inputPath + ".jpeg";

                    OutputStream os = new FileOutputStream(inputPath);
                    System.out.println(inputPath + "///" + size.width + " " + size.height);
                    BufferedImage chartImage = chartPanel.getChart().createBufferedImage(size.width,
                            size.height, null);
                    ImageIO.write(chartImage, "png", os);
                    os.close();
                    JOptionPane.showMessageDialog(null, "Chart image was saved in " + inputPath);

                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }.init(chartPanel));

    panel.add("Center", chartPanel);
    panel.add("South", buttonPanel);

    chartPanel.setPreferredSize(new java.awt.Dimension(700, 500));
    setContentPane(panel);

}

From source file:ac.kaist.ccs.presentation.CCSHubSelectionCo2Coverage.java

public CCSHubSelectionCo2Coverage(final String title, List<Double> coverSourceNum) {

    super(title);
    this.title = title;
    final XYDataset dataset = createDataset(coverSourceNum);
    final JFreeChart chart = createChart(dataset);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    final ChartPanel chartPanel = new ChartPanel(chart);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BorderLayout());
    JButton buttonExport = new JButton("Export");
    buttonPanel.add("East", buttonExport);
    buttonExport.addActionListener(new ActionListener() {
        ChartPanel chartPanel;/*from   ww w . jav  a  2 s .  co m*/

        public ActionListener init(ChartPanel chartPanel) {
            this.chartPanel = chartPanel;
            return this;
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            Dimension size = chartPanel.getSize();

            try {
                //String outPath = textFieldSelectPath.getText();
                //String filename = "chromatography.png";
                //String path = outPath+"/"+filename;
                JFileChooser fileChooser = new JFileChooser();

                fileChooser.setCurrentDirectory(new File("/Users/mac/Desktop"));

                fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JPEG", "jpeg"));

                int returnVal = fileChooser.showDialog(new JFrame(), "Open File Path");

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    String inputPath = fileChooser.getSelectedFile().getAbsolutePath();
                    if (!inputPath.endsWith(".jpeg"))
                        inputPath = inputPath + ".jpeg";

                    OutputStream os = new FileOutputStream(inputPath);
                    System.out.println(inputPath + "///" + size.width + " " + size.height);
                    BufferedImage chartImage = chartPanel.getChart().createBufferedImage(size.width,
                            size.height, null);
                    ImageIO.write(chartImage, "png", os);
                    os.close();
                    JOptionPane.showMessageDialog(null, "Chart image was saved in " + inputPath);

                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }.init(chartPanel));

    panel.add("Center", chartPanel);
    panel.add("South", buttonPanel);

    chartPanel.setPreferredSize(new java.awt.Dimension(700, 500));
    setContentPane(panel);

}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductImages.java

@Override
public void run(final Product product) {
    if (ImageIO.getUseCache())
        ImageIO.setUseCache(false);

    DrbNode node = null;/*from   w  ww  .  ja  v  a  2 s  .  c o m*/
    URL url = product.getPath();

    // Prepare the DRb node to be processed
    try {
        // First : force loading the model before accessing items.
        @SuppressWarnings("unused")
        DrbCortexModel model = DrbCortexModel.getDefaultModel();
        node = ProcessingUtils.getNodeFromPath(url.getPath());

        if (node == null) {
            throw new IOException("Cannot Instantiate Drb with URI \"" + url.toExternalForm() + "\".");
        }

    } catch (Exception e) {
        logger.error("Exception raised while processing Quicklook", e);
        return;
    }

    if (!ImageFactory.isImage(node)) {
        logger.debug("No Image.");
        return;
    }

    RenderedImageList input_list = null;
    RenderedImage input_image = null;
    try {
        input_list = ImageFactory.createImage(node);
        input_image = RenderingFactory.createDefaultRendering(input_list);
    } catch (Exception e) {
        logger.debug("Cannot retrieve default rendering");
        if (logger.isDebugEnabled()) {
            logger.debug("Error occurs during rendered image reader", e);
        }

        if (input_list == null)
            return;
        input_image = input_list;
    }

    int quicklook_width = cfgManager.getProductConfiguration().getQuicklookConfiguration().getWidth();
    int quicklook_height = cfgManager.getProductConfiguration().getQuicklookConfiguration().getHeight();
    boolean quicklook_cutting = cfgManager.getProductConfiguration().getQuicklookConfiguration().isCutting();

    logger.info("Generating Quicklook " + quicklook_width + "x" + quicklook_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight());

    RenderedImage image = ProcessingUtils.ResizeImage(input_image, quicklook_width, quicklook_height, 10f,
            quicklook_cutting);

    String product_id = product.getIdentifier();
    if (product_id == null)
        product_id = "unknown";

    // Manages the quicklook output
    File image_directory = incomingManager.getNewIncomingPath();

    LockFactory lf = new NativeFSLockFactory(image_directory);
    Lock lock = lf.makeLock(".lock-writing");
    try {
        lock.obtain(900000);
    } catch (Exception e) {
        logger.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")");
    }
    File file = new File(image_directory, product_id + "-ql.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setQuicklookPath(file.getPath());
        product.setQuicklookSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save quicklook.", e);
    }

    // Thumbnail
    int thumbnail_width = cfgManager.getProductConfiguration().getThumbnailConfiguration().getWidth();
    int thumbnail_height = cfgManager.getProductConfiguration().getThumbnailConfiguration().getHeight();
    boolean thumbnail_cutting = cfgManager.getProductConfiguration().getThumbnailConfiguration().isCutting();

    logger.info("Generating Thumbnail " + thumbnail_width + "x" + thumbnail_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight() + " image.");

    image = ProcessingUtils.ResizeImage(input_image, thumbnail_width, thumbnail_height, 10f, thumbnail_cutting);

    // Manages the quicklook output
    file = new File(image_directory, product_id + "-th.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setThumbnailPath(file.getPath());
        product.setThumbnailSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save thumbnail.", e);
    }
    SdiImageFactory.close(input_list);
    try {
        lock.close();
    } catch (IOException e) {
    }
}

From source file:net.sf.nmedit.nordmodular.NMHelpHandler.java

private URL getModuleImageURL(PModuleDescriptor dmodule) {
    if (dmodule.getComponentId() == null) {
        if (log.isWarnEnabled()) {
            log.warn("module has no componentid " + dmodule);
        }/*ww  w.  j av  a2s. c  om*/
        return null;
    }
    String name = dmodule.getComponentId() + ".png";

    TempDir tempdir = TempDir.forObject(this);
    if (tempdir == null) {
        if (log.isWarnEnabled()) {
            log.warn("TempDir.forObject(this) returned null");
        }
        return null;
    }
    File dir = tempdir.getTempFile("help/modules");

    if (!dir.exists()) {
        try {
            dir.mkdirs();
        } catch (Throwable t) {
            if (log.isErrorEnabled()) {
                log.error("could not create dir for module images", t);
            }
            return null;
        }
    }

    File imgFile = new File(dir, name);
    if (!imgFile.exists()) {
        // create image
        JTContext context = NMContextData.sharedInstance().getJTContext();
        ModuleElement mstore = context.getStorageContext().getModuleStoreById(dmodule.getComponentId());

        JTModule component;
        try {
            component = mstore.createModule(context, new PBasicModule(dmodule));
        } catch (JTException e) {
            if (log.isErrorEnabled()) {
                log.error("could not create module component for " + dmodule, e);
            }
            return null;
        }

        ModuleImageRenderer mir = new ModuleImageRenderer();
        mir.add(component);
        mir.setForDragAndDrop(false);
        mir.setPaintExtraBorder(false);
        mir.setRenderCablesEnabled(false);
        Image image = mir.render();
        if (image == null) {
            if (log.isWarnEnabled()) {
                log.warn("rendering image failed");
            }
            return null;
        }

        if (!(image instanceof RenderedImage)) {
            if (log.isWarnEnabled()) {
                log.warn("rendered image not instanceof " + RenderedImage.class);
            }
        }

        // store image
        try {
            ImageIO.write((RenderedImage) image, "PNG", imgFile);
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("could not write image " + imgFile, e);
            }
            return null;
        }
    }

    try {
        return imgFile.toURI().toURL();
    } catch (Throwable t) {
        if (log.isErrorEnabled()) {
            log.error("could not resolve URL " + imgFile, t);
        }
        return null;
    }
}

From source file:com.joey.software.regionSelectionToolkit.controlers.ImageProfileToolDynamicRangePanel.java

public void showFlattenedImage() {
    JFrame f = new JFrame("Flattened Image");
    JButton save = new JButton("Save");

    final DynamicRangeImage img = getFlattenedImage();

    f.getContentPane().setLayout(new BorderLayout());
    f.getContentPane().add(img, BorderLayout.CENTER);
    f.getContentPane().add(save, BorderLayout.SOUTH);

    f.setSize(600, 480);//  w w w  .java 2  s . c  om
    f.setVisible(true);
    save.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                File f = FileSelectionField.getUserFile();
                if (f != null) {
                    ImageIO.write(img.getImage().getImage(), "png", f);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

}

From source file:org.suren.autotest.web.framework.log.Image4SearchLog.java

@Around("execution(* org.suren.autotest.web.framework.core.ElementSearchStrategy.search*(..))")
public Object hello(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();

    Object res = joinPoint.proceed(args);
    WebDriver driver = engine.getDriver();
    if (res instanceof WebElement && driver instanceof TakesScreenshot) {
        TakesScreenshot shot = (TakesScreenshot) driver;

        File file = shot.getScreenshotAs(OutputType.FILE);
        BufferedImage bufImg = ImageIO.read(file);

        try {//from   w w w . j a v  a  2  s. c  om
            WebElement webEle = (WebElement) res;
            Point loc = webEle.getLocation();
            Dimension size = webEle.getSize();

            Graphics2D g = bufImg.createGraphics();
            g.setColor(Color.red);
            g.drawRect(loc.getX(), loc.getY(), size.getWidth(), size.getHeight());
        } catch (StaleElementReferenceException e) {
            //
        }

        File elementSearchImageFile = new File(outputDir,
                progressIdentify + "_" + System.currentTimeMillis() + ".png");
        try (OutputStream output = new FileOutputStream(elementSearchImageFile)) {
            ImageIO.write(bufImg, "gif", output);
            elementSearchImageFileList.add(elementSearchImageFile);
            animatedGifEncoder.addFrame(bufImg);
        }
    }

    return res;
}

From source file:com.github.srec.rec.DefaultScreenShot.java

public String capture(String subdir, Rectangle screenRect, Robot robot) {
    BufferedImage image = robot.createScreenCapture(screenRect);
    if (image == null) {
        return null;
    }// w  w  w. j a va2  s . c om
    String captureFileName = "screenshot-" + counter++ + ".png";
    String pathname = PropertiesReader.getProperties().getProperty(PropertiesReader.SCREENSHOTS_DIR);
    if (isBlank(pathname)) {
        pathname = "target/screenshots";
    }
    if (!isBlank(subdir)) {
        pathname = pathname + File.separator + subdir;
    }
    createScreenshotDirectory(pathname);
    String finalFileName = pathname + File.separator + captureFileName;
    try {
        ImageIO.write(image, "png", new File(finalFileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return finalFileName;
}

From source file:org.messic.server.facade.controllers.pages.CaptchaController.java

@ApiMethod(path = "/captcha", verb = ApiVerb.GET, description = "Get a captcha", produces = {
        MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error") })
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)/*from   w ww.ja v a  2  s .c o m*/
@ResponseBody
@ApiResponseObject
public Captcha getCaptcha() throws UnknownMessicRESTException {

    try {
        UUID idOne = UUID.randomUUID();
        // create the image with the text
        BufferedImage bi = service.getImageChallengeForID(idOne.toString());
        BufferedImage bi2 = Util.ImagedeepCopy(bi);
        Graphics2D g2d = (Graphics2D) bi.getGraphics();
        float alpha = 0.25f;
        int type = AlphaComposite.SRC_OVER;
        AlphaComposite composite = AlphaComposite.getInstance(type, alpha);
        g2d.setComposite(composite);

        final int Min = 5;
        final int Max = 30;
        int random1 = Min + (int) (Math.random() * ((Max - Min) + 1));
        int random2 = Min + (int) (Math.random() * ((Max - Min) + 1));

        g2d.drawImage(bi2, random1, random2, null);

        alpha = 0.80f;
        type = AlphaComposite.SRC_OVER;
        composite = AlphaComposite.getInstance(type, alpha);
        g2d.setComposite(composite);

        int MinX = 0;
        int MaxX = bi.getWidth();
        int MinY = 0;
        int MaxY = bi.getHeight();
        g2d.setColor(Color.black);
        for (int i = 0; i < random2; i++) {
            int random3 = MinX + (int) (Math.random() * ((MaxX - MinX) + 1));
            int random4 = MinX + (int) (Math.random() * ((MaxX - MinX) + 1));
            int random5 = MinY + (int) (Math.random() * ((MaxY - MinY) + 1));
            int random6 = MinY + (int) (Math.random() * ((MaxY - MinY) + 1));
            g2d.drawLine(random3, random5, random4, random6);
        }

        Captcha result = new Captcha();
        result.id = idOne.toString();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", baos);
        byte[] resultb64 = Base64.encode(baos.toByteArray());
        result.captchaImage = new String(resultb64);
        return result;
    } catch (Exception e) {
        throw new UnknownMessicRESTException(e);
    }
}

From source file:org.kuali.mobility.people.controllers.PeopleController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/{userNameHash}", method = RequestMethod.GET)
public String getUserDetails(Model uiModel, HttpServletRequest request,
        @PathVariable("userNameHash") String userNameHash/*,
                                                         @RequestParam("lName") String searchLastName, @RequestParam("fName") String searchFirstName, @RequestParam("uName") String searchUserName,
                                                         @RequestParam("exact") String searchExactness, @RequestParam("status") String searchStatus, @RequestParam("location") String searchLocation*/) {

    User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
    boolean isLoggedIn = false;
    if (user != null) {
        isLoggedIn = true;/*w  ww  . j  av a 2s .  c o m*/
    }

    /*
    Search search = new Search();
    search.setLastName(searchLastName);
    search.setFirstName(searchFirstName);
    search.setUserName(searchUserName);
    search.setExactness(searchExactness);
    search.setLocation(searchLocation);
    search.setStatus(searchStatus);
    */

    Map<String, String> userNameHashes = (Map<String, String>) request.getSession()
            .getAttribute("People.UserNames.Hashes");
    Person p = null;
    if (userNameHashes != null) {
        String userName = userNameHashes.get(userNameHash);
        p = peopleService.getUserDetails(userName);
    }
    uiModel.addAttribute("person", p);
    //      uiModel.addAttribute("search", search);
    uiModel.addAttribute("loggedIn", isLoggedIn);

    if (!isLoggedIn && p != null && p.getEmail() != null && !"".equals(p.getEmail())) {
        BufferedImage bufferedImage = peopleService.generateObfuscatedImage(p.getEmail());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "png", os);
            String key = "People.Image.Email.";
            // Add an identifier to the key so heavily cached browsers do not reuse the same image for different people
            String hash = null;
            if (p.getUserName() != null) {
                hash = "" + Math.abs(p.getUserName().hashCode());
            } else {
                Date now = new Date();
                hash = "" + now.getTime();
            }
            key = key + hash;
            request.getSession().setAttribute(key, os.toByteArray());
            uiModel.addAttribute("imageKey", hash);
        } catch (Exception ioException) {
            LOG.error("Error generating email image: ", ioException);
        }
    }
    return "people/details";
}