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:de.romankreisel.faktotum.beans.BundesbruderBean.java

public BufferedImage getImageFromByteArray(byte[] array) throws IOException {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(array);
    BufferedImage originalImage = ImageIO.read(byteArrayInputStream);
    byteArrayInputStream.close();/*from  w  w w .  j av  a 2  s. co m*/
    return originalImage;
}

From source file:com.xia.ssm.controller.OcrController.java

@RequestMapping("drivingLicense")
public void drivingLicense(@RequestBody String requestMsg, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    String dataString = "";
    ClaimPhoneDTO thPhoneDTO = new ClaimPhoneDTO();
    thPhoneDTO.setResponseCode(ExceptionClaimCode.QUEST_SUCCESS);
    //        String sendType = request.getParameter("SendType");
    //        if(StringUtils.notEmpty(sendType)){
    thPhoneDTO.setSendType("35");
    //        }else{
    //            thPhoneDTO.setResponseCode(ActiveResponseClaimCode.DATA_INTEGRITY_ERROR);
    //        }// ww w .j ava2s . c o  m
    /* String companyCode = request.getParameter("companyCode");
     if(StringUtils.notEmpty(companyCode)){
    thPhoneDTO.setZzbh(companyCode);        
     }else{
    thPhoneDTO.setResponseCode(ActiveResponseClaimCode.DATA_INTEGRITY_ERROR);
     }*/
    if (thPhoneDTO.getSendType().equals(ExceptionClaimCode.DRIVING_LICENSE)) {
        //???  
        //          String fileName = "456.jpg";     
        String fileName = System.currentTimeMillis() + ".jpg";

        //imgetomcatbasePathC:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.20\webapps\flexTest\imge  
        String basePath = request.getSession().getServletContext().getRealPath("/imge/");

        File pathFile = new File(ocrPicPath);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        try {
            String imagePath = "D://11.jpg";//?  
            File file = new File(imagePath);
            FileInputStream in = new FileInputStream(file);
            //??
            BufferedImage bufferedImage = ImageIO.read(in);
            //                BufferedImage bufferedImage = ImageIO.read(request.getInputStream());    
            if (bufferedImage != null) {
                //?  
                ImageIO.write(bufferedImage, "jpeg", new File(ocrPicPath, fileName));
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("??---------------------?"
                    + DateTimeUtil.getNowTimeEnglishString());
            log.error(e.getMessage());
            thPhoneDTO.setResponseCode(ExceptionClaimCode.DRIVERLICENSE_PIC_ERROR);
        }
        // ?flex?  
        thPhoneDTO.setPhotoNames(fileName);
        thPhoneDTO.setAppPath(ocrPicPath);
        thPhoneDTO.setLicenseImg(fileName);

        //? ??
        if (thPhoneDTO.getResponseCode().equals(ExceptionClaimCode.QUEST_SUCCESS)) {
            try {
                thPhoneDTO.setOnlineFlag(onlineFlag);
                thPhoneDTO.setWtAddrUrl(wtAddrUrl);
                thPhoneDTO.setPicType(WTUtils.WT_PIC_TYPE);

                thPhoneDTO = CheckPic.sendPicToWt(thPhoneDTO);

                LicenseDTO licenseDTO = new LicenseDTO();
                BeanUtil.copy(licenseDTO, thPhoneDTO);
                //                    distinguishService.insertLicense(licenseDTO);
                if (thPhoneDTO.getResponseCode().equals(ExceptionClaimCode.QUEST_SUCCESS)) {
                    StringBuffer json = new StringBuffer();

                    json.append("{ResponseCode:'").append(thPhoneDTO.getResponseCode()).append("',")
                            .append("ResponseMessage:'")
                            .append(ExceptionClaimCode.EXCEPTION_CLAIMCODE_MAP
                                    .get(thPhoneDTO.getResponseCode()))
                            .append("',").append("PlateNo:'")
                            .append(thPhoneDTO.getPlateNo() == null ? "" : thPhoneDTO.getPlateNo()).append("',")
                            .append("VehicleType:'")
                            .append(thPhoneDTO.getVehicleType() == null ? "" : thPhoneDTO.getVehicleType())
                            .append("',").append("CustomerName:'")
                            .append(thPhoneDTO.getCustomerName() != null ? thPhoneDTO.getCustomerName() : "")
                            .append("',").append("Address:'")
                            .append(thPhoneDTO.getAddress() != null ? thPhoneDTO.getAddress() : "").append("',")
                            .append("UseType:'")
                            .append(thPhoneDTO.getUseType() == null ? "" : thPhoneDTO.getUseType()).append("',")
                            .append("VehicleModels:'")
                            .append(thPhoneDTO.getVehicleModels() != null ? thPhoneDTO.getVehicleModels() : "")
                            .append("',").append("VIN:'")
                            .append(thPhoneDTO.getVin() != null ? thPhoneDTO.getVin() : "").append("',")
                            .append("EngineNo:'")
                            .append(thPhoneDTO.getEngineNo() != null ? thPhoneDTO.getEngineNo() : "")
                            .append("',").append("RegisterDate:'")
                            .append(thPhoneDTO.getRegisterDate() != null ? thPhoneDTO.getRegisterDate() : "")
                            .append("',").append("IssueDate:'")
                            .append(thPhoneDTO.getIssueDate() != null ? thPhoneDTO.getIssueDate() : "")
                            .append("'}").append("Status:'")
                            .append(thPhoneDTO.getStatus() != null ? thPhoneDTO.getStatus() : "").append("'}")
                            .append("State:'")
                            .append(thPhoneDTO.getState() != null ? thPhoneDTO.getState() : "").append("'}");
                    dataString = json.toString();
                } else {
                    dataString = ClaimPhoneMehthod.buildContentInterFaceJsonError(thPhoneDTO);
                    log.error("??----------------?"
                            + DateTimeUtil.getNowTimeEnglishString());
                }

            } catch (Exception e) {
                ErrorsLogPrintUtil.printToLog4j(log, e);
                log.error("??----------------??"
                        + DateTimeUtil.getNowTimeEnglishString());
                log.error(e.getMessage());
                thPhoneDTO.setResponseCode(ExceptionClaimCode.DRIVERLICENSE_FAILED);
                dataString = ClaimPhoneMehthod.buildContentInterFaceJsonError(thPhoneDTO);
            }
        } else {
            dataString = ClaimPhoneMehthod.buildContentInterFaceJsonError(thPhoneDTO);
        }
    }

}

From source file:com.afis.jx.ckfinder.connector.utils.ImageUtils.java

/**
 * Uploads image and if the image size is larger than maximum allowed it resizes the image.
 *
 * @param stream input stream.//from  w ww.j a  v  a2 s .  c o  m
 * @param file file name
 * @param fileName name of file
 * @param conf connector configuration
 * @throws IOException when error occurs.
 */
public static void createTmpThumb(final InputStream stream, final File file, final String fileName,
        final IConfiguration conf) throws IOException {

    BufferedInputStream bufferedIS = new BufferedInputStream(stream);
    bufferedIS.mark(Integer.MAX_VALUE);
    BufferedImage image = ImageIO.read(bufferedIS);
    if (image == null) {
        throw new IOException("Wrong file");
    }
    Dimension dimension = createThumbDimension(image, conf.getImgWidth(), conf.getImgHeight());
    if (dimension.width == 0 || dimension.height == 0
            || (image.getHeight() == dimension.height && image.getWidth() == dimension.width)) {
        bufferedIS.reset();
        writeUntouchedImage(bufferedIS, file);
    } else {
        resizeImage(image, dimension.width, dimension.height, conf.getImgQuality(), file);
    }
    stream.close();
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

private Optional<BufferedImage> decompressImage(ResponseEntity<byte[]> resp) {
    if (resp.getStatusCode() != HttpStatus.OK) {
        return Optional.empty();
    }/*from w w  w. j  a  v a 2s.  c o m*/

    byte[] compressedBytes = resp.getBody();
    try {
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(compressedBytes));
        return Optional.of(image);
    } catch (IOException e) {
        return Optional.empty();
    }
}

From source file:cish.CISH.java

/**
 * Creates new form CISH//  ww  w. j a v  a2 s.c  o m
 */
public CISH() {
    initComponents();
    try {
        this.setIconImage(ImageIO.read((getClass().getResource("/cish/icon.png"))));
    } catch (IOException ex) {
        Logger.getLogger(CISH.class.getName()).log(Level.SEVERE, null, ex);
    }
    initComponents2();
    drawRatioPlot();
}

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

/**
 * Uploads image and if the image size is larger than maximum allowed it
 * resizes the image./* w  w w  .j a  v a2 s  .  c  om*/
 *
 * @param stream input stream.
 * @param file file name
 * @param fileName name of file
 * @param conf connector configuration
 * @throws IOException when error occurs.
 */
public static void createTmpThumb(final InputStream stream, final File file, final String fileName,
        final IConfiguration conf) throws IOException {

    BufferedInputStream bufferedIS = new BufferedInputStream(stream);
    bufferedIS.mark(Integer.MAX_VALUE);
    BufferedImage image = ImageIO.read(bufferedIS);
    if (image == null) {
        throw new IOException("Wrong file");
    }
    Dimension dimension = createThumbDimension(image, conf.getImgWidth(), conf.getImgHeight());
    if (image.getHeight() == dimension.height && image.getWidth() == dimension.width) {
        bufferedIS.reset();
        writeUntouchedImage(bufferedIS, file);
    } else {
        resizeImage(image, dimension.width, dimension.height, conf.getImgQuality(), file);
    }
    stream.close();
}

From source file:com.joliciel.jochre.search.highlight.ImageSnippet.java

public BufferedImage getImage() {
    try {//from   w ww.  ja v a  2  s .  co  m
        BufferedImage originalImage = ImageIO.read(imageFile);
        BufferedImage imageSnippet = new BufferedImage(this.rectangle.getWidth(), this.rectangle.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        originalImage = originalImage.getSubimage(this.rectangle.getLeft(), this.rectangle.getTop(),
                this.rectangle.getWidth(), this.rectangle.getHeight());
        Graphics2D graphics2D = imageSnippet.createGraphics();
        graphics2D.drawImage(originalImage, 0, 0, this.rectangle.getWidth(), this.rectangle.getHeight(), null);
        int extra = 2;
        for (Rectangle rect : this.highlights) {
            graphics2D.setStroke(new BasicStroke(1));
            graphics2D.setPaint(Color.BLACK);
            graphics2D.drawRect(rect.getLeft() - this.rectangle.getLeft() - extra,
                    rect.getTop() - this.rectangle.getTop() - extra, rect.getWidth() + (extra * 2),
                    rect.getHeight() + (extra * 2));
            graphics2D.setColor(new Color(255, 255, 0, 127));
            graphics2D.fillRect(rect.getLeft() - this.rectangle.getLeft() - extra,
                    rect.getTop() - this.rectangle.getTop() - extra, rect.getWidth() + (extra * 2),
                    rect.getHeight() + (extra * 2));
        }
        return imageSnippet;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java

/**
 * Main GET method/*from w w w .  j  a  va 2s .c o m*/
 * @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 = 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:nosqltools.MainForm.java

/**
 * Creates new form MainForm and sets the necessary properties for the main
 * form/*  w  w  w  .  j ava 2s . co m*/
 */
public MainForm() {
    Image img = null;
    try {
        img = ImageIO.read(new File("resources/mongoicon.png"));
    } catch (IOException e) {
    }
    this.setIconImage(img);
    initComponents();
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    fc.setFileFilter(filter);

    textArea = new RSyntaxTextArea(20, 60);
    textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JSON);
    textArea.setCodeFoldingEnabled(true);
    textArea.setAntiAliasingEnabled(true);
    Table_JSON.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            int row = Table_JSON.rowAtPoint(evt.getPoint());
            int col = Table_JSON.columnAtPoint(evt.getPoint());

            JOptionPane.showMessageDialog(null,
                    "Value in the cell clicked :" + " " + Table_JSON.getValueAt(row, col).toString());

            if (json_util.isArray(Table_JSON.getValueAt(row, col).toString())) {
                if (JOptionPane.showConfirmDialog(null, "View the array as a table:", "VIEW",
                        JOptionPane.OK_CANCEL_OPTION) == JOptionPane.YES_OPTION) {
                    Panel_Views.setEnabled(false);
                    Panel_Connections.setEnabled(false);
                    jMenuBar1.setEnabled(false);

                    if (row >= 0 && col >= 0) {

                        TableForm tableForm = new TableForm(Table_JSON.getValueAt(row, col).toString());
                    }
                }
            }
        }
    });
    RTextScrollPane sp = new RTextScrollPane(textArea);
    sp.setFoldIndicatorEnabled(true);
    Panel_Text.add(sp);
    Save_File.setEnabled(false);

    Panel_Text.setVisible(false);
    Panel_Table.setVisible(false);
    Panel_Hierarchical.setVisible(false);
    Panel_Compare.setVisible(false);
    Panel_Compare_Upper.setVisible(false);
    Panel_Connect.setVisible(false);

    util.changeTextAreaTheme(textArea);

}

From source file:mvc.controller.UsuarioController.java

private void setImagePath(List<Usuario> listaUsuarios) throws IOException {

    for (Usuario usuario : listaUsuarios) {

        BufferedImage bImage = ImageIO.read(new File(usuario.getPhoto()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bImage, "jpg", baos);
        baos.flush();//w  w  w  . j  av  a2 s  .c  om
        byte[] imageInByteArray = baos.toByteArray();
        baos.close();
        String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);
        usuario.setPhoto(b64);

    }

}