Example usage for javax.imageio.stream FileImageInputStream FileImageInputStream

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

Introduction

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

Prototype

public FileImageInputStream(RandomAccessFile raf) 

Source Link

Document

Constructs a FileImageInputStream that will read from a given RandomAccessFile .

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 {//w  w  w. j a  v  a2  s .  co 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:com.jaeksoft.searchlib.util.ImageUtils.java

public static Dimension getDimensions(File imageFile) throws IOException {
    FileImageInputStream fiis = null;
    try {//from   w  w  w  .java2  s  .  c  o  m
        fiis = new FileImageInputStream(imageFile);
        ImageReader imageReader = ImageIO
                .getImageReadersBySuffix(FilenameUtils.getExtension(imageFile.getName())).next();
        imageReader.setInput(fiis);
        return new Dimension(imageReader.getWidth(0), imageReader.getHeight(0));
    } finally {
        IOUtils.close(fiis);
    }
}

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);
    }/*from  w ww  .  ja v  a 2  s .  c o 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:com.aurel.track.admin.customize.category.report.execute.ReportExecuteAction.java

/**
 * Writes the preview image into the servlet response
 * @return/*from w  ww  .ja  v  a  2 s  .c  o  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 using the parameters in the file.
 * //from w w  w  . j av  a2  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: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./*  w  ww.j  a  v a2  s.c om*/
 * 
 * @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:lucee.runtime.img.Image.java

public IIOMetadata getMetaData(Struct parent) {
    InputStream is = null;/*from w ww  .ja v a  2  s  .  c o  m*/
    javax.imageio.stream.ImageInputStreamImpl iis = null;
    try {

        if (source instanceof File) {
            iis = new FileImageInputStream((File) source);
        } else if (source == null)
            iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format, true)));
        else
            iis = new MemoryCacheImageInputStream(is = source.getInputStream());

        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            // pick the first available ImageReader
            ImageReader reader = readers.next();
            IIOMetadata meta = null;
            synchronized (sync) {
                // attach source to the reader
                reader.setInput(iis, true);

                // read metadata of first image
                meta = reader.getImageMetadata(0);
                meta.setFromTree(FORMAT, meta.getAsTree(FORMAT));
                reader.reset();
            }
            // generating dump
            if (parent != null) {
                String[] formatNames = meta.getMetadataFormatNames();
                for (int i = 0; i < formatNames.length; i++) {
                    Node root = meta.getAsTree(formatNames[i]);
                    //print.out(XMLCaster.toString(root));
                    addMetaddata(parent, "metadata", root);
                }
            }
            return meta;
        }
    } catch (Throwable t) {
    } finally {
        ImageUtil.closeEL(iis);
        IOUtil.closeEL(is);
    }
    return null;
}

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;//from ww  w  .  ja  va 2 s .co  m
        try {
            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  . ja  v a 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.apache.carbondata.sdk.file.ImageTest.java

public void binaryToCarbonWithHWD(String sourceImageFolder, String outputPath, String preDestPath,
        String sufAnnotation, final String sufImage, int numToWrite) throws Exception {
    int num = 1;/*w ww.j  a v a  2s  .c om*/
    Field[] fields = new Field[7];
    fields[0] = new Field("height", DataTypes.INT);
    fields[1] = new Field("width", DataTypes.INT);
    fields[2] = new Field("depth", DataTypes.INT);
    fields[3] = new Field("binaryName", DataTypes.STRING);
    fields[4] = new Field("binary", DataTypes.BINARY);
    fields[5] = new Field("labelName", DataTypes.STRING);
    fields[6] = new Field("labelContent", DataTypes.STRING);

    byte[] originBinary = null;

    // read and write image data
    for (int j = 0; j < num; j++) {

        Object[] files = listFiles(sourceImageFolder, sufImage).toArray();

        int index = 0;

        if (null != files) {
            CarbonWriter writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields))
                    .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build();

            for (int i = 0; i < files.length; i++) {
                if (0 == index % numToWrite) {
                    writer.close();
                    writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields))
                            .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build();
                }
                index++;

                // read image and encode to Hex
                File file = new File((String) files[i]);
                System.out.println(file.getCanonicalPath());
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                int depth = 0;
                boolean isGray;
                boolean hasAlpha;
                BufferedImage bufferedImage = null;
                try {
                    bufferedImage = ImageIO.read(file);
                    isGray = bufferedImage.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY;
                    hasAlpha = bufferedImage.getColorModel().hasAlpha();

                    if (isGray) {
                        depth = 1;
                    } else if (hasAlpha) {
                        depth = 4;
                    } else {
                        depth = 3;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(i);
                    ImageInputStream stream = new FileImageInputStream(new File(file.getCanonicalPath()));
                    Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);

                    Exception lastException = null;
                    while (iter.hasNext()) {
                        ImageReader reader = null;
                        try {
                            reader = (ImageReader) iter.next();
                            ImageReadParam param = reader.getDefaultReadParam();
                            reader.setInput(stream, true, true);
                            Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);

                            while (imageTypes.hasNext()) {
                                ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                                System.out
                                        .println(imageTypeSpecifier.getColorModel().getColorSpace().getType());
                                int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                                if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                                    param.setDestinationType(imageTypeSpecifier);
                                    break;
                                }
                            }
                            bufferedImage = reader.read(0, param);
                            isGray = bufferedImage.getColorModel().getColorSpace()
                                    .getType() == ColorSpace.TYPE_GRAY;
                            hasAlpha = bufferedImage.getColorModel().hasAlpha();

                            if (isGray) {
                                depth = 1;
                            } else if (hasAlpha) {
                                depth = 4;
                            } else {
                                depth = 3;
                            }
                            if (null != bufferedImage)
                                break;
                        } catch (Exception e2) {
                            lastException = e2;
                        } finally {
                            if (null != reader)
                                reader.dispose();
                        }
                    }
                    // If you don't have an image at the end of all readers
                    if (null == bufferedImage) {
                        if (null != lastException) {
                            throw lastException;
                        }
                    }
                } finally {
                    originBinary = new byte[bis.available()];
                    while ((bis.read(originBinary)) != -1) {
                    }

                    String txtFileName = file.getCanonicalPath().split(sufImage)[0] + sufAnnotation;
                    BufferedInputStream txtBis = new BufferedInputStream(new FileInputStream(txtFileName));
                    String txtValue = null;
                    byte[] txtBinary = null;
                    txtBinary = new byte[txtBis.available()];
                    while ((txtBis.read(txtBinary)) != -1) {
                        txtValue = new String(txtBinary, "UTF-8");
                    }
                    // write data
                    writer.write(new Object[] { bufferedImage.getHeight(), bufferedImage.getWidth(), depth,
                            file.getCanonicalPath(), originBinary, txtFileName, txtValue.replace("\n", "") });
                    bis.close();
                }
            }
            writer.close();
        }
    }

    CarbonReader reader = CarbonReader.builder(outputPath).build();

    System.out.println("\nData:");
    int i = 0;
    while (i < 20 && reader.hasNext()) {
        Object[] row = (Object[]) reader.readNextRow();

        byte[] outputBinary = (byte[]) row[1];
        System.out.println(row[2] + " " + row[3] + " " + row[4] + " " + row[5] + " image size:"
                + outputBinary.length + " " + row[0]);

        // save image, user can compare the save image and original image
        String destString = preDestPath + i + sufImage;
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString));
        bos.write(outputBinary);
        bos.close();
        i++;
    }
    System.out.println("\nFinished");
    reader.close();
}