Example usage for javax.imageio.stream FileImageInputStream close

List of usage examples for javax.imageio.stream FileImageInputStream close

Introduction

In this page you can find the example usage for javax.imageio.stream FileImageInputStream close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.bc.util.io.FileUtils.java

public static void copy(File source, File target) throws IOException {
    final byte[] buffer = new byte[ONE_KB * ONE_KB];
    int bytesRead;

    FileImageInputStream sourceStream = null;
    FileImageOutputStream targetStream = null;

    try {//from   ww  w . ja  v  a 2s  .  c  o m
        final File targetDir = target.getParentFile();
        if (!targetDir.isDirectory()) {
            if (!targetDir.mkdirs()) {
                throw new IOException("failed to create target directory: " + targetDir.getAbsolutePath());
            }
        }
        target.createNewFile();

        sourceStream = new FileImageInputStream(source);
        targetStream = new FileImageOutputStream(target);
        while ((bytesRead = sourceStream.read(buffer)) >= 0) {
            targetStream.write(buffer, 0, bytesRead);
        }
    } finally {
        if (sourceStream != null) {
            sourceStream.close();
        }
        if (targetStream != null) {
            targetStream.flush();
            targetStream.close();
        }
    }
}

From source file:de.hpi.fgis.hdrs.node.Index.java

void readMeta() throws IOException {
    File metaFile = new File(indexRoot.getAbsolutePath() + File.separator + METAFILE);
    if (!metaFile.isFile()) {
        throw new IOException("Index meta file not found for index " + order);
    }/* w w  w .j a  v a2  s  .  co  m*/
    segments.clear();
    FileImageInputStream in = new FileImageInputStream(metaFile);
    int size = in.readInt();
    for (int i = 0; i < size; ++i) {
        SegmentInfo info = SegmentInfo.read(in);
        segments.add(info);
    }
    in.close();
}

From source file:edu.stanford.epad.common.dicom.DicomReader.java

/**
 * Generate a buffered image using the parameters in the file.
 * /*from  w  w w  .ja  v  a  2  s  .c  o  m*/
 * @param frameValue frame number
 * @return image
 * @throws IOException
 */
