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:neembuu.uploader.captcha.ImagePanel.java

public final void update(URL imageFileUrl, HttpContext httpContext) {
    try {//from  ww w. j  a  va 2s  .c  o m
        HttpClient httpClient = NUHttpClient.getHttpClient();
        HttpGet httpGet = new HttpGet(imageFileUrl.toURI());
        HttpResponse httpresponse = httpClient.execute(httpGet, httpContext);
        byte[] imageInByte = EntityUtils.toByteArray(httpresponse.getEntity());
        InputStream in = new ByteArrayInputStream(imageInByte);
        image = ImageIO.read(in);
        //image = ImageIO.read(imageFileUrl);
    } catch (Exception ex) {
        NULogger.getLogger().log(Level.INFO, "ImagePanel exception: {0}", ex.getMessage());
    }
}

From source file:fi.helsinki.opintoni.service.ImageService.java

@SkipLoggingAspect
public BufferedImage inputStreamToBufferedImage(InputStream inputStream) {
    try {//from   w ww  .j  a v a  2  s  .co m
        return ImageIO.read(inputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:modmanager.MainWindow.java

/**
 * Creates new form MainWindow//from   w w  w  . j  a  v a2 s. c  om
 */
public MainWindow() {
    modifications = new ModificationManager();

    initComponents();

    /**
     * Set icon of this app
     */
    try {
        this.setIconImage(ImageIO.read(MainWindow.class.getResourceAsStream("/resources/Icon.png")));
    } catch (IOException ex) {
        Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
    }

    registerAsyncActions();
    modifications.initialize();

    /**
     * Enforce selection of skyrim directory
     */
    if (modifications.getSkyrimDirectory() == null) {
        selectSkyrimDirectory(true);
    }

    modificationList.setModel(modifications.getModificationModel());
    modifications.addModificationListener(this);

    /**
     * Make drag and drop
     */
    registerDnD();

    /**
     * make searchable list
     */
    registerSearch();
}

From source file:com.openkm.util.ImageUtils.java

/**
 * crop/* w ww.ja  v  a  2 s.  co m*/
 */
public static byte[] crop(byte[] img, int x, int y, int width, int height) throws RuntimeException {
    log.debug("crop({}, {}, {}, {}, {})", new Object[] { img.length, x, y, width, height });
    ByteArrayInputStream bais = new ByteArrayInputStream(img);
    byte[] imageInByte;

    try {
        BufferedImage image = ImageIO.read(bais);
        BufferedImage croppedImage = image.getSubimage(x, y, width, height);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(croppedImage, "png", baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        IOUtils.closeQuietly(baos);
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new RuntimeException("IOException: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(bais);
    }

    log.debug("crop: {}", imageInByte.length);
    return imageInByte;
}

From source file:task5.Histogram.java

private void getImage() {
    String userDir = System.getProperty("user.home");
    JFileChooser fileChooser = new JFileChooser(userDir + "/Desktop");
    int result = fileChooser.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        try {//from www  . jav a2  s . c  o  m
            img = ImageIO.read(selectedFile);
            myframe = get_MYIMAGE();
        } catch (IOException ex) {
            Logger.getLogger(MyImage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:view.statistics.RequestStatsAndPrediction.java

/**
 * Creates new form PredictRequests/*from w w  w .jav a2 s. c om*/
 */
public RequestStatsAndPrediction() throws FileNotFoundException, IOException {
    initComponents();
    FileInputStream imgStream = null;
    File imgfile = new File("..\\BBMS\\src\\images\\drop.png");
    imgStream = new FileInputStream(imgfile);
    BufferedImage bi = ImageIO.read(imgStream);
    ImageIcon myImg = new ImageIcon(bi);
    this.setFrameIcon(myImg);
    setTitle("Request Statistics and Prediction");
    sdcontroller = new SampleDetailsController();
    Calendar calendar = Calendar.getInstance();
    yearChooser.setStartYear(calendar.get(Calendar.YEAR));
    monthChooser.setMonth(calendar.get(calendar.MONTH) + 1);

    int year = yearChooser.getYear();
    int month = monthChooser.getMonth() + 1;

    int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    int currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;

    int data[][] = null;

    try {
        data = sdcontroller.getYearlyRequestCountsOf(month);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(RequestStatsAndPrediction.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(RequestStatsAndPrediction.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (year >= currentYear && month >= currentMonth) {

        try {
            predictText.setText(Predictions.getPredictedRequestsOf(year, month) + "");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(RequestStatsAndPrediction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(RequestStatsAndPrediction.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        JOptionPane.showMessageDialog(this,
                "Predictions available only for future months. Only the graph will be drawn", "Error",
                JOptionPane.ERROR_MESSAGE);
        predictText.setText("Invalid input!");
    }

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    if (data != null) {
        for (int i = 0; i < data[0].length; i++) {
            dataset.setValue(data[1][i], "Bla bla bla", data[0][i] + "");
        }
    }

    JFreeChart chart = ChartFactory.createLineChart3D(
            "Yearly Blood Request Count For The Month of " + getMontName(month + ""), "Year", "Request Count",
            dataset, PlotOrientation.VERTICAL, false, true, false);
    chart.setBackgroundPaint(Color.PINK);
    chart.getTitle().setPaint(Color.RED);
    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.BLUE);

    ChartPanel panel = new ChartPanel(chart);
    panel.setPreferredSize(new java.awt.Dimension(200, 350));
    chartAreaPanel.setLayout(new GridLayout());
    chartAreaPanel.removeAll();
    chartAreaPanel.revalidate();
    chartAreaPanel.add(panel);
    chartAreaPanel.repaint();

    this.repaint();

}

From source file:javafxqrgenerator.model.GeneratorModel.java

public String getQRDecodedData(File f) {
    try {/* w w w.  j  a va2s.c  o m*/
        BufferedImage image = ImageIO.read(f);
        LuminanceSource source = new BufferedImageLuminanceSource(image);

        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Reader reader = new MultiFormatReader();
        Result result = reader.decode(bitmap);
        return result.getText();
    } catch (IOException | NotFoundException | ChecksumException | FormatException e) {
        System.out.println("Error reading QR: " + e.getMessage());
    }
    return null;
}

From source file:iqq.im.action.GetCaptchaImageAction.java

@Override
protected void onHttpStatusOK(QQHttpResponse response) throws QQException, JSONException {
    try {// ww  w.jav a 2  s . c om
        ByteArrayInputStream in = new ByteArrayInputStream(response.getResponseData());
        notifyActionEvent(QQActionEvent.Type.EVT_OK, ImageIO.read(in));
    } catch (IOException e) {
        notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.UNKNOWN_ERROR, e));
    }
}

From source file:org.openmrs.module.complexdatadb.api.handler.ImageDBHandler.java

/**
 * @see org.openmrs.obs.ComplexObsHandler#saveObs(org.openmrs.Obs)
 *///w w  w .j  a va 2s .c o m
@Override
public Obs saveObs(Obs obs) throws APIException {

    // Get the buffered image from the ComplexData.
    BufferedImage img = null;

    Object data = obs.getComplexData().getData();
    if (data instanceof BufferedImage) {
        img = (BufferedImage) data;
    } else if (data instanceof InputStream) {
        try {
            img = ImageIO.read((InputStream) data);
            if (img == null) {
                throw new IllegalArgumentException("Invalid image file");
            }
        } catch (IOException e) {
            throw new APIException(
                    "Unable to convert complex data to a valid input stream and then read it into a buffered image",
                    e);
        }
    }

    if (img == null) {
        throw new APIException("Cannot save complex obs where obsId=" + obs.getObsId()
                + " because its ComplexData.getData() is null.");
    }

    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        String extension = getExtension(obs.getComplexData().getTitle());
        ImageIO.write(img, extension, baos);
        baos.flush();
        byte[] bImage = baos.toByteArray();
        baos.close();

        ComplexDataToDB image = new ComplexDataToDB();

        image.setData(bImage);

        Context.getService(ComplexDataToDBService.class).saveComplexDataToDB(image);

        // Set the Title and URI for the valueComplex
        obs.setValueComplex(extension + " image |" + image.getUuid());

        // Remove the ComlexData from the Obs
        obs.setComplexData(null);

    } catch (IOException ioe) {
        throw new APIException("Trying to write complex obs to the database. ", ioe);
    }

    return obs;
}

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

public static BufferedImage readImage(File imageFile) throws IOException {
    int rotation = getImageRotation(imageFile);
    BufferedImage img = ImageIO.read(imageFile);

    if (rotation == 0) {
        return img;
    }//w ww .  j a  va 2s.c o m

    boolean swapXY = rotation != 180;

    BufferedImage rotated = new BufferedImage(swapXY ? img.getHeight() : img.getWidth(),
            swapXY ? img.getWidth() : img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    g2d.translate((rotated.getWidth() - img.getWidth()) / 2, (rotated.getHeight() - img.getHeight()) / 2);
    g2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);

    g2d.drawImage(img, 0, 0, null);
    g2d.dispose();

    return rotated;
}