Example usage for javax.imageio ImageIO read

List of usage examples for javax.imageio ImageIO read

Introduction

In this page you can find the example usage for javax.imageio ImageIO read.

Prototype

public static BufferedImage read(ImageInputStream stream) throws IOException 

Source Link

Document

Returns a BufferedImage as the result of decoding a supplied ImageInputStream with an ImageReader chosen automatically from among those currently registered.

Usage

From source file:edu.harvard.mcz.imagecapture.ThumbnailBuilder.java

@Override
public void run() {
    int existsCounter = 0;
    // mkdir thumbs ; mogrify -path thumbs -resize 80x120 *.JPG                   
    if (startPoint.isDirectory() && (!startPoint.getName().equals("thumbs"))) {
        File thumbsDir = new File(startPoint.getPath() + File.separator + "thumbs");
        log.debug(thumbsDir.getPath());//  w w  w. ja  v  a 2  s . c  o m
        if (!thumbsDir.exists()) {
            thumbsDir.mkdir();
            thumbsDir.setWritable(true);
            log.debug("Creating " + thumbsDir.getPath());
        }
        File[] potentialFilesToThumb = startPoint.listFiles();
        List<File> filesToThumb = new ArrayList<File>();
        int filesToThumbCount = 0;
        for (int i = 0; i < potentialFilesToThumb.length; i++) {
            if (potentialFilesToThumb[i].getName().endsWith(".JPG")) {
                filesToThumb.add(potentialFilesToThumb[i]);
                filesToThumbCount++;
            }
        }
        if (filesToThumbCount > 0) {
            int targetWidth = 100;
            int targetHeight = 150;

            Iterator<File> i = filesToThumb.iterator();
            while (i.hasNext()) {
                File file = i.next();
                File output = new File(thumbsDir.getPath().concat(File.separator).concat(file.getName()));
                if (!output.exists()) {
                    // don't overwrite existing thumnails
                    try {
                        BufferedImage img = ImageIO.read(file);
                        BufferedImage thumbnail = Scalr.resize(img, Scalr.Method.BALANCED,
                                Scalr.Mode.FIT_TO_WIDTH, targetWidth, targetHeight, Scalr.OP_ANTIALIAS);
                        // img.createGraphics().drawImage(ImageIO.read(file).getScaledInstance(targetWidth, targetHeigh, Image.SCALE_SMOOTH),0,0,null);
                        ImageIO.write(thumbnail, "jpg", output);
                        thumbnailCounter++;
                    } catch (IOException e1) {
                        log.error(e1.getMessage(), e1);
                        JOptionPane.showMessageDialog(null, e1.getMessage() + "\n", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    existsCounter++;
                }
            }

        } else {
            String message = "No *.JPG files found in " + startPoint.getPath();
            log.debug(message);
        }
    }
    String exists = "";
    if (existsCounter > 0) {
        exists = "\nSkipped " + existsCounter + " existing thumbnails.";
    }
    JOptionPane.showMessageDialog(null,
            "Done building " + thumbnailCounter + " thumbnails in ./thumbs/" + exists, "Thumbnails Built.",
            JOptionPane.INFORMATION_MESSAGE);
}

From source file:dk.dma.msiproxy.web.WmsProxyServlet.java

/**
 * Main GET method// www . j av  a2s  .  c  om
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Cache for a day
    WebUtils.cache(response, CACHE_TIMEOUT);

    // Check that the WMS provider has been defined using system properties
    if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin)
            || StringUtils.isBlank(wmsPassword)) {
        response.sendRedirect(BLANK_IMAGE);
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, String[]> paramMap = (Map<String, String[]>) request.getParameterMap();
    String params = paramMap.entrySet().stream().map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0]))
            .collect(Collectors.joining("&"));
    params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword);

    String url = wmsProvider + "?" + params;
    log.trace("Loading image " + url);

    try {
        BufferedImage image = ImageIO.read(new URL(url));
        if (image != null) {
            image = transformWhiteToTransparent(image);

            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
            image.flush();
            out.close();
            return;
        }
    } catch (Exception e) {
        log.trace("Failed loading WMS image for URL " + url);
    }

    // Fall back to return a blank image
    response.sendRedirect(BLANK_IMAGE);
}

From source file:de.burrotinto.jKabel.dispalyAS.DisplayK.java

@Bean(name = "bearbeitenPanel")
public JPanel getBearbeitenPanel(KabelTypAuswahlAAS kabelTypAuswahlAAS, TrommelAuswahlAAS tommelAAs,
        StreckenAAS streckenAAS, Color background) {

    kabelTypAuswahlAAS.addKabelTypListner(tommelAAs);
    kabelTypAuswahlAAS.addKabelTypListner(streckenAAS);

    tommelAAs.addTrommelListner(streckenAAS);

    JPanel l = new JPanel(new GridLayout(1, 2));
    JPanel all = new JPanel(new GridLayout(1, 2));

    JScrollPane kSP = new JScrollPane(kabelTypAuswahlAAS);
    l.add(kSP);//from w  w  w .j a  v  a  2s  .c o  m
    l.add(new JScrollPane(tommelAAs));
    all.add(l);
    JScrollPane sc = new JScrollPane(streckenAAS);
    sc.setPreferredSize(new Dimension(740, 740));
    all.add(sc);

    kSP.setOpaque(false);
    sc.setOpaque(false);

    l.setBackground(background);
    kabelTypAuswahlAAS.setBackground(background);
    tommelAAs.setBackground(background);
    streckenAAS.setBackground(background);

    try {
        streckenAAS.setLogo(ImageIO.read(new File(ConfigReader.getInstance().getPath() + "logo.jpg")));
    } catch (IOException e) {
        streckenAAS.setLogo(null);
    }
    all.setBackground(background);
    return all;
}

From source file:io.github.jeremgamer.editor.panels.MusicFrame.java

public MusicFrame(JFrame frame, final GeneralSave gs) {

    ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>();
    try {//from  w ww. j  a v  a2s  . c  o  m
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png")));
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    this.setIconImages((List<? extends Image>) icons);

    this.setTitle("Musique");
    this.setSize(new Dimension(300, 225));

    this.addWindowListener(new WindowListener() {
        @Override
        public void windowActivated(WindowEvent event) {
        }

        @Override
        public void windowClosed(WindowEvent event) {
        }

        @Override
        public void windowClosing(WindowEvent event) {
            try {
                gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (clip != null) {
                clip.stop();
                clip.close();
                try {
                    audioStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void windowDeactivated(WindowEvent event) {
        }

        @Override
        public void windowDeiconified(WindowEvent event) {
        }

        @Override
        public void windowIconified(WindowEvent event) {
        }

        @Override
        public void windowOpened(WindowEvent event) {
        }
    });

    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

    this.setModal(true);
    this.setLocationRelativeTo(frame);

    JPanel properties = new JPanel();
    properties.setBorder(BorderFactory.createTitledBorder("Lecture"));
    ButtonGroup bg = new ButtonGroup();
    bg.add(one);
    bg.add(loop);
    one.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent event) {
            JRadioButton rb = (JRadioButton) event.getSource();
            if (rb.isSelected()) {
                gs.set("music.reading", 0);
                try {
                    gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (clip != null) {
                    if (clip.isRunning())
                        clip.loop(0);
                }
            }
        }
    });
    loop.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent event) {
            JRadioButton rb = (JRadioButton) event.getSource();
            if (rb.isSelected()) {
                gs.set("music.reading", 1);
                try {
                    gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (clip != null) {
                    if (clip.isRunning())
                        clip.loop(Clip.LOOP_CONTINUOUSLY);
                }
            }
        }
    });
    properties.add(one);
    properties.add(loop);
    if (gs.getInt("music.reading") == 0) {
        one.setSelected(true);
    } else {
        loop.setSelected(true);
    }

    volume.setMaximum(100);
    volume.setMinimum(0);
    volume.setValue(30);
    volume.setPaintTicks(true);
    volume.setPaintLabels(true);
    volume.setMinorTickSpacing(10);
    volume.setMajorTickSpacing(20);
    volume.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent event) {
            JSlider slider = (JSlider) event.getSource();
            double value = slider.getValue();
            gain = value / 100;
            dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
            if (clip != null)
                gainControl.setValue(dB);
            gs.set("music.volume", (int) value);
        }
    });
    volume.setValue(gs.getInt("music.volume"));
    properties.add(volume);
    properties.setPreferredSize(new Dimension(300, 125));

    content.add(properties);

    JPanel browsePanel = new JPanel();
    browsePanel.setBorder(BorderFactory.createTitledBorder(""));
    JButton browse = new JButton("Parcourir...");
    if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
        preview.setEnabled(false);
        browse.setText("");
        try {
            browse.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    browse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
                if (clip != null) {
                    clip.stop();
                    clip.close();
                    try {
                        audioStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                name.setText("");
                preview.setEnabled(false);
                button.setText("Parcourir...");
                button.setIcon(null);
                new File("projects/" + Editor.getProjectName() + "/music.wav").delete();
                gs.set("music.name", "");
            } else {
                String path = null;
                JFileChooser chooser = new JFileChooser(Editor.lastPath);
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio (WAV)", "wav");
                chooser.setFileFilter(filter);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int option = chooser.showOpenDialog(null);
                if (option == JFileChooser.APPROVE_OPTION) {
                    path = chooser.getSelectedFile().getAbsolutePath();
                    Editor.lastPath = chooser.getSelectedFile().getParent();
                    copyMusic(new File(path));
                    button.setText("");
                    try {
                        button.setIcon(
                                new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    gs.set("music.name", new File(path).getName());
                    try {
                        gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    name.setText(new File(path).getName());
                    preview.setEnabled(true);
                }
            }
        }

    });
    if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
        preview.setEnabled(true);
    } else {
        preview.setEnabled(false);
    }
    preview.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            JToggleButton tb = (JToggleButton) event.getSource();
            if (tb.isSelected()) {
                try {
                    audioStream = AudioSystem.getAudioInputStream(
                            new File("projects/" + Editor.getProjectName() + "/music.wav"));
                    format = audioStream.getFormat();
                    info = new DataLine.Info(Clip.class, format);
                    clip = (Clip) AudioSystem.getLine(info);
                    clip.open(audioStream);
                    clip.start();
                    gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
                    gainControl.setValue(dB);
                    if (loop.isSelected()) {
                        clip.loop(Clip.LOOP_CONTINUOUSLY);
                    } else {
                        clip.loop(0);
                    }
                    clip.addLineListener(new LineListener() {
                        @Override
                        public void update(LineEvent event) {
                            Clip clip = (Clip) event.getSource();
                            if (!clip.isRunning()) {
                                preview.setSelected(false);
                                clip.stop();
                                clip.close();
                                try {
                                    audioStream.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    });
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
            } else {
                clip.stop();
                clip.close();
                try {
                    audioStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    });
    JPanel buttons = new JPanel();
    buttons.setLayout(new BorderLayout());
    buttons.add(browse, BorderLayout.WEST);
    buttons.add(preview, BorderLayout.EAST);
    browsePanel.setLayout(new BorderLayout());
    browsePanel.add(buttons, BorderLayout.NORTH);
    browsePanel.add(name, BorderLayout.SOUTH);

    name.setPreferredSize(new Dimension(280, 25));
    name.setText(gs.getString("music.name"));
    content.add(browsePanel);

    this.setContentPane(content);
    this.setVisible(true);
}

From source file:com.cognifide.aet.job.common.comparators.layout.utils.ImageComparisonConvertImageTest.java

@Test
public void convertImageTo2DArray_1x4Gradients_expectLastPixelSame() throws Exception {
    try {/*from  w w w .j a  v a  2  s.c  om*/
        // given
        patternStream = getClass()
                .getResourceAsStream("/mock/LayoutComparator/comparingColors/1x4-blue-gradient.png");
        BufferedImage pattern = ImageIO.read(patternStream);
        sampleStream = getClass()
                .getResourceAsStream("/mock/LayoutComparator/comparingColors/1x4-grey-gradient.png");
        BufferedImage sample = ImageIO.read(sampleStream);
        // when
        int[][] patternPixels = ImageComparison.convertImageTo2DArray(pattern);
        int[][] samplePixels = ImageComparison.convertImageTo2DArray(sample);
        // then
        int patternPixel = patternPixels[3][0];
        int samplePixel = samplePixels[3][0];
        assertThat(patternPixel, is(equalTo(samplePixel)));
    } finally {
        closeInputStreams(imageStreams);
    }
}