public BufferedImage getImage(int frameValue) throws IOException {
    FileImageInputStream fis = null;
    BufferedImage image;

    try {
        fis = new FileImageInputStream(dicomFile);
        DicomImageReader codec = (DicomImageReader) new DicomImageReaderSpi().createReaderInstance();
        codec.setInput(fis);
        DicomImageReadParam param = (DicomImageReadParam) codec.getDefaultReadParam();
        image = codec.read(frameValue, param);
    } finally {
        if (fis != null)
            fis.close();
    }
    return image;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportExecuteAction.java

/**
 * Writes the preview image into the servlet response
 * @return/*from  w  w w .  java  2  s.  co  m*/
 */
public String showPreviewImage() {
    File imgFile = null;
    if (!leaf) {

        String folderDirectory = "";
        if ("projects-ticon".equals(iconCls)) {
            folderDirectory = ApplicationBean.getInstance().getServletContext().getRealPath(
                    "/" + Constants.DESIGN_DIRECTORY + "/" + Constants.DEFAULTDESIGNPATH + "/img/project.png");
        } else {
            folderDirectory = ApplicationBean.getInstance().getServletContext().getRealPath(
                    "/" + Constants.DESIGN_DIRECTORY + "/" + Constants.DEFAULTDESIGNPATH + "/img/folder.png");
        }
        imgFile = new File(folderDirectory);
    } else {
        File templateDir = ReportBL.getDirTemplate(templateID);
        String imageName = (String) descriptionMap.get(IDescriptionAttributes.PREVIEW_GIF);
        imgFile = new File(templateDir, imageName);
    }
    if (templateID != null) {
        if (imgFile != null && imgFile.exists()) {
            try {
                FileImageInputStream input = new FileImageInputStream(imgFile);
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                byte[] data;
                int numBytesRead;
                while ((numBytesRead = input.read(buf)) != -1) {
                    output.write(buf, 0, numBytesRead);
                }
                data = output.toByteArray();
                output.close();
                input.close();
                servletResponse.setContentType("image/gif");
                OutputStream outputStream = servletResponse.getOutputStream();
                outputStream.write(data);
                outputStream.flush();
            } catch (Exception e) {
                LOGGER.warn("Getting the preview image failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
    return null;
}

From source file:edu.stanford.epad.common.dicom.DicomReader.java

/**
 * Generate a buffered image with the high order bits of PixelData in the red channel and low order bits in the green
 * channel.//www  .j  a  v  a2 s.c o  m
 * 
 * @param frameValue frame number
 * @return image
 * @throws IOException
 */
public BufferedImage getPackedImage(int frameValue) throws IOException {
    FileImageInputStream fis = null;
    DicomInputStream dis = null;
    BufferedImage packedImage = null;

    try {
        StopTagInputHandler stop = new StopTagInputHandler(Tag.PixelData);
        log.info("" + Thread.currentThread().getId() + " Opening Dicom:" + dicomFile.getName());
        dis = new DicomInputStream(dicomFile);
        dis.setHandler(stop);
        DicomObject object = dis.readDicomObject();
        RasterProcessor rasterProcessor = new RasterProcessor(object);
        dis.close();
        fis = new FileImageInputStream(dicomFile);
        DicomImageReader codec = (DicomImageReader) new DicomImageReaderSpi().createReaderInstance();
        codec.setInput(fis);
        DicomImageReadParam param = (DicomImageReadParam) codec.getDefaultReadParam();
        Raster raster = codec.readRaster(frameValue, param);
        packedImage = rasterProcessor.buildPng(raster);
    } finally {
        IOUtils.closeQuietly(dis);
        if (fis != null)
            fis.close();
        log.info("" + Thread.currentThread().getId() + " Closed");
    }
    return packedImage;
}

From source file:de.hpi.fgis.hdrs.node.Node.java

boolean initialize() {
    // read segment id counter
    File storemeta = new File(rootDir.getAbsolutePath() + File.separator + SEGMENT_ID_COUNTER_FILE);
    if (storemeta.isFile()) {
        FileImageInputStream in;
        try {/*from  w w  w . j a  va  2  s  .c om*/
            in = new FileImageInputStream(storemeta);
            segmentIdCounter = in.readInt();
            in.close();
        } catch (IOException ex) {
            LOG.fatal("error while reading store meta file ", ex);
            return false;
        }
    }

    LOG.info("Using segment configuration: " + segmentConf);

    // init indexes
    for (Triple.COLLATION order : orders) {
        try {
            File indexRoot = new File(rootDir.getAbsolutePath() + File.separator + order);

            Index index;
            if (indexRoot.isDirectory()) {
                LOG.info("Opening index " + order);
                index = Index.openIndex(indexRoot, order, this);
            } else {
                LOG.info("Creating index " + order);
                index = Index.createIndex(indexRoot, order, this);
                if (router.getLocalPeer() == router.locateSegment(order, SegmentInfo.getSeed(0))) {
                    index.createSeedSegment();
                }
            }

            indexes.put(order, index);
            router.initialize(order);

        } catch (IOException ex) {
            LOG.fatal("error while opening index " + order, ex);
            return false;
        }
    }

    router.syncLocalCatalog();

    // create segment descriptors
    for (Index index : indexes.values()) {
        for (SegmentInfo info : router.getLocalCatalog().getSegments(index.getOrder())) {
            segments.put(Long.valueOf(info.getSegmentId()),
                    new SegmentDescriptor(SegmentStatus.OFFLINE, info, index));
        }
    }

    LOG.info("Segment catalog initialized: " + router.getLocalCatalog());
    return true;
}

From source file:com.lynk.hrm.ui.dialog.InfoEmployee.java

private void startRead() {
    new SwingWorker<String, Void>() {
        @Override/*from   w ww  .j  a  va 2  s  .  c o  m*/
        protected String doInBackground() throws Exception {
            int result;
            IdCard idCard = new IdCard();
            String photoPath = System.getProperty("user.dir") + "/temp/" + "idCard.bmp";
            WString imageFile = new WString(photoPath);
            result = IdCardLibrary.INSTANCE.OpenCardReader(0, 4, 115200);
            if (result != 0) {
                showErrorMsg(IdCard.getErrorMsg(result));
                return null;
            }
            try {
                result = IdCardLibrary.INSTANCE.GetPersonMsgW(idCard, imageFile);
                if (result == 0) {
                    uiName.setText(idCard.getName());
                    uiNamePy.setText(PinyinUtil.getPinpin(idCard.getName()));
                    uiIdCard.setText(idCard.getCardId());
                    uiGender.setText(idCard.getSex());
                    uiBirthday.setText(idCard.getBirthday());
                    uiAge.setText(Integer.toString(Utils.getAge(idCard.getBirthday())));
                    uiCensusAddress.setText(idCard.getAddress());

                    RenderedImage imgOri = ImageIO.read(new File(photoPath));
                    File imgFile = File.createTempFile("photo_", ".png",
                            new File(System.getProperty("user.dir") + "/temp"));
                    ImageIO.write(imgOri, "png", imgFile);

                    uiPhoto.setImage(imgFile.getPath());
                    uiPhoto.putClientProperty("path", imgFile.getPath());
                    FileImageInputStream fiis = new FileImageInputStream(new File(imgFile.getPath()));
                    byte[] photoByte = new byte[(int) fiis.length()];
                    fiis.read(photoByte);
                    fiis.flush();
                    fiis.close();
                    uiPhoto.putClientProperty("photo", photoByte);

                    IdCardLibrary.INSTANCE.CloseCardReader();
                }
                Thread.sleep(1000);
            } catch (Exception e) {
                showErrorMsg(e);
            }
            return null;
        }
    }.execute();
}

From source file:org.openmrs.obs.handler.ImageHandler.java

/**
 * Currently supports all views and puts the Image file data into the ComplexData object
 * /*from ww w.  ja v  a  2  s.  c  o m*/
 * @see org.openmrs.obs.ComplexObsHandler#getObs(org.openmrs.Obs, java.lang.String)
 */
public Obs getObs(Obs obs, String view) {
    File file = getComplexDataFile(obs);

    // Raw image
    if (ComplexObsHandler.RAW_VIEW.equals(view)) {
        BufferedImage img = null;
        try {
            img = ImageIO.read(file);
        } catch (IOException e) {
            log.error("Trying to read file: " + file.getAbsolutePath(), e);
        }

        ComplexData complexData = new ComplexData(file.getName(), img);

        // Image MIME type
        try {
            FileImageInputStream imgStream = new FileImageInputStream(file);
            Iterator<ImageReader> imgReader = ImageIO.getImageReaders(imgStream);
            imgStream.close();
            if (imgReader.hasNext()) {
                complexData.setMimeType("image/" + imgReader.next().getFormatName().toLowerCase());
            } else {
                log.warn("MIME type of " + file.getAbsolutePath() + " is not known");
            }
        } catch (FileNotFoundException e) {
            log.error("Image " + file.getAbsolutePath() + " was not found", e);
        } catch (IOException e) {
            log.error("Trying to determine MIME type of " + file.getAbsolutePath(), e);
        }

        obs.setComplexData(complexData);
    } else {
        // No other view supported
        // NOTE: if adding support for another view, don't forget to update supportedViews list above
        return null;
    }

    return obs;
}

From source file:org.psystems.dicomweb.Dcm2Dcm.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 *//*from www.j  a  v  a2 s.  c  o m*/
public void recodeImages(File src, File dest) throws IOException {

    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
    FileImageInputStream input = new FileImageInputStream(src);
    reader.setInput(input);
    if (dest.exists())
        dest.delete();
    FileImageOutputStream output = new FileImageOutputStream(dest);
    writer.setOutput(output);
    DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
    DicomObject ds = streamMeta.getDicomObject();
    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
    DicomObject newDs = new BasicDicomObject();
    ds.copyTo(newDs);
    writeMeta.setDicomObject(newDs);
    int frames = ds.getInt(Tag.NumberOfFrames, 1);
    LookupTable lut = prepareBitStrip(writeMeta, reader);
    newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
    if (overwriteObject != null) {
        overwriteObject.copyTo(newDs);
    }
    writer.prepareWriteSequence(writeMeta);
    for (int i = 0; i < frames; i++) {
        WritableRaster r = (WritableRaster) reader.readRaster(i, null);
        ColorModel cm = ColorModelFactory.createColorModel(ds);
        BufferedImage bi = new BufferedImage(cm, r, false, null);
        if (lut != null) {
            lut.lookup(bi.getRaster(), bi.getRaster());
        }
        IIOImage iioimage = new IIOImage(bi, null, null);
        writer.writeToSequence(iioimage, null);
    }
    writer.endWriteSequence();
    output.close();
    input.close();
}

From source file:org.psystems.dicomweb.Dcm2DcmCopy.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 *//*from   w ww. ja  v a 2s. co  m*/
public void recodeImages(File src, File dest) throws IOException {
    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
    FileImageInputStream input = new FileImageInputStream(src);
    reader.setInput(input);
    if (dest.exists())
        dest.delete();
    FileImageOutputStream output = new FileImageOutputStream(dest);
    writer.setOutput(output);
    DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
    DicomObject ds = streamMeta.getDicomObject();
    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
    DicomObject newDs = new BasicDicomObject();
    ds.copyTo(newDs);
    writeMeta.setDicomObject(newDs);
    int frames = ds.getInt(Tag.NumberOfFrames, 1);
    LookupTable lut = prepareBitStrip(writeMeta, reader);
    newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
    if (overwriteObject != null) {
        overwriteObject.copyTo(newDs);
    }
    writer.prepareWriteSequence(writeMeta);
    for (int i = 0; i < frames; i++) {
        WritableRaster r = (WritableRaster) reader.readRaster(i, null);
        ColorModel cm = ColorModelFactory.createColorModel(ds);
        BufferedImage bi = new BufferedImage(cm, r, false, null);
        if (lut != null) {
            lut.lookup(bi.getRaster(), bi.getRaster());
        }
        IIOImage iioimage = new IIOImage(bi, null, null);
        writer.writeToSequence(iioimage, null);
    }
    writer.endWriteSequence();
    output.close();
    input.close();
}