コード例 #1
0
 /**
  * Decode JBIG2 data using Java ImageIO library.
  *
  * <p>{@inheritDoc}
  */
 public void decode(
     InputStream compressedData, OutputStream result, COSDictionary options, int filterIndex)
     throws IOException {
   /**
    * A working JBIG2 ImageIO plugin is needed to decode JBIG2 encoded streams. The following is
    * known to be working. It can't be bundled with PDFBox because of an incompatible license.
    * http://code.google.com/p/jbig2-imageio/
    */
   Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JBIG2");
   if (!readers.hasNext()) {
     LOG.error("Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.");
     return;
   }
   ImageReader reader = readers.next();
   COSDictionary decodeP = (COSDictionary) options.getDictionaryObject(COSName.DECODE_PARMS);
   COSInteger bits = (COSInteger) options.getDictionaryObject(COSName.BITS_PER_COMPONENT);
   COSStream st = null;
   if (decodeP != null) {
     st = (COSStream) decodeP.getDictionaryObject(COSName.JBIG2_GLOBALS);
   }
   if (st != null) {
     reader.setInput(
         ImageIO.createImageInputStream(
             new SequenceInputStream(st.getFilteredStream(), compressedData)));
   } else {
     reader.setInput(ImageIO.createImageInputStream(compressedData));
   }
   BufferedImage bi = reader.read(0);
   reader.dispose();
   if (bi != null) {
     // I am assuming since JBIG2 is always black and white
     // depending on your renderer this might or might be needed
     if (bi.getColorModel().getPixelSize() != bits.intValue()) {
       if (bits.intValue() != 1) {
         LOG.error("Do not know how to deal with JBIG2 with more than 1 bit");
         return;
       }
       BufferedImage packedImage =
           new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
       Graphics graphics = packedImage.getGraphics();
       graphics.drawImage(bi, 0, 0, null);
       graphics.dispose();
       bi = packedImage;
     }
     DataBuffer dBuf = bi.getData().getDataBuffer();
     if (dBuf.getDataType() == DataBuffer.TYPE_BYTE) {
       result.write(((DataBufferByte) dBuf).getData());
     } else {
       LOG.error("Image data buffer not of type byte but type " + dBuf.getDataType());
     }
   } else {
     LOG.error("Something went wrong when decoding the JBIG2 encoded datastream.");
   }
 }
コード例 #2
0
ファイル: ImageIOHelper.java プロジェクト: AxellH/docs
  /**
   * Gets pixel data of an <code>IIOImage</code> object.
   *
   * @param oimage an <code>IIOImage</code> object
   * @return a byte buffer of pixel data
   * @throws Exception
   */
  public static ByteBuffer getImageByteBuffer(BufferedImage oimage) throws IOException {
    // Get tif writer and set output to file
    ImageWriter writer = new TIFFImageWriterSpi().createWriterInstance();

    // Set up the writeParam
    // We are using the old JAI ImageIO plugin, because for some reason, OCR don't work with
    // TwelveMonkeys' plugin
    ImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(streamMetadata, new IIOImage(oimage, null, null), tiffWriteParam);
    writer.dispose();

    // Read the writed image
    ios.seek(0);
    ImageReader reader = new TIFFImageReaderSpi().createReaderInstance();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(ios, true, true);
    BufferedImage bi;
    try {
      bi = reader.read(0, param);
    } finally {
      reader.dispose();
      ios.close();
    }

    return convertImageData(bi);
  }
コード例 #3
0
ファイル: DicomImageReader.java プロジェクト: rawmahn/dcm4che
  @Override
  public BufferedImage read(int frameIndex, ImageReadParam param) throws IOException {
    readMetadata();
    checkIndex(frameIndex);

    WritableRaster raster;
    if (decompressor != null) {
      decompressor.setInput(iisOfFrame(frameIndex));
      if (LOG.isDebugEnabled()) LOG.debug("Start decompressing frame #" + (frameIndex + 1));
      BufferedImage bi = decompressor.read(0, decompressParam(param));
      if (LOG.isDebugEnabled()) LOG.debug("Finished decompressing frame #" + (frameIndex + 1));
      if (samples > 1) return bi;

      raster = bi.getRaster();
    } else raster = (WritableRaster) readRaster(frameIndex, param);

    ColorModel cm;
    if (pmi.isMonochrome()) {
      int[] overlayGroupOffsets = getActiveOverlayGroupOffsets(param);
      byte[][] overlayData = new byte[overlayGroupOffsets.length][];
      for (int i = 0; i < overlayGroupOffsets.length; i++) {
        overlayData[i] = extractOverlay(overlayGroupOffsets[i], raster);
      }
      cm = createColorModel(8, DataBuffer.TYPE_BYTE);
      SampleModel sm = createSampleModel(DataBuffer.TYPE_BYTE, false);
      raster = applyLUTs(raster, frameIndex, param, sm, 8);
      for (int i = 0; i < overlayGroupOffsets.length; i++) {
        applyOverlay(overlayGroupOffsets[i], raster, frameIndex, param, 8, overlayData[i]);
      }
    } else {
      cm = createColorModel(bitsStored, dataType);
    }
    return new BufferedImage(cm, raster, false, null);
  }
コード例 #4
0
ファイル: DicomImageReader.java プロジェクト: rawmahn/dcm4che
  @Override
  public Raster readRaster(int frameIndex, ImageReadParam param) throws IOException {
    readMetadata();
    checkIndex(frameIndex);

    if (decompressor != null) {
      decompressor.setInput(iisOfFrame(frameIndex));

      if (LOG.isDebugEnabled()) LOG.debug("Start decompressing frame #" + (frameIndex + 1));
      Raster wr =
          pmi.decompress() == pmi && decompressor.canReadRaster()
              ? decompressor.readRaster(0, decompressParam(param))
              : decompressor.read(0, decompressParam(param)).getRaster();
      if (LOG.isDebugEnabled()) LOG.debug("Finished decompressing frame #" + (frameIndex + 1));
      return wr;
    }
    iis.seek(pixeldata.offset + frameIndex * frameLength);
    WritableRaster wr = Raster.createWritableRaster(createSampleModel(dataType, banded), null);
    DataBuffer buf = wr.getDataBuffer();
    if (buf instanceof DataBufferByte) {
      byte[][] data = ((DataBufferByte) buf).getBankData();
      for (byte[] bs : data) iis.readFully(bs);
      if (pixeldata.bigEndian && pixeldataVR.vr == VR.OW) ByteUtils.swapShorts(data);
    } else {
      short[] data = ((DataBufferUShort) buf).getData();
      iis.readFully(data, 0, data.length);
    }
    return wr;
  }
コード例 #5
0
ファイル: ImageSize.java プロジェクト: javagraphics/main
  private static Dimension getSizeUsingImageIO(URL url) throws IOException {
    InputStream in = null;
    ImageInputStream iis = null;
    ImageReader reader = null;
    try {
      in = url.openStream();
      iis = new MemoryCacheImageInputStream(in);
      Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
      if (!it.hasNext()) return null;

      reader = it.next();
      reader.setInput(iis, true, true);

      Dimension d = new Dimension(reader.getWidth(0), reader.getHeight(0));
      if (d.width <= 0 || d.height <= 0)
        throw new RuntimeException("invalid dimensions: " + d.width + "x" + d.height);
      return d;
    } finally {
      try {
        if (reader != null) reader.dispose();
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        if (iis != null) iis.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        if (in != null) in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #6
0
ファイル: GeoTiffTest.java プロジェクト: bradh/imageio-ext
  /**
   * Test Read exploiting JAI-ImageIO tools capabilities
   *
   * @throws FileNotFoundException
   * @throws IOException
   */
  @Test
  public void testGCP() throws FileNotFoundException, IOException {
    if (!isGDALAvailable) {
      return;
    }

    String fileName = "gcp.tif";
    final File file = TestData.file(this, fileName);

    ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance();
    reader.setInput(file);
    GDALCommonIIOImageMetadata metadata = (GDALCommonIIOImageMetadata) reader.getImageMetadata(0);

    final int gcpNumber = metadata.getGcpNumber();
    Assert.assertEquals(gcpNumber, 4);

    final List<GCP> gcps = metadata.getGCPs();
    Assert.assertNotNull(gcps);
    Assert.assertFalse(gcps.isEmpty());
    for (int i = 0; i < 4; i++) {
      Assert.assertEquals(gcps.get(i), referenceGCPs.get(i));
    }

    reader.dispose();
  }
コード例 #7
0
ファイル: Prueba.java プロジェクト: frisco82/TuentiContest
  void readAndDisplayMetadata(String fileName) {
    try {

      File file = new File(fileName);
      ImageInputStream iis = ImageIO.createImageInputStream(file);
      Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);

      if (readers.hasNext()) {

        // pick the first available ImageReader
        ImageReader reader = readers.next();

        // attach source to the reader
        reader.setInput(iis, true);

        // read metadata of first image
        IIOMetadata metadata = reader.getImageMetadata(0);

        String[] names = metadata.getMetadataFormatNames();
        int length = names.length;
        for (int i = 0; i < length; i++) {
          System.out.println("Format name: " + names[i]);
          displayMetadata(metadata.getAsTree(names[i]));
        }
      }
    } catch (Exception e) {

      e.printStackTrace();
    }
  }
コード例 #8
0
ファイル: ScanPhoto.java プロジェクト: rpdev/PhotoSorter
 private BufferedImage getImage(File file) {
   ImageInputStream iis = null;
   BufferedImage image = null;
   try {
     iis = ImageIO.createImageInputStream(file);
     Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
     if (!it.hasNext()) throw new UnsupportedOperationException("No image reader fround.");
     ImageReader reader = it.next();
     reader.setInput(iis);
     int scaleFactor;
     if (reader.getWidth(0) >= reader.getHeight(0))
       scaleFactor = Math.round(((float) reader.getWidth(0)) / MAX_SIZE);
     else scaleFactor = Math.round(((float) reader.getHeight(0)) / MAX_SIZE);
     ImageReadParam param = reader.getDefaultReadParam();
     param.setSourceSubsampling(scaleFactor, scaleFactor, 0, 0);
     image = reader.read(0, param);
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (iis != null)
       try {
         iis.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
   }
   return image;
 }
コード例 #9
0
ファイル: TCDocumentObject.java プロジェクト: DicomFlow/repos
    @Override
    protected void ensureContentAvailable() {
      if (!isContentAvailable()) {
        try {
          contentURL = createWadoURL(getMimeType(), -1);
        } catch (Exception e) {
          log.error("Unable to get image document WADO URL!", e);
        }
        try {
          Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("dicom");
          if (readers != null && readers.hasNext()) {
            List<org.dcm4chee.archive.entity.File> files =
                ((TCQueryLocal) JNDIUtils.lookup(TCQueryLocal.JNDI_NAME))
                    .findInstanceByUID(getSOPInstanceUID())
                    .getFiles();
            String fsId = files.get(0).getFileSystem().getDirectoryPath();
            String fileId = files.get(0).getFilePath();

            ImageReader reader = readers.next();
            reader.setInput(
                ImageIO.createImageInputStream(
                    fsId.startsWith("tar:")
                        ? TarRetrieveDelegate.getInstance().retrieveFileFromTar(fsId, fileId)
                        : FileUtils.resolve(new File(fsId, fileId))),
                true);
            contentImage = reader.read(0);
            thumbnailImage = toThumbnailImage(contentImage);
          }
        } catch (Exception e) {
          log.error("Unable to convert encapsulated image to image!", e);
        }
      }
    }
コード例 #10
0
ファイル: GeoTiffTest.java プロジェクト: bradh/imageio-ext
  @Test
  public void testDataTypes() throws IOException, FileNotFoundException {
    if (!isGDALAvailable) {
      return;
    }
    final List<String> fileList = new ArrayList<String>(4);
    fileList.add("paletted.tif");
    fileList.add("utmByte.tif");
    fileList.add("utmInt16.tif");
    fileList.add("utmInt32.tif");
    fileList.add("utmFloat32.tif");
    fileList.add("utmFloat64.tif");

    for (String fileName : fileList) {
      final ImageReadParam irp = new ImageReadParam();
      final File inputFile = TestData.file(this, fileName);
      irp.setSourceSubsampling(1, 1, 0, 0);
      ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance();
      reader.setInput(inputFile);
      final RenderedImage image = reader.readAsRenderedImage(0, irp);
      if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, fileName);
      if (!fileName.contains("paletted")) {
        Assert.assertEquals(256, image.getHeight());
        Assert.assertEquals(256, image.getWidth());
      } else {
        Assert.assertEquals(128, image.getHeight());
        Assert.assertEquals(128, image.getWidth());
      }

      reader.dispose();
    }
  }
コード例 #11
0
ファイル: ImageTools.java プロジェクト: vikasing/crowl
 public Dimension getImageDimensions(InputStream imageStream) {
   ImageInputStream in = null;
   Dimension dimension = null;
   try {
     in = ImageIO.createImageInputStream(imageStream);
     final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
     if (readers.hasNext()) {
       ImageReader reader = readers.next();
       try {
         reader.setInput(in);
         dimension = new Dimension(reader.getWidth(0), reader.getHeight(0));
       } finally {
         reader.dispose();
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (in != null)
       try {
         in.close();
       } catch (Exception e) {
         e.printStackTrace();
       }
   }
   return dimension;
 }
コード例 #12
0
ファイル: ImageIOHelper.java プロジェクト: KeithZhang/zk
  public static BufferedImage getImage(File imageFile) {

    BufferedImage al = null;

    try {

      String imageFileName = imageFile.getName();

      String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);

      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);

      ImageReader reader = readers.next();
      if (reader == null) {

        JOptionPane.showConfirmDialog(
            null, "Need to install JAI Image I/O package./nhttps://jai-imageio.dev.java.net");

        return null;
      }
      ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);
      al = reader.read(0);
      reader.dispose();

    } catch (IOException ioe) {
      System.err.println(ioe.getMessage());
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
    return al;
  }
コード例 #13
0
  /**
   * 图片文件转换为tif格式
   *
   * @param imageFile 文件路径
   * @param imageFormat 文件扩展名
   * @return
   */
  public static File createImage(File imageFile, String imageFormat) {
    File tempFile = null;
    try {
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      ImageReader reader = readers.next();

      ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);
      // Read the stream metadata
      IIOMetadata streamMetadata = reader.getStreamMetadata();

      // Set up the writeParam
      TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.CHINESE);
      tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

      // Get tif writer and set output to file
      Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
      ImageWriter writer = writers.next();

      BufferedImage bi = reader.read(0);
      IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
      tempFile = tempImageFile(imageFile);
      ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
      writer.setOutput(ios);
      writer.write(streamMetadata, image, tiffWriteParam);
      ios.close();

      writer.dispose();
      reader.dispose();

    } catch (IOException e) {
      e.printStackTrace();
    }
    return tempFile;
  }
コード例 #14
0
  @Override
  public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
      throws IOException, HttpMessageNotReadableException {

    ImageInputStream imageInputStream = null;
    ImageReader imageReader = null;
    try {
      imageInputStream = createImageInputStream(inputMessage.getBody());
      MediaType contentType = inputMessage.getHeaders().getContentType();
      Iterator<ImageReader> imageReaders =
          ImageIO.getImageReadersByMIMEType(contentType.toString());
      if (imageReaders.hasNext()) {
        imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        process(irp);
        imageReader.setInput(imageInputStream, true);
        return imageReader.read(0, irp);
      } else {
        throw new HttpMessageNotReadableException(
            "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
      }
    } finally {
      if (imageReader != null) {
        imageReader.dispose();
      }
      if (imageInputStream != null) {
        try {
          imageInputStream.close();
        } catch (IOException ex) {
          // ignore
        }
      }
    }
  }
コード例 #15
0
ファイル: ResourceHelper.java プロジェクト: muh6mm3d/javlo
 public static IIOMetadata getImageMetadata(File image) throws IOException {
   Iterator readers =
       ImageIO.getImageReadersBySuffix(StringHelper.getFileExtension(image.getName()));
   if (StringHelper.isImage(image.getName())) {
     if (!readers.hasNext()) {
       return null;
     } else {
       ImageReader imageReader = (ImageReader) readers.next();
       FileImageInputStream in = new FileImageInputStream(image);
       try {
         imageReader.setInput(in);
         return imageReader.getImageMetadata(0);
       } finally {
         if (in != null) {
           try {
             in.close();
           } catch (Exception e) {
             e.printStackTrace();
           }
         }
       }
     }
   } else {
     return null;
   }
 }
コード例 #16
0
  private Dimension getSize(File file) {
    try {
      ImageInputStream input = ImageIO.createImageInputStream(file);
      if (input != null) {
        try {
          Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
          if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
              reader.setInput(input);
              return new Dimension(reader.getWidth(0), reader.getHeight(0));
            } finally {
              reader.dispose();
            }
          }
        } finally {
          if (input != null) {
            input.close();
          }
        }
      }

      // Fallback: read the image using the normal means
      BufferedImage image = ImageIO.read(file);
      if (image != null) {
        return new Dimension(image.getWidth(), image.getHeight());
      } else {
        return null;
      }
    } catch (IOException e) {
      // Pass -- we can't handle all image types, warn about those we can
      return null;
    }
  }
コード例 #17
0
  /**
   * Gets a list of <code>IIOImage</code> objects for an image file.
   *
   * @param imageFile input image file. It can be any of the supported formats, including TIFF,
   *     JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL Ghostscript is installed
   * @return a list of <code>IIOImage</code> objects
   * @throws Exception
   */
  public static List<IIOImage> getIIOImageList(File imageFile) throws IOException {
    File workingTiffFile = null;

    ImageReader reader = null;
    ImageInputStream iis = null;

    try {
      // convert PDF to TIFF
      if (imageFile.getName().toLowerCase().endsWith(".pdf")) {
        workingTiffFile = PdfUtilities.convertPdf2Tiff(imageFile);
        imageFile = workingTiffFile;
      }

      List<IIOImage> iioImageList = new ArrayList<IIOImage>();

      String imageFileName = imageFile.getName();
      String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
      if (imageFormat.matches("(pbm|pgm|ppm)")) {
        imageFormat = "pnm";
      } else if (imageFormat.equals("jp2")) {
        imageFormat = "jpeg2000";
      }
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      reader = readers.next();

      if (reader == null) {
        throw new RuntimeException(
            "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
      }

      iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);

      int imageTotal = reader.getNumImages(true);

      for (int i = 0; i < imageTotal; i++) {
        //                IIOImage oimage = new IIOImage(reader.read(i), null,
        // reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        iioImageList.add(oimage);
      }

      return iioImageList;
    } finally {
      try {
        if (iis != null) {
          iis.close();
        }
        if (reader != null) {
          reader.dispose();
        }
      } catch (Exception e) {
        // ignore
      }
      if (workingTiffFile != null && workingTiffFile.exists()) {
        workingTiffFile.delete();
      }
    }
  }
コード例 #18
0
ファイル: GeoTiffTest.java プロジェクト: bradh/imageio-ext
  /**
   * Test Writing capabilities.
   *
   * @throws FileNotFoundException
   * @throws IOException
   */
  @Test
  public void write() throws IOException, FileNotFoundException {
    if (!isGDALAvailable) {
      return;
    }
    final File outputFile = TestData.temp(this, "writetest.tif", false);
    outputFile.deleteOnExit();
    final File inputFile = TestData.file(this, "utmByte.tif");

    ImageReadParam rparam = new ImageReadParam();
    rparam.setSourceRegion(new Rectangle(1, 1, 300, 500));
    rparam.setSourceSubsampling(1, 2, 0, 0);
    ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance();
    reader.setInput(inputFile);
    final IIOMetadata metadata = reader.getImageMetadata(0);

    final ParameterBlockJAI pbjImageRead = new ParameterBlockJAI("ImageRead");
    pbjImageRead.setParameter("Input", inputFile);
    pbjImageRead.setParameter("reader", reader);
    pbjImageRead.setParameter("readParam", rparam);

    final ImageLayout l = new ImageLayout();
    l.setTileGridXOffset(0).setTileGridYOffset(0).setTileHeight(256).setTileWidth(256);

    RenderedOp image =
        JAI.create("ImageRead", pbjImageRead, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, l));

    if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, "geotiff");

    // ////////////////////////////////////////////////////////////////
    // preparing to write
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageWrite = new ParameterBlockJAI("ImageWrite");
    ImageWriter writer = new GeoTiffImageWriterSpi().createWriterInstance();
    pbjImageWrite.setParameter("Output", outputFile);
    pbjImageWrite.setParameter("writer", writer);
    pbjImageWrite.setParameter("ImageMetadata", metadata);
    pbjImageWrite.setParameter("Transcode", false);
    ImageWriteParam param = new ImageWriteParam(Locale.getDefault());
    param.setSourceRegion(new Rectangle(10, 10, 100, 100));
    param.setSourceSubsampling(2, 1, 0, 0);
    pbjImageWrite.setParameter("writeParam", param);

    pbjImageWrite.addSource(image);
    final RenderedOp op = JAI.create("ImageWrite", pbjImageWrite);
    final ImageWriter writer2 =
        (ImageWriter) op.getProperty(ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER);
    writer2.dispose();

    // ////////////////////////////////////////////////////////////////
    // preparing to read again
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageReRead = new ParameterBlockJAI("ImageRead");
    pbjImageReRead.setParameter("Input", outputFile);
    pbjImageReRead.setParameter("Reader", new GeoTiffImageReaderSpi().createReaderInstance());
    final RenderedOp image2 = JAI.create("ImageRead", pbjImageReRead);
    if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image2, "geotif2");
    else Assert.assertNotNull(image2.getTiles());
  }
コード例 #19
0
ファイル: WebPParser.java プロジェクト: koroshiya/JxReader
  public static BufferedImage decodeWebP(InputStream is) throws IOException {

    ImageReader imageReader = getReader();
    ImageInputStream iis = ImageIO.createImageInputStream(is);
    imageReader.setInput(iis, false);

    return imageReader.read(0);
  }
コード例 #20
0
  @Test
  //    @Ignore
  public void nearestExternal() throws Exception {

    final OverviewsEmbedder oe = new OverviewsEmbedder();
    oe.setDownsampleStep(2);
    oe.setNumSteps(5);
    oe.setScaleAlgorithm(OverviewsEmbedder.SubsampleAlgorithm.Nearest.toString());
    // use default
    oe.setTileCache(JAI.getDefaultInstance().getTileCache());
    oe.setTileWidth(256);
    oe.setTileHeight(256);
    oe.setExternalOverviews(true);
    oe.setSourcePath(TestData.file(this, "DEM_.tiff").getAbsolutePath());
    oe.addProcessingEventListener(
        new ProcessingEventListener() {

          @Override
          public void getNotification(ProcessingEvent event) {
            LOGGER.info(event.toString());
          }

          @Override
          public void exceptionOccurred(ExceptionEvent event) {
            LOGGER.warning(event.toString());
          }
        });
    oe.run();

    // now red it back and check that things are coherent
    final ImageReader reader = new TIFFImageReaderSpi().createReaderInstance();
    reader.setInput(
        ImageIO.createImageInputStream(org.geotools.test.TestData.file(this, "DEM_.tiff")));
    assertTrue(reader.getNumImages(true) == 1);
    reader.reset();

    assertTrue(org.geotools.test.TestData.file(this, "DEM_.tif.ovr").exists());
    reader.setInput(
        ImageIO.createImageInputStream(org.geotools.test.TestData.file(this, "DEM_.tif.ovr")));
    assertTrue(reader.getNumImages(true) == 5);
    assertTrue(reader.isImageTiled(0));
    assertEquals(256, reader.getTileHeight(0));
    assertEquals(256, reader.getTileWidth(0));
    reader.dispose();
  }
コード例 #21
0
  /**
   * Write world image extensions : TFW, PRJ, TAB
   *
   * @param request
   * @param file
   * @param in
   * @throws IOException
   */
  private void writeWorldImageExt(WcsReaderRequest request, File file) throws IOException {

    String baseFilePath = file.getPath().substring(0, file.getPath().lastIndexOf('.'));

    // Compute image size and image transformed BBOX
    ReferencedEnvelope transformedBBox;
    AffineTransform transform;

    int width = -1;
    int height = -1;
    String ext = FileUtils.extension(file);

    try {
      final Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(ext.substring(1));

      while (readers.hasNext() && width < 0 && height < 0) {
        ImageInputStream stream = null;
        try {
          ImageReader reader = readers.next();
          stream = ImageIO.createImageInputStream(file.getAbsoluteFile());
          reader.setInput(stream, true, false);
          width = reader.getWidth(0);
          height = reader.getHeight(0);
          break;
        } catch (Exception e) {
          width = -1;
          height = -1;
          // try next reader;
        } finally {
          if (stream != null) {
            stream.close();
          }
        }
      }

      transformedBBox = request.requestBbox.transform(request.responseCRS, true, 10);
      if (width < 0) {
        width = (int) Math.round(transformedBBox.getWidth() / request.crsResolution());
      }

      if (height < 0) {
        height = (int) Math.round(transformedBBox.getHeight() / request.crsResolution());
      }

      Rectangle imageSize = new Rectangle(width, height);
      transform = RendererUtilities.worldToScreenTransform(transformedBBox, imageSize);
      transform.invert();

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

    // Generate TFW TAB PRJ files
    createWorldFile(transform, ext, baseFilePath);
    createTABFile(transformedBBox, width, height, baseFilePath, ext);
    createPrjFile(request.responseCRS, baseFilePath);
  }
コード例 #22
0
  GranuleOverviewLevelDescriptor getLevel(final int index) {

    // load level
    // create the base grid to world transformation
    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {

      // get a stream
      assert cachedStreamSPI != null : "no cachedStreamSPI available!";
      inStream =
          cachedStreamSPI.createInputStreamInstance(
              granuleUrl, ImageIO.getUseCache(), ImageIO.getCacheDirectory());
      if (inStream == null)
        throw new IllegalArgumentException(
            "Unable to create an inputstream for the granuleurl:"
                + (granuleUrl != null ? granuleUrl : "null"));

      // get a reader and try to cache the relevant SPI
      if (cachedReaderSPI == null) {
        reader = ImageIOExt.getImageioReader(inStream);
        if (reader != null) cachedReaderSPI = reader.getOriginatingProvider();
      } else reader = cachedReaderSPI.createReaderInstance();
      if (reader == null)
        throw new IllegalArgumentException(
            "Unable to get an ImageReader for the provided file " + granuleUrl.toString());
      reader.setInput(inStream);

      // call internal method which will close everything
      return getLevel(index, reader);

    } catch (IllegalStateException e) {

      // clean up
      try {
        if (inStream != null) inStream.close();
      } catch (Throwable ee) {

      } finally {
        if (reader != null) reader.dispose();
      }

      throw new IllegalArgumentException(e);

    } catch (IOException e) {

      // clean up
      try {
        if (inStream != null) inStream.close();
      } catch (Throwable ee) {
      } finally {
        if (reader != null) reader.dispose();
      }

      throw new IllegalArgumentException(e);
    }
  }
コード例 #23
0
ファイル: ImageIOTest.java プロジェクト: ljx407/test
 @Test
 public void metaDataTest() throws IOException {
   Iterator<ImageReader> itrR = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader imageReader = itrR.next();
   ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));
   imageReader.setInput(imageInputStream, true);
   IIOMetadata ioMetadata = imageReader.getImageMetadata(0);
   System.out.println(ioMetadata.toString());
 }
コード例 #24
0
  /**
   * Returns the geotiff metadata for this geotiff file.
   *
   * @return the metadata
   */
  public GeoTiffIIOMetadataDecoder getMetadata() {
    GeoTiffIIOMetadataDecoder metadata = null;
    ImageReader reader = null;
    boolean closeMe = true;
    ImageInputStream stream = null;

    try {
      if ((source instanceof InputStream) || (source instanceof ImageInputStream)) {
        closeMe = false;
      }
      if (source instanceof ImageInputStream) {
        stream = (ImageInputStream) source;
      } else {
        inStreamSPI = ImageIOExt.getImageInputStreamSPI(source);
        if (inStreamSPI == null) {
          throw new IllegalArgumentException("No input stream for the provided source");
        }
        stream =
            inStreamSPI.createInputStreamInstance(
                source, ImageIO.getUseCache(), ImageIO.getCacheDirectory());
      }
      if (stream == null) {
        throw new IllegalArgumentException("No input stream for the provided source");
      }
      stream.mark();
      reader = READER_SPI.createReaderInstance();
      reader.setInput(stream);
      final IIOMetadata iioMetadata = reader.getImageMetadata(0);
      metadata = new GeoTiffIIOMetadataDecoder(iioMetadata);
    } catch (IOException e) {
      if (LOGGER.isLoggable(Level.SEVERE)) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
      }
    } finally {
      if (reader != null)
        try {
          reader.dispose();
        } catch (Throwable t) {
        }

      if (stream != null) {
        try {
          stream.reset();
        } catch (Throwable t) {
        }
        if (closeMe) {
          try {
            stream.close();
          } catch (Throwable t) {
          }
        }
      }
    }
    return metadata;
  }
コード例 #25
0
ファイル: GeoTiffTest.java プロジェクト: bradh/imageio-ext
  /**
   * Test Read on a Paletted Image
   *
   * @throws FileNotFoundException
   * @throws IOException
   */
  @Test
  public void palette() throws FileNotFoundException, IOException {
    if (!isGDALAvailable) {
      return;
    }
    final File outputFile = TestData.temp(this, "writetest.tif", false);
    outputFile.deleteOnExit();
    final File inputFile = TestData.file(this, "paletted.tif");

    ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance();
    reader.setInput(inputFile);
    final IIOMetadata metadata = reader.getImageMetadata(0);

    final ParameterBlockJAI pbjImageRead = new ParameterBlockJAI("ImageRead");
    pbjImageRead.setParameter("Input", inputFile);
    pbjImageRead.setParameter("reader", reader);

    final ImageLayout l = new ImageLayout();
    l.setTileGridXOffset(0).setTileGridYOffset(0).setTileHeight(256).setTileWidth(256);

    RenderedOp image =
        JAI.create("ImageRead", pbjImageRead, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, l));

    if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, "Paletted image read");

    // ////////////////////////////////////////////////////////////////
    // preparing to write
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageWrite = new ParameterBlockJAI("ImageWrite");
    ImageWriter writer = new GeoTiffImageWriterSpi().createWriterInstance();
    pbjImageWrite.setParameter("Output", outputFile);
    pbjImageWrite.setParameter("writer", writer);
    pbjImageWrite.setParameter("ImageMetadata", metadata);
    pbjImageWrite.setParameter("Transcode", false);
    pbjImageWrite.addSource(image);
    final RenderedOp op = JAI.create("ImageWrite", pbjImageWrite);
    final ImageWriter writer2 =
        (ImageWriter) op.getProperty(ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER);
    writer2.dispose();

    // ////////////////////////////////////////////////////////////////
    // preparing to read again
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageReRead = new ParameterBlockJAI("ImageRead");
    pbjImageReRead.setParameter("Input", outputFile);
    pbjImageReRead.setParameter("Reader", new GeoTiffImageReaderSpi().createReaderInstance());
    final RenderedOp image2 = JAI.create("ImageRead", pbjImageReRead);
    if (TestData.isInteractiveTest())
      Viewer.visualizeAllInformation(image2, "Paletted image read back after writing");
    else Assert.assertNotNull(image2.getTiles());
    ImageIOUtilities.disposeImage(image2);
    ImageIOUtilities.disposeImage(image);
  }
コード例 #26
0
ファイル: DicomImageReader.java プロジェクト: rawmahn/dcm4che
  @Override
  public ImageTypeSpecifier getRawImageType(int frameIndex) throws IOException {
    readMetadata();
    checkIndex(frameIndex);

    if (decompressor == null) createImageType(bitsStored, dataType, banded);

    if (isRLELossless()) createImageType(bitsStored, dataType, true);

    decompressor.setInput(iisOfFrame(0));
    return decompressor.getRawImageType(0);
  }
コード例 #27
0
ファイル: ImageIOTest.java プロジェクト: ljx407/test
  @Test
  public void imageReaderTest() throws IOException {
    Iterator<ImageReader> irs = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader imageReader = irs.next();

    ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));

    imageReader.setInput(imageInputStream, true);

    BufferedImage bufferedImage = imageReader.read(0);
    System.out.println(bufferedImage.getWidth());
  }
コード例 #28
0
ファイル: ImageUtil.java プロジェクト: gahzl/bbs
 /*
  * 图片裁剪通用接口
  */
 public static void cutImage(String src, String dest, int x, int y, int w, int h)
     throws IOException {
   Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader reader = (ImageReader) iterator.next();
   InputStream in = new FileInputStream(src);
   ImageInputStream iis = ImageIO.createImageInputStream(in);
   reader.setInput(iis, true);
   ImageReadParam param = reader.getDefaultReadParam();
   Rectangle rect = new Rectangle(x, y, w, h);
   param.setSourceRegion(rect);
   BufferedImage bi = reader.read(0, param);
   ImageIO.write(bi, "jpg", new File(dest));
 }
コード例 #29
0
  /**
   * Creates a list of TIFF image files from an image file. It basically converts images of other
   * formats to TIFF format, or a multi-page TIFF image to multiple TIFF image files.
   *
   * @param imageFile input image file
   * @param index an index of the page; -1 means all pages, as in a multi-page TIFF image
   * @return a list of TIFF image files
   * @throws Exception
   */
  public static List<File> createTiffFiles(File imageFile, int index) throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    String imageFileName = imageFile.getName();
    String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);

    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
    ImageReader reader = readers.next();

    if (reader == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
    reader.setInput(iis);
    // Read the stream metadata
    //        IIOMetadata streamMetadata = reader.getStreamMetadata();

    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    // Read the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    int imageTotal = reader.getNumImages(true);

    for (int i = 0; i < imageTotal; i++) {
      // all if index == -1; otherwise, only index-th
      if (index == -1 || i == index) {
        //                BufferedImage bi = reader.read(i);
        //                IIOImage oimage = new IIOImage(bi, null, reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
        ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
        writer.setOutput(ios);
        writer.write(streamMetadata, oimage, tiffWriteParam);
        ios.close();
        tiffFiles.add(tiffFile);
      }
    }
    writer.dispose();
    reader.dispose();

    return tiffFiles;
  }
コード例 #30
0
ファイル: ImageIOTest.java プロジェクト: ljx407/test
 /**
  * 1、�?过ImageIO获得ImageReader 2、�?过ImageReader获得ImageInputStream 3、指定ImageReader的source 4、获得缩略图的数�?
  * 5、若缩略图大�?,读取缩略图
  */
 @Test
 public void thumbnailTest() throws IOException {
   Iterator<ImageReader> itr = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader imageReader = itr.next();
   ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));
   imageReader.setInput(imageInputStream, true);
   int thumbnailNum = imageReader.getNumThumbnails(0);
   System.out.println(thumbnailNum);
   if (thumbnailNum > 0) {
     BufferedImage bufferedImage = imageReader.readThumbnail(0, 0);
     // TODO 图片其它处理
     System.out.println(bufferedImage.getWidth());
   }
 }