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.ikon.extractor.BarcodeTextExtractor.java

/**
 * {@inheritDoc}/*from  ww  w  . ja v a 2s .  co m*/
 */
public Reader extractText(InputStream stream, String type, String encoding) throws IOException {
    try {
        com.google.zxing.Reader reader = new MultiFormatReader();
        BufferedImage image = ImageIO.read(stream);
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result = reader.decode(bitmap);
        return new StringReader(result.getText());
    } catch (Exception e) {
        log.warn("Failed to extract barcode text", e);
        return new StringReader("");
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

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

@Test
public void convertImageTo2DArray_2x1Image_expectSecondPixelDifferent() throws Exception {
    try {//from   w w  w.  ja  v a2s .c  o m
        // given
        patternStream = getClass().getResourceAsStream("/mock/LayoutComparator/comparingColors/2x1-red.png");
        BufferedImage pattern = ImageIO.read(patternStream);
        sampleStream = getClass()
                .getResourceAsStream("/mock/LayoutComparator/comparingColors/2x1-red-black.png");
        BufferedImage sample = ImageIO.read(sampleStream);
        // when
        int[][] patternPixels = ImageComparison.convertImageTo2DArray(pattern);
        int[][] samplePixels = ImageComparison.convertImageTo2DArray(sample);
        // then
        int patternPixel = patternPixels[0][1];
        int samplePixel = samplePixels[0][1];
        assertThat(patternPixel, is(not(equalTo(samplePixel))));
    } finally {
        closeInputStreams(imageStreams);
    }
}

From source file:PictureScaler.java

/** Creates a new instance of PictureScaler */
public PictureScaler() {
    try {/*www  .ja v a2  s .co m*/
        URL url = getClass().getResource("BB.jpg");
        picture = ImageIO.read(url);
        scaleW = (int) (SCALE_FACTOR * picture.getWidth());
        scaleH = (int) (SCALE_FACTOR * picture.getHeight());
        System.out.println("w, h = " + picture.getWidth() + ", " + picture.getHeight());
        setPreferredSize(new Dimension(PADDING + (5 * (scaleW + PADDING)), scaleH + (4 * PADDING)));
    } catch (Exception e) {
        System.out.println("Problem reading image file: " + e);
        System.exit(0);
    }
}

From source file:net.duckling.ddl.util.ImageUtils.java

/**
 * ???//ww  w .j a  v  a2 s  . com
 * @param tmpFilePath ?
 * @return
 */
public static boolean scare(String tmpFilePath) {
    try {
        BufferedImage src = ImageIO.read(new File(tmpFilePath)); // 
        int width = src.getWidth();
        int height = src.getHeight();
        if (width > DEFAULT_WIDTH) {
            height = (DEFAULT_WIDTH * height) / width;
            width = DEFAULT_WIDTH;
        }
        Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // ??
        g.dispose();
        File resultFile = new File(tmpFilePath);
        ImageIO.write(tag, "JPEG", resultFile);// ?
        return true;
    } catch (IOException e) {
        LOG.error(e);
    }
    return false;
}

From source file:bjerne.gallery.service.impl.ImageResizeServiceImpl.java

@Override
public void resizeImage(File origImage, File newImage, int width, int height) throws IOException {
    LOG.debug("Entering resizeImage(origImage={}, width={}, height={})", origImage, width, height);
    long startTime = System.currentTimeMillis();
    InputStream is = new BufferedInputStream(new FileInputStream(origImage));
    BufferedImage i = ImageIO.read(is);
    IOUtils.closeQuietly(is);//w  ww.j a  v  a 2s . c  o  m
    BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int origWidth = i.getWidth();
    int origHeight = i.getHeight();
    LOG.debug("Original size of image - width: {}, height={}", origWidth, height);
    float widthFactor = ((float) origWidth) / ((float) width);
    float heightFactor = ((float) origHeight) / ((float) height);
    float maxFactor = Math.max(widthFactor, heightFactor);
    int newHeight, newWidth;
    if (maxFactor > 1) {
        newHeight = (int) (((float) origHeight) / maxFactor);
        newWidth = (int) (((float) origWidth) / maxFactor);
    } else {
        newHeight = origHeight;
        newWidth = origWidth;
    }
    LOG.debug("Size of scaled image will be: width={}, height={}", newWidth, newHeight);
    int startX = Math.max((width - newWidth) / 2, 0);
    int startY = Math.max((height - newHeight) / 2, 0);
    Graphics2D scaledGraphics = scaledImage.createGraphics();
    scaledGraphics.setColor(backgroundColor);
    scaledGraphics.fillRect(0, 0, width, height);
    scaledGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    scaledGraphics.drawImage(i, startX, startY, newWidth, newHeight, null);
    OutputStream resultImageOutputStream = new BufferedOutputStream(FileUtils.openOutputStream(newImage));
    String extension = FilenameUtils.getExtension(origImage.getName());
    ImageIO.write(scaledImage, extension, resultImageOutputStream);
    IOUtils.closeQuietly(resultImageOutputStream);
    long duration = System.currentTimeMillis() - startTime;
    LOG.debug("Time in milliseconds to scale {}: {}", newImage.toString(), duration);
}

From source file:com.salesmanager.core.module.impl.application.files.CoreFileImpl.java

public String uploadFile(int merchantid, String config, File file, String fileName, String contentType)
        throws FileException {

    /** Check content type **/
    String imgct = conf.getString(config + ".contenttypes");
    if (imgct != null) {

        List ct = new ArrayList();
        StringTokenizer st = new StringTokenizer(imgct, ";");
        while (st.hasMoreTokens()) {
            ct.add(st.nextToken());/*from   ww w.  j  a  va2s  .co m*/
        }

        // check content type
        if (!ct.contains(contentType)) {
            throw new FileException(LabelUtil.getInstance().getText("errors.unsupported.file ") + contentType);
        }
    }

    /** if an image check size **/
    String imgwsz = conf.getString(config + ".maxwidth");
    String imghsz = conf.getString(config + ".maxheight");

    if (imgwsz != null && imghsz != null) {

        int wseize = 0;
        int hseize = 0;

        BufferedImage originalImage = null;

        try {
            wseize = Integer.parseInt(imgwsz);
            hseize = Integer.parseInt(imghsz);

        } catch (Exception e) {
            throw new FileException(e);
        }

        try {

            originalImage = ImageIO.read(file);
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();

            if (width > wseize || height > hseize) {
                throw new FileException(LabelUtil.getInstance().getText("errors.filedimensiontoolarge"));
            }

        } catch (FileException fe) {
            throw fe;
        } catch (Exception e) {
            throw new FileException(e);
        }

    }

    // Check file size
    long fsize = file.length();
    String smaxfsize = conf.getString(config + ".maxfilesize");
    if (StringUtils.isBlank(smaxfsize)) {
        smaxfsize = conf.getString("core.branding.cart.maxfilesize");
    }
    if (smaxfsize == null) {
        throw new FileException(FileException.ERROR, "Properties " + config + ".maxfilesize not defined");
    }
    long maxsize = 0;
    try {
        maxsize = Long.parseLong(smaxfsize);

    } catch (Exception e) {
        throw new FileException(e);
    }

    if (fsize > maxsize) {
        throw new FileException(LabelUtil.getInstance().getText("errors.filetoolarge"));
    }

    return copyFile(merchantid, config, file, fileName, contentType);

}

From source file:gd.gui.GeneticDrawingView.java

@Action
public void chooseImage() throws IOException {
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File("."));
    fc.showOpenDialog(mainPanel);/*  w  w w .  j  a v  a  2  s  .co m*/

    File file = fc.getSelectedFile();
    targetImage = ImageIO.read(file);
    targetImageLabel.setIcon(scaleToImageLabel(targetImage));
    fittestDrawingView.setSize(targetImage.getWidth(), targetImage.getHeight());
}

From source file:com.digitalgeneralists.assurance.ui.components.AboutPanel.java

protected void initializeComponent() {
    if (!this.initialized) {
        GridBagLayout gridbag = new GridBagLayout();
        setLayout(gridbag);//www  .  j  a  v a  2 s  .c  o  m

        GridBagConstraints applicationIconConstraints = new GridBagConstraints();
        applicationIconConstraints.anchor = 11;
        applicationIconConstraints.fill = 1;
        applicationIconConstraints.gridx = 0;
        applicationIconConstraints.gridy = 0;
        applicationIconConstraints.weightx = 1.0D;
        applicationIconConstraints.weighty = 0.8D;
        applicationIconConstraints.gridheight = 1;
        applicationIconConstraints.gridwidth = 1;
        applicationIconConstraints.insets = new Insets(5, 5, 5, 5);
        try {
            Image iconImage = ImageIO.read(getClass().getClassLoader().getResource("assurance.png"));
            iconImage = iconImage.getScaledInstance(48, 48, 0);
            JLabel applicationIcon = new JLabel(new ImageIcon(iconImage));
            add(applicationIcon, applicationIconConstraints);
        } catch (IOException e) {
            this.logger.warn(e);
        }

        GridBagConstraints applicationNameLabelConstraints = new GridBagConstraints();
        applicationNameLabelConstraints.anchor = 11;
        applicationNameLabelConstraints.fill = 1;
        applicationNameLabelConstraints.gridx = 0;
        applicationNameLabelConstraints.gridy = 1;
        applicationNameLabelConstraints.weightx = 1.0D;
        applicationNameLabelConstraints.weighty = 0.1D;
        applicationNameLabelConstraints.gridheight = 1;
        applicationNameLabelConstraints.gridwidth = 1;
        applicationNameLabelConstraints.insets = new Insets(5, 5, 5, 5);

        JLabel applicationNameLabel = new JLabel(Application.applicationName, 0);
        add(applicationNameLabel, applicationNameLabelConstraints);

        GridBagConstraints applicationVersionLabelConstraints = new GridBagConstraints();
        applicationVersionLabelConstraints.anchor = 11;
        applicationVersionLabelConstraints.fill = 1;
        applicationVersionLabelConstraints.gridx = 0;
        applicationVersionLabelConstraints.gridy = 2;
        applicationVersionLabelConstraints.weightx = 1.0D;
        applicationVersionLabelConstraints.weighty = 0.1D;
        applicationVersionLabelConstraints.gridheight = 1;
        applicationVersionLabelConstraints.gridwidth = 1;
        applicationVersionLabelConstraints.insets = new Insets(5, 5, 5, 5);

        StringBuilder labelText = new StringBuilder(128);
        JLabel applicationVersionLabel = new JLabel(labelText.append(Application.applicationVersion)
                .append(" (").append(Application.applicationBuildNumber).append(")").toString(), 0);
        labelText.setLength(0);

        add(applicationVersionLabel, applicationVersionLabelConstraints);

        this.initialized = true;
    }
}

From source file:cz.alej.michalik.totp.client.OtpPanel.java

/**
 * Pid jeden panel se zznamem/*from   w ww .j  a v a  2 s . co m*/
 * 
 * @param raw_data
 *            Data z Properties
 * @param p
 *            Properties
 * @param index
 *            Index zznamu - pro vymazn
 */
public OtpPanel(String raw_data, final Properties p, final int index) {
    // Data jsou oddlena stednkem
    final String[] data = raw_data.split(";");

    // this.setBackground(App.COLOR);
    this.setLayout(new GridBagLayout());
    // Mkov rozloen prvk
    GridBagConstraints c = new GridBagConstraints();
    this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 100));

    // Tla?tko pro zkoprovn hesla
    final JButton passPanel = new JButton("");
    passPanel.setFont(passPanel.getFont().deriveFont(App.FONT_SIZE));
    passPanel.setBackground(App.COLOR);
    // Zabere celou ku
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 100;
    this.add(passPanel, c);
    passPanel.setText(data[0]);

    // Tla?tko pro smazn
    JButton delete = new JButton("X");
    try {
        String path = "/material-design-icons/action/drawable-xhdpi/ic_delete_black_24dp.png";
        Image img = ImageIO.read(App.class.getResource(path));
        delete.setIcon(new ImageIcon(img));
        delete.setText("");
    } catch (Exception e) {
        System.out.println("Icon not found");
    }
    delete.setFont(delete.getFont().deriveFont(App.FONT_SIZE));
    delete.setBackground(App.COLOR);
    // Zabere kousek vpravo
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.5;
    c.anchor = GridBagConstraints.EAST;
    this.add(delete, c);

    // Akce pro vytvoen a zkoprovn hesla do schrnky
    passPanel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Generuji kod pro " + data[1]);
            System.out.println(new Base32().decode(data[1].getBytes()).length);
            clip.set(new TOTP(new Base32().decode(data[1].getBytes())).toString());
            System.out.printf("Kd pro %s je ve schrnce\n", data[0]);
            passPanel.setText("Zkoprovno");
            // Zobraz zprvu na 1 vteinu
            int time = 1000;
            // Animace zobrazen zprvy po zkoprovn
            final Timer t = new Timer(time, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    passPanel.setText(data[0]);
                }
            });
            t.start();
            t.setRepeats(false);
        }
    });

    // Akce pro smazn panelu a uloen zmn
    delete.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.printf("Odstrann %s s indexem %d\n", data[0], index);
            p.remove(String.valueOf(index));
            App.saveProperties();
            App.loadProperties();
        }
    });

}

From source file:su.fmi.photoshareclient.remote.ImageHandler.java

public static ImageLabel getImage(int id, String name) {
    try {/*ww  w .j  ava 2 s. c o m*/
        // logic for user verification

        //      Client client = ClientBuilder.newBuilder().newClient();
        //            WebTarget target = client.target("http://94.156.77.61:8080/photoshare");
        //            target = target.path("rest/image/getfile/MiltonStapler.jpg");
        //
        //            Invocation.Builder builder = target.request();
        //            Response response = builder.get();
        //            FileInputStream book = builder.get(FileInputStream.class);
        //            System.out.println("done");
        ProjectProperties props = new ProjectProperties();
        String webPage = "http://" + props.get("socket") + props.get("restEndpoint") + "/image/getfile/" + name;
        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + LoginHandler.getAuthStringEncripted());
        InputStream is = urlConnection.getInputStream();
        //            InputStreamReader isr = new InputStreamReader(is);
        //            
        //            int numCharsRead;
        //            char[] charArray = new char[1024];
        //            StringBuffer sb = new StringBuffer();
        //            while ((numCharsRead = isr.read(charArray)) > 0) {
        //                sb.append(charArray, 0, numCharsRead);
        //            }
        //            String result = sb.toString();
        BufferedImage bi = ImageIO.read(is);
        ImageLabel img = new ImageLabel(bi, id, name);
        return img;

        //            System.out.println("*** BEGIN ***");
        //            System.out.println(result);
        //            System.out.println("*** END ***");
    } catch (MalformedURLException ex) {
        Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}