From source file:com.wet.wired.jsr.recorder.DesktopScreenRecorder.java

public DesktopScreenRecorder(OutputStream oStream, ScreenRecorderListener listener, String sessionId) {
    super(oStream, listener);

    BasicConfigurator.configure();//from w  w  w.ja v  a2  s .  c om

    if (sessionId == null) {
        sessionId = UUID.randomUUID().toString();
    }

    try {
        Idioma idioma = new Idioma();
        logger.trace("Set Idioma:start()");
        config = idioma.setIdioma("espanol");
        logger.trace("Set Idioma:end()");
    } catch (ConfigurationException e2) {
        logger.error(e2.getMessage());
    }

    LoggerUtils loggerUtils = new LoggerUtils();

    loggerUtils.load(config.getString("pathGlobal"), sessionId, config.getString("synchronizer.ruta.log"),
            config.getString("pathLog4j"), "synchronizer.log", "synchronizer.html");

    logger.info("****************** Inicio de Screen Recorder ***************** ");
    logger.info("*********** " + sessionId + " *********** ");
    logger.info("************************************************************ ");

    try {
        String mouseCursorFile;

        if (useWhiteCursor)
            mouseCursorFile = "white_cursor.png";
        else
            mouseCursorFile = "black_cursor.png";

        URL cursorURL = getClass().getResource("/mouse_cursors/" + mouseCursorFile);

        mouseCursor = ImageIO.read(cursorURL);

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

From source file:com.company.project.web.controller.WebSocketController.java

@MessageMapping("/fileShareMapping")
//@SendTo("/topic/fileShareResponse")
public void fileShare(String param) throws Exception {
    // TODO detect file type
    String id = param.substring(0, 36); // extract prepend UUID which is 36 chars length
    String base64Chunk = param.substring(36, param.length());

    if (base64Chunk.length() == 0) {
        this.simpMessagingTemplate.convertAndSend("/topic/fileShareResponse/" + id, "0");
        this.simpMessagingTemplate.convertAndSend("/topic/imageFileShareResponse", map.get(id).toString());
        BufferedImage image = null;
        byte[] imageByte;
        try {//from   w  w w .j  a va 2s .c  om
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(map.get(id).toString().split(",")[1]);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        File outputfile = new File("D:/GemShelf/" + UUID.randomUUID() + ".jpg");
        ImageIO.write(image, "jpg", outputfile);
        map.remove(id);
    } else {
        StringBuilder sb = map.get(id);
        if (sb == null) {
            sb = new StringBuilder();
            sb.append(base64Chunk);
            map.put(id, sb);
        } else {
            sb.append(base64Chunk);
        }
        this.simpMessagingTemplate.convertAndSend("/topic/fileShareResponse/" + id, "1");
    }

}

From source file:com.liusoft.dlog4j.photo.FileSystemSaver.java

public Photo save(HttpContext context, FormFile imgFile, boolean autoRotate) throws IOException {
    String extendName = StringUtils.getFileExtend(imgFile.getFileName()).toLowerCase();
    String[] urls = this.createNewPhotoURI(context, extendName);
    if (urls == null)
        return null;

    String origionalPath = urls[0];
    String previewPath = urls[1];
    //?//www .j  a v  a  2s  .c  om
    {
        ImageUtils.writeToFile(imgFile, origionalPath);
    }

    Photo photo = new Photo();

    if (ImageUtils.isJPG(extendName)) {
        try {
            ImageUtils.fillExifInfo(origionalPath, photo);
            int orient = photo.getOrientation();
            if (autoRotate && orient > 0 && orient <= 8) {
                //Rotate the image
                ImageUtils.rotateImage(origionalPath, orient);
            }
        } catch (Exception e) {
            log.error("Exception occur when reading EXIF of " + origionalPath, e);
        }
    } else if (ImageUtils.isBMP(extendName)) {
        String jpgName = ImageUtils.BMP_TO_JPG(origionalPath);
        if (jpgName != null) {
            //bmp
            if (new File(origionalPath).delete())
                origionalPath = jpgName;
        }
    }

    //???
    File fOrigionalImage = new File(origionalPath);
    photo.setSize((int) fOrigionalImage.length());
    BufferedImage oldImage = (BufferedImage) ImageIO.read(fOrigionalImage);
    int old_width = oldImage.getWidth();
    int old_height = oldImage.getHeight();
    photo.setWidth(old_width);
    photo.setHeight(old_height);
    photo.setColorBit(oldImage.getColorModel().getPixelSize());
    photo.setFileName(imgFile.getFileName());

    {
        //?1024*768
        int ori_width = MAX_WIDTH, ori_height = MAX_HEIGHT;
        boolean regenerate_img = true;
        if (old_width <= MAX_WIDTH && old_height <= MAX_HEIGHT) {
            ori_width = old_width;
            ori_height = old_height;
            regenerate_img = false;
        } else if (old_width > MAX_WIDTH && old_height > MAX_HEIGHT) {
            ori_width = MAX_WIDTH;
            ori_height = old_height * ori_width / old_width;
        } else if (old_width > MAX_WIDTH && old_height <= MAX_HEIGHT) {
            ori_width = MAX_WIDTH;
            ori_height = old_height;
        } else if (old_width <= MAX_WIDTH && old_height > MAX_HEIGHT) {
            ori_height = MAX_HEIGHT;
            ori_width = old_width * ori_height / old_height;
        }
        if (regenerate_img) {
            photo.setWidth(ori_width);
            photo.setHeight(ori_height);
            ImageUtils.createPreviewImage(new FileInputStream(origionalPath), origionalPath, ori_width,
                    ori_height);
            photo.setSize((int) new File(origionalPath).length());
        }
    }

    //?
    int preview_width, preview_height;
    preview_width = Math.min(PREVIEW_WIDTH, photo.getWidth());
    if (photo.getHeight() <= PREVIEW_HEIGHT)
        preview_height = photo.getHeight();
    else {
        //?
        preview_height = photo.getHeight() * preview_width / photo.getWidth();
    }

    if (preview_width == photo.getWidth() && preview_height == photo.getHeight()) {
        //???
        previewPath = origionalPath;
    } else {
        //?
        if (ImageUtils.isImage(extendName)) {
            previewPath = ImageUtils.createPreviewImage(new FileInputStream(origionalPath), previewPath,
                    preview_width, preview_height);
        } else {
            photo = null;
            return null;
        }
    }
    //url
    //String contextPath = context.getRequest().getContextPath() + "/";
    String uploadPath = this.getUploadPath(context);
    String path1 = origionalPath.substring(uploadPath.length());
    String path2 = previewPath.substring(uploadPath.length());
    photo.setImageURL(getPhotoBaseURI(context) + StringUtils.replace(path1, File.separator, "/"));
    photo.setPreviewURL(getPhotoBaseURI(context) + StringUtils.replace(path2, File.separator, "/"));
    return photo;
}

From source file:de.anycook.upload.UploadHandler.java

/**
 * speichert eine gegebene Bilddatei ab, indem saveSmallImage und saveBigImage genutzt werden
 *
 * @param file bilddatei, die gepeichert werden soll
 * @return Namen der gespeicherten Dateien
 *//*from  w  w  w  . ja v  a 2s .co  m*/
public String saveFile(File file) throws SQLException, IOException {
    String newFilename = makeAndCheckFilename() + ".png";
    BufferedImage image = ImageIO.read(file);

    Preconditions.checkNotNull(image);
    Preconditions.checkNotNull(newFilename);

    saveSmallImage(image, newFilename);
    saveBigImage(image, newFilename);
    saveOriginalImage(image, newFilename);
    file.delete();
    logger.debug("successfully uploaded file " + newFilename);
    return newFilename;
}

From source file:de.ep3.ftpc.view.designer.UIDesigner.java

/**
 * Loads a (buffered) image from the resources directory provided.
 *
 * @param dirName The directory name under the resource/drawable directory.
 * @param fileName The file name under the directory name provided before.
 * @return A hopefully nice image.//  w w  w  . j  a v a2  s  .co  m
 */
public BufferedImage getDefaultImage(String dirName, String fileName) {
    String filePath = "drawable" + File.separator + dirName + File.separator + fileName;

    Resource res = App.getContext().getResource(filePath);

    BufferedImage image;

    try {
        image = ImageIO.read(res.getInputStream());
    } catch (IOException e) {
        // Don't blame this checked-to-unchecked exception conversion. This is by design (fail fast and early).
        throw new IllegalStateException("Unable to load image file " + fileName + " (" + e.getMessage() + ")");
    }

    return image;
}