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:com.openkm.extractor.BarcodeTextExtractor.java

/**
 * {@inheritDoc}//from www.  j a  v  a  2  s . co m
 */
public Reader extractText(InputStream stream, String type, String encoding) throws IOException {
    try {
        BufferedImage image = ImageIO.read(stream);
        String text = multiple(image);
        return new StringReader(text);
    } catch (Exception e) {
        log.warn("Failed to extract barcode text", e);
        return new StringReader("");
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * create thumb file./*from  ww  w .  j av  a2s  .  co  m*/
 *
 * @param originFile origin image file.
 * @param file file to save thumb
 * @param thumbnail connector thumbnail properties
 * @return true if success
 * @throws IOException when IO Exception occurs.
 */
public static boolean createThumb(Path originFile, Path file, ThumbnailProperties thumbnail)
        throws IOException {
    log.debug("createThumb");
    BufferedImage image;
    try (InputStream is = Files.newInputStream(originFile)) {
        image = ImageIO.read(is);
    }
    if (image != null) {
        Dimension dimension = createThumbDimension(image, thumbnail.getMaxWidth(), thumbnail.getMaxHeight());
        FileUtils.createPath(file, true);
        if (image.getHeight() <= dimension.height && image.getWidth() <= dimension.width) {
            writeUntouchedImage(originFile, file);
        } else {
            resizeImage(image, dimension.width, dimension.height, thumbnail.getQuality(), file);
        }
        return true;
    } else {
        log.error("Wrong image file");
    }
    return false;
}

From source file:davmail.util.IOUtil.java

/**
 * Resize image bytes to a max width or height image size.
 *
 * @param inputBytes input image bytes//from  w  w  w. j a v  a 2s .c o  m
 * @param max        max size
 * @return scaled image bytes
 * @throws IOException on error
 */
public static byte[] resizeImage(byte[] inputBytes, int max) throws IOException {
    BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(inputBytes));
    if (inputImage == null) {
        throw new IOException("Unable to decode image data");
    }
    BufferedImage outputImage = resizeImage(inputImage, max);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(outputImage, "jpg", baos);
    return baos.toByteArray();
}

From source file:com.htmlhifive.pitalium.image.model.PersistedScreenshotImageTest.java

private BufferedImage getImage() throws Exception {
    return ImageIO.read(getClass().getResource("ScreenshotImageTest_image.png"));
}

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

public Others(final JFrame frame, final OtherPanel op, final PanelSave ps) {
    this.frame = frame;

    this.setBorder(BorderFactory.createTitledBorder(""));
    JButton add = null;/* www  . java  2 s.c o  m*/
    try {
        add = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("add.png"))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                JOptionPane jop = new JOptionPane();
                @SuppressWarnings("static-access")
                String name = jop.showInputDialog((JFrame) SwingUtilities.windowForComponent(otherList),
                        "Nommez le composant :", "Crer un composant", JOptionPane.QUESTION_MESSAGE);

                if (name != null) {
                    for (int i = 0; i < data.getSize(); i++) {
                        if (data.get(i).equals(name)) {
                            name += "1";
                        }
                    }
                    data.addElement(name);
                    new OtherSave(name);
                    ActionPanel.updateLists();
                    PanelsPanel.updateLists();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });

    JButton remove = null;
    try {
        remove = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    remove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                if (otherList.getSelectedValue() != null) {
                    File file = new File("projects/" + Editor.getProjectName() + "/others/"
                            + otherList.getSelectedValue() + ".rbd");
                    JOptionPane jop = new JOptionPane();
                    @SuppressWarnings("static-access")
                    int option = jop.showConfirmDialog((JFrame) SwingUtilities.windowForComponent(otherList),
                            "tes-vous sr de vouloir supprimer ce composant?", "Avertissement",
                            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

                    if (option == JOptionPane.OK_OPTION) {
                        File dir = new File("projects/" + Editor.getProjectName() + "/panels");
                        for (File f : FileUtils.listFilesAndDirs(dir, TrueFileFilter.INSTANCE,
                                TrueFileFilter.INSTANCE)) {
                            if (!f.isDirectory()) {
                                try {
                                    ps.load(f);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OtherSave os = new OtherSave();
                                try {
                                    os.load(file);
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                                String type = null;
                                switch (os.getInt("type")) {
                                case 0:
                                    type = "Zone de saisie";
                                    break;
                                case 1:
                                    type = "Zone de saisie de mot de passe";
                                    break;
                                case 2:
                                    type = "Zone de saisie (Grande)";
                                    break;
                                case 3:
                                    type = "Case  cocher";
                                    break;
                                case 4:
                                    type = "Menu droulant";
                                    break;
                                case 5:
                                    type = "Barre de progression";
                                    break;
                                case 6:
                                    type = "Slider";
                                    break;
                                case 7:
                                    type = "Spinner";
                                    break;
                                }
                                for (String section : ps.getSectionsContaining(
                                        otherList.getSelectedValue() + " (" + type + ")")) {
                                    ps.removeSection(section);
                                    try {
                                        ps.save(f);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        if (otherList.getSelectedValue().equals(op.getFileName())) {
                            op.setFileName("");
                        }
                        op.hide();
                        file.delete();
                        data.remove(otherList.getSelectedIndex());
                        ActionPanel.updateLists();
                        OtherPanel.updateLists();
                        PanelsPanel.updateLists();
                    }
                }
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            }

        }

    });

    JPanel buttons = new JPanel();
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
    buttons.add(add);
    buttons.add(remove);

    updateList();
    otherList.addMouseListener(new MouseAdapter() {
        @SuppressWarnings("unchecked")
        public void mouseClicked(MouseEvent evt) {
            JList<String> list = (JList<String>) evt.getSource();
            if (evt.getClickCount() == 2) {
                int index = list.locationToIndex(evt.getPoint());
                if (isOpen == false) {
                    op.show();
                    op.load(new File("projects/" + Editor.getProjectName() + "/others/"
                            + list.getModel().getElementAt(index) + ".rbd"));
                    previousSelection = list.getSelectedValue();
                    isOpen = true;
                } else {
                    try {
                        if (previousSelection.equals(list.getModel().getElementAt(index))) {
                            op.hide();
                            previousSelection = list.getSelectedValue();
                            list.clearSelection();
                            isOpen = false;
                        } else {
                            op.hideThenShow();
                            previousSelection = list.getSelectedValue();
                            op.load(new File("projects/" + Editor.getProjectName() + "/others/"
                                    + list.getModel().getElementAt(index) + ".rbd"));
                        }
                    } catch (NullPointerException npe) {
                        op.hide();
                        list.clearSelection();
                    }
                }
            } else if (evt.getClickCount() == 3) {
                int index = list.locationToIndex(evt.getPoint());
                if (isOpen == false) {
                    op.show();
                    op.load(new File("projects/" + Editor.getProjectName() + "/others/"
                            + list.getModel().getElementAt(index) + ".rbd"));
                    previousSelection = list.getSelectedValue();
                    isOpen = true;
                } else {
                    try {
                        if (previousSelection.equals(list.getModel().getElementAt(index))) {
                            op.hide();
                            previousSelection = list.getSelectedValue();
                            list.clearSelection();
                            isOpen = false;
                        } else {
                            op.hideThenShow();
                            previousSelection = list.getSelectedValue();
                            op.load(new File("projects/" + Editor.getProjectName() + "/others/"
                                    + list.getModel().getElementAt(index) + ".rbd"));
                        }
                    } catch (NullPointerException npe) {
                        op.hide();
                        list.clearSelection();
                    }
                }
            }
        }
    });
    JScrollPane listPane = new JScrollPane(otherList);
    listPane.getVerticalScrollBar().setUnitIncrement(Editor.SCROLL_SPEED);
    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    this.add(buttons);
    this.add(listPane);
    OtherPanel.updateLists();
}

From source file:org.openmrs.module.drawing.web.controller.ManageTemplatesController.java

@RequestMapping(value = "/module/drawing/manageTemplates", method = RequestMethod.POST)
public void manage(@RequestParam(value = "templateName", required = false) String templateName,
        @RequestParam(value = "template", required = true) MultipartFile file, ModelMap model,
        HttpSession session) {//  w w w.  jav a 2  s  . co m

    model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames());
    if (file == null || file.getSize() == 0) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Please Fill All The Fields");
        return;
    } else if (!DrawingUtil.isImage(file.getOriginalFilename())) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "File Format Not Supported");
        return;
    }
    if (StringUtils.isBlank(templateName))
        templateName = file.getOriginalFilename();
    else
        templateName = templateName + "." + DrawingUtil.getExtension(file.getOriginalFilename());

    try {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
        Boolean saved = DrawingUtil.saveFile(templateName, bi);
        if (saved) {
            session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Template Saved");
            model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames());

        } else
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Error Saving Template");

    } catch (IOException e) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Unable To Save Uploaded File");
        log.error("Unable to read uploadedFile", e);
    }

}

From source file:com.softenido.cafedark.image.hash.ImageHashBuilder.java

public Hash buildHash(VirtualFile pf) throws FileNotFoundException, IOException, ArchiveException {
    if (pf.length() == 0) {
        return null;
    }//  w w w . ja  v a  2 s  . com
    InputStream in = pool.get(pf);
    try {
        BufferedImage image = ImageIO.read(in);
        if (image != null) {
            return buildHash(image);
        }
        return null;
    } catch (Exception ex) {
        Logger.getLogger(ImageHashBuilder.class.getName()).log(Level.WARNING, pf.toString(), ex);
        return null;
    } finally {
        in.close();
    }
}

From source file:eu.flatworld.worldexplorer.layer.nltl7.NLTL7HTTPProvider.java

@Override
public void run() {
    while (true) {
        while (getQueueSize() != 0) {
            Tile tile = peekTile();/*  w ww . ja  v  a2s  . c  o m*/
            synchronized (tile) {
                String s = String.format(NLTL7Layer.HTTP_BASE, tile.getL(), tile.getX(), tile.getY());
                LogX.log(Level.FINER, s);
                GetMethod gm = new GetMethod(s);
                gm.setRequestHeader("User-Agent", WorldExplorer.USER_AGENT);
                try {
                    int response = client.executeMethod(gm);
                    LogX.log(Level.FINEST, NAME + " " + response + " " + s);
                    if (response == HttpStatus.SC_OK) {
                        InputStream is = gm.getResponseBodyAsStream();
                        BufferedImage bi = ImageIO.read(is);
                        is.close();
                        if (bi != null) {
                            tile.setImage(bi);
                        }
                    }
                } catch (Exception ex) {
                    LogX.log(Level.FINER, "", ex);
                } finally {
                    gm.releaseConnection();
                }
                LogX.log(Level.FINEST, NAME + " dequeueing: " + tile);
                unqueueTile(tile);
            }
            firePropertyChange(P_DATAREADY, null, tile);
            Thread.yield();
        }
        firePropertyChange(P_IDLE, false, true);
        try {
            Thread.sleep(QUEUE_SLEEP_TIME);
        } catch (Exception ex) {
        }
        ;
    }
}

From source file:net.sqs2.omr.result.export.chart.ChartImageWriter.java

private static BufferedImage[] createItemBackgroundImages(File[] itemBackgroundImageFiles) {
    int numItems = itemBackgroundImageFiles.length;
    BufferedImage[] itemBackgroundImages = new BufferedImage[numItems];
    int index = 0;

    for (File itemBackgroundImageFile : itemBackgroundImageFiles) {
        try {/*from w w  w  . j a  v a2 s .c  o  m*/
            itemBackgroundImages[index++] = ImageIO.read(itemBackgroundImageFile);
        } catch (IOException ignore) {
            ignore.printStackTrace();
        }
    }
    return itemBackgroundImages;
}

From source file:edworld.pdfreader4humans.PDFReaderTest.java

private void assertImagesAreSimilar(InputStream expectedOutputStream, BufferedImage outputImage)
        throws IOException {
    try {/* w w w .  ja  v a2s  . co  m*/
        BufferedImage expectedOutputImage = ImageIO.read(expectedOutputStream);
        assertEquals(expectedOutputImage.getType(), outputImage.getType());
        assertEquals(expectedOutputImage.getWidth(), outputImage.getWidth());
        assertEquals(expectedOutputImage.getHeight(), outputImage.getHeight());
        assertEquals(expectedOutputImage.getTransparency(), outputImage.getTransparency());
        for (int k = 0; k < Math.max(outputImage.getWidth(), outputImage.getHeight()); k++) {
            int kX = k % outputImage.getWidth();
            int kY = k % outputImage.getHeight();
            int expectedColor = expectedOutputImage.getRGB(kX, kY);
            int actualColor = outputImage.getRGB(kX, kY);
            if ((expectedColor ^ 0xFFFFFF) == actualColor)
                expectedColor ^= 0xFFFFFF;
            assertEquals("Color should be the same at (" + k + "," + k + ").", expectedColor, actualColor);
        }
    } finally {
        expectedOutputStream.close();
    }
}