예제 #1
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);
    }
  }
예제 #2
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;
    }
  }
예제 #3
0
파일: CsvFile.java 프로젝트: bcdev/beam
 @Override
 public void close() {
   try {
     stream.close();
   } catch (IOException ignore) {
   }
 }
 public Tuple2<BufferedImage, String> readImageAndFormat(InputStream is)
     throws IOException, IllegalArgumentException {
   ImageInputStream iis = ImageIO.createImageInputStream(is);
   Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
   if (!readers.hasNext()) {
     iis.close();
     throw new IllegalArgumentException("unsupported image type");
   }
   ImageReader reader = readers.next();
   String inputFormat = reader.getFormatName();
   reader.setInput(iis, true, true);
   BufferedImage src = reader.read(0);
   reader.dispose();
   iis.close();
   return new Tuple2<BufferedImage, String>(src, inputFormat.toLowerCase());
 }
예제 #5
0
  @Test
  public void testCloseQuietlyImageInputStreamClosed() throws IOException {
    final ImageInputStream in = new MemoryCacheImageInputStream(new ClosedInputStream());
    in.close();

    IOUtils.closeQuietly(in);
  }
예제 #6
0
  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();
      }
    }
  }
  @Test
  public void testAddAndGetTile() throws InterruptedException, FileNotFoundException, IOException {
    // Input stream to use
    ImageInputStream stream_in = null;
    try {
      stream_in = new FileImageInputStream(TestData.file(this, "world.tiff"));
      // Input RenderedImage to use
      final RenderedOp input =
          ImageReadDescriptor.create(
              stream_in, 0, false, false, false, null, null, null, null, null);

      // Boolean used for checking if the conditions are passed
      final AtomicBoolean passed = new AtomicBoolean(true);
      // Cache creation
      final ConcurrentTileCacheMultiMap cache =
          new ConcurrentTileCacheMultiMap(1000 * 1000, false, 1f, 4);
      // Selection of one tile from the image
      Raster data = input.getTile(input.getMinTileX(), input.getMinTileY());
      // Setting the tile inside the cache
      cache.add(input, input.getMinTileX(), input.getMinTileY(), data);
      // Thread pool to use for doing concurrent access on the cache
      ThreadPoolExecutor executor =
          new ThreadPoolExecutor(
              TOTAL, TOTAL, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000000));
      // Latch used for waiting all the threads to end their work
      final CountDownLatch latch = new CountDownLatch(TOTAL);
      // Cycle for launching various requests
      int counter = TOTAL;
      while (counter > 0) {

        executor.execute(
            new Runnable() {

              public void run() {
                // Get the tile to use
                Raster data = cache.getTile(input, input.getMinTileX(), input.getMinTileY());
                if (data == null) {
                  passed.getAndSet(false);
                }
                latch.countDown();
              }
            });
        // Counter update
        counter--;
      }
      // Waiting all threads to finish
      latch.await();
      // Ensure that all the threads have found the tile
      Assert.assertTrue(passed.get());
    } finally {
      try {
        if (stream_in != null) {
          stream_in.flush();
          stream_in.close();
        }
      } catch (Throwable t) {
        //
      }
    }
  }
  @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
        }
      }
    }
  }
예제 #9
0
 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;
 }
  /**
   * reads an AOT Kx LUT (BBDR breadboard procedure GA_read_LUT_AOD)
   *
   * <p>A LUT value can be accessed with lut.getValue(new double[]{wvlValue, aotValue, hsfValue,
   * aziValue, szaValue, vzaValue, parameterValue});
   *
   * @param sensor The sensor
   * @return LookupTable
   * @throws java.io.IOException when failing to real LUT data
   */
  public static LookupTable getAotKxLookupTable(Sensor sensor) throws IOException {
    ImageInputStream iis = Luts.getAotKxLutData(sensor.getInstrument());
    try {
      // read LUT dimensions and values
      float[] vza = Luts.readDimension(iis);
      int nVza = vza.length;
      float[] sza = Luts.readDimension(iis);
      int nSza = sza.length;
      float[] azi = Luts.readDimension(iis);
      int nAzi = azi.length;
      float[] hsf = Luts.readDimension(iis);
      int nHsf = hsf.length;
      float[] aot = Luts.readDimension(iis);
      int nAot = aot.length;

      float[] kx = new float[] {1.0f, 2.0f};
      int nKx = kx.length;

      float[] wvl = sensor.getWavelength();
      final int nWvl = wvl.length;

      float[] lut = new float[nKx * nVza * nSza * nAzi * nHsf * nAot * nWvl];
      iis.readFully(lut, 0, lut.length);

      return new LookupTable(lut, wvl, aot, hsf, azi, sza, vza, kx);
    } finally {
      iis.close();
    }
  }
예제 #11
0
 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
  /**
   * 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();
      }
    }
  }
예제 #13
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);
  }
 /**
  * Disposes this reader.
  *
  * <p>This method just tries to close the underlying {@link ImageInputStream}.
  */
 public void dispose() {
   if (inStream != null && closeMe) {
     try {
       inStream.close();
     } catch (IOException e) {
       if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
     }
   }
 }
  /**
   * {@inheritDoc}
   *
   * @return GridCoverageReader.
   */
  @Override
  public GridCoverageReader convert(final ReferenceType source, final Map<String, Object> params)
      throws UnconvertibleObjectException {

    final InputStream stream = getInputStreamFromReference(source);

    String encoding = null;
    if (params != null && params.get(ENCODING) != null) {
      encoding = (String) params.get(ENCODING);
    }
    ImageInputStream imageStream = null;
    try {

      // decode form base64 stream
      if (encoding != null && encoding.equals(WPSEncoding.BASE64.getValue())) {
        final String encodedImage = IOUtilities.toString(stream);
        final byte[] byteData = Base64.decode(encodedImage.trim());
        if (byteData != null && byteData.length > 0) {
          try (InputStream is = new ByteArrayInputStream(byteData)) {
            imageStream = ImageIO.createImageInputStream(is);
          }
        }

      } else {
        imageStream = ImageIO.createImageInputStream(stream);
      }

      if (imageStream != null) {
        final ImageReader reader;
        if (source.getMimeType() != null) {
          reader = XImageIO.getReaderByMIMEType(source.getMimeType(), imageStream, null, null);
        } else {
          reader = XImageIO.getReader(imageStream, null, Boolean.FALSE);
        }
        return CoverageIO.createSimpleReader(reader);
      } else {
        throw new UnconvertibleObjectException("Error during image stream acquisition.");
      }

    } catch (MalformedURLException ex) {
      throw new UnconvertibleObjectException(
          "Reference grid coverage invalid input : Malformed url", ex);
    } catch (CoverageStoreException ex) {
      throw new UnconvertibleObjectException(
          "Reference grid coverage invalid input : Can't read coverage", ex);
    } catch (IOException ex) {
      throw new UnconvertibleObjectException("Reference grid coverage invalid input : IO", ex);
    } finally {
      if (imageStream != null) {
        try {
          imageStream.close();
        } catch (IOException ex) {
          LOGGER.log(Level.WARNING, "Error during release the image stream.", ex);
        }
      }
    }
  }
 /**
  * *****************************************************************************************************************
  *
  * @inheritDoc *****************************************************************************
  */
 @Override
 public void close() throws IOException {
   try {
     super.close();
   } finally {
     if (thmInputStream != null) {
       thmInputStream.close(); // TODO: should catch exceptions here?
     }
   }
 }
예제 #17
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;
  }
예제 #18
0
 void cleanup(TestEnvironment env) {
   super.cleanup(env);
   if (inputStream != null) {
     try {
       inputStream.close();
     } catch (IOException e) {
       System.err.println("error closing stream");
     }
     inputStream = null;
   }
 }
예제 #19
0
 public BufferedImage getBufferedImage(String keepLetter) {
   try {
     final InputStream is = getInputStream(keepLetter);
     final ImageInputStream iis = ImageIO.createImageInputStream(is);
     final VP8Decoder vp8Decoder = new VP8Decoder();
     vp8Decoder.decodeFrame(iis, false);
     iis.close();
     return vp8Decoder.getFrame().getBufferedImage();
   } catch (Exception e) {
     return null;
   }
 }
예제 #20
0
 public void runTest(Object ctx, int numReps) {
   final Context ictx = (Context) ctx;
   try {
     do {
       ImageInputStream iis = ictx.createImageInputStream();
       iis.close();
       ictx.closeOriginalStream();
     } while (--numReps >= 0);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
예제 #21
0
  @Test
  public void testCloseQuietlyImageInputStreamOpen() {
    final ImageInputStream in = new MemoryCacheImageInputStream(new NullInputStream(1000));

    IOUtils.closeQuietly(in);

    try {
      in.close();
      fail();
    } catch (IOException e) {
      // This, oddly, the expected behavior of close().
    }
  }
예제 #22
0
  /**
   * Load image data for file and put user data attributes into file.
   *
   * @param file File
   * @return true if file image is loaded.
   * @throws java.io.IOException if image can not be loaded
   */
  private static boolean refresh(@NotNull VirtualFile file) throws IOException {
    Long loadedTimeStamp = file.getUserData(TIMESTAMP_KEY);
    SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
    if (loadedTimeStamp == null
        || loadedTimeStamp.longValue() != file.getTimeStamp()
        || SoftReference.dereference(imageRef) == null) {
      try {
        final byte[] content = file.contentsToByteArray();

        if (ICO_FORMAT.equalsIgnoreCase(file.getExtension())) {
          try {
            final BufferedImage image =
                ICO_IMAGE_PARSER.getBufferedImage(new ByteSourceArray(content), null);
            file.putUserData(FORMAT_KEY, ICO_FORMAT);
            file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image));
            return true;
          } catch (ImageReadException ignore) {
          }
        }

        InputStream inputStream = new ByteArrayInputStream(content, 0, content.length);
        ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream);
        try {
          Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
          if (imageReaders.hasNext()) {
            ImageReader imageReader = imageReaders.next();
            try {
              file.putUserData(FORMAT_KEY, imageReader.getFormatName());
              ImageReadParam param = imageReader.getDefaultReadParam();
              imageReader.setInput(imageInputStream, true, true);
              int minIndex = imageReader.getMinIndex();
              BufferedImage image = imageReader.read(minIndex, param);
              file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image));
              return true;
            } finally {
              imageReader.dispose();
            }
          }
        } finally {
          imageInputStream.close();
        }
      } finally {
        // We perform loading no more needed
        file.putUserData(TIMESTAMP_KEY, file.getTimeStamp());
      }
    }
    return false;
  }
예제 #23
0
 /**
  * Retrieve image dimensions. This method simply reads headers so it should perform relatively
  * fast.
  */
 protected static Dimension retrieveImageDimensions(File imageFile) throws IOException {
   long start = System.currentTimeMillis();
   if (!imageFile.exists()) {
     logger.info(
         "No file found while determining image dimensions: " + imageFile.getAbsolutePath());
     return null;
   }
   ImageInputStream iis = null;
   Dimension dimensions = null;
   ImageReader reader = null;
   // use a FileInputStream and make sure it gets closed to prevent unclosed file
   // errors on some operating systems
   FileInputStream fis = null;
   try {
     fis = new FileInputStream(imageFile);
     iis = ImageIO.createImageInputStream(fis);
     Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
     if (readers.hasNext()) {
       reader = readers.next();
       reader.setInput(iis, true);
       dimensions = new Dimension(reader.getWidth(0), reader.getHeight(0));
     }
   } finally {
     if (reader != null) {
       reader.dispose();
     }
     if (iis != null) {
       try {
         iis.close();
       } catch (IOException e) {
         // ignore
       }
     }
     IOUtils.closeQuietly(fis);
   }
   if (logger.isDebugEnabled()) {
     long execution = (System.currentTimeMillis() - start);
     logger.debug(
         "Image dimension lookup for "
             + imageFile.getAbsolutePath()
             + " took "
             + (execution / 1000.000)
             + " s");
   }
   return dimensions;
 }
예제 #24
0
  @Test
  public void test16BitPNG() throws Exception {
    // the resource has been compressed since the palette is way larger than the image itself,
    // and the palette does not get compressed
    InputStream gzippedStream =
        ImageWorkerTest.class.getResource("test-data/sf-sfdem.tif.gz").openStream();
    GZIPInputStream is = new GZIPInputStream(gzippedStream);
    try {
      ImageInputStream iis = ImageIO.createImageInputStream(is);
      ImageReader reader = new TIFFImageReaderSpi().createReaderInstance(iis);
      reader.setInput(iis);
      BufferedImage bi = reader.read(0);
      reader.dispose();
      iis.close();
      IndexColorModel icm = (IndexColorModel) bi.getColorModel();
      assertEquals(65536, icm.getMapSize());

      final File outFile = TestData.temp(this, "temp.png");
      ImageWorker worker = new ImageWorker(bi);
      worker.writePNG(outFile, "FILTERED", 0.75f, true, false);
      worker.dispose();

      // make sure we can read it
      BufferedImage back = ImageIO.read(outFile);

      // we expect a RGB one
      ComponentColorModel ccm = (ComponentColorModel) back.getColorModel();
      assertEquals(3, ccm.getNumColorComponents());

      // now ask to write paletted
      worker = new ImageWorker(bi);
      worker.writePNG(outFile, "FILTERED", 0.75f, true, true);
      worker.dispose();

      // make sure we can read it
      back = ImageIO.read(outFile);

      // we expect a RGB one
      icm = (IndexColorModel) back.getColorModel();
      assertEquals(3, icm.getNumColorComponents());
      assertTrue(icm.getMapSize() <= 256);
    } finally {
      is.close();
    }
  }
예제 #25
0
  /**
   * 得到图片地址路径
   *
   * @param path
   * @return
   */
  public static boolean listDir(String path) {
    File picPath = new File("/home/lifeix/temp/uploadpicPath.txt");
    //		File picPath = new File("/home/lifeix/temp/picPath.txt");
    if (picPath.exists()) {
      try {
        imgsArr = FileUtils.readLines(picPath);
        return true;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    File dir = new File(path);
    File[] files = dir.listFiles();
    for (File file : files) {

      if (file.isDirectory()) {
        listDir(file.getAbsolutePath());
      } else {
        try {
          ImageInputStream is = ImageIO.createImageInputStream(file);
          if (is != null && file.getAbsolutePath().endsWith(".jpg")) {
            imgsArr.add(file.getAbsolutePath());
            System.out.println(file.getAbsolutePath());
          }
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        //				System.out.println(file.getAbsolutePath());
        // System.out.println(file.getParent() + "-->" + file.getName());
      }
    }

    if (picPath.exists()) {
      try {
        FileUtils.writeLines(picPath, imgsArr);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return true;
  }
  /**
   * *****************************************************************************************************************
   *
   * @inheritDoc
   *     ****************************************************************************************************************
   */
  public boolean canDecodeInput(Object source) throws IOException {
    if (source instanceof ImageInputStream) {
      return canDecodeInput((ImageInputStream) source);
    } else {
      ImageInputStream iis = null;

      try {
        iis = ImageIO.createImageInputStream(source);

        if (iis != null) {
          return canDecodeInput(iis);
        }
      } finally {
        if (iis != null) {
          iis.close();
        }
      }
    }

    return false;
  }
예제 #27
0
  @Test
  public void test16BitGIF() throws Exception {
    // the resource has been compressed since the palette is way larger than the image itself,
    // and the palette does not get compressed
    InputStream gzippedStream =
        ImageWorkerTest.class.getResource("test-data/sf-sfdem.tif.gz").openStream();
    GZIPInputStream is = new GZIPInputStream(gzippedStream);
    try {
      ImageInputStream iis = ImageIO.createImageInputStream(is);
      ImageReader reader = new TIFFImageReaderSpi().createReaderInstance(iis);
      reader.setInput(iis);
      BufferedImage bi = reader.read(0);
      if (TestData.isInteractiveTest()) {
        ImageIOUtilities.visualize(bi, "before");
      }
      reader.dispose();
      iis.close();
      IndexColorModel icm = (IndexColorModel) bi.getColorModel();
      assertEquals(65536, icm.getMapSize());

      final File outFile = TestData.temp(this, "temp.gif");
      ImageWorker worker = new ImageWorker(bi);
      worker.writeGIF(outFile, "LZW", 0.75f);

      // Read it back.
      bi = ImageIO.read(outFile);
      if (TestData.isInteractiveTest()) {
        ImageIOUtilities.visualize(bi, "after");
      }
      ColorModel cm = bi.getColorModel();
      assertTrue("wrong color model", cm instanceof IndexColorModel);
      assertEquals("wrong transparency model", Transparency.OPAQUE, cm.getTransparency());
      final IndexColorModel indexColorModel = (IndexColorModel) cm;
      assertEquals("wrong transparent color index", -1, indexColorModel.getTransparentPixel());
      assertEquals("wrong component size", 8, indexColorModel.getComponentSize(0));
      outFile.delete();
    } finally {
      is.close();
    }
  }
  /**
   * reads a NSky DW LUT (BBDR breadboard procedure GA_read_LUT_Nsky, first LUT) * This LUT is
   * equivalent to the original IDL LUT. * A LUT value can be accessed with lut.getValue(new
   * double[]{wvlValue, ozoValue, cwvValue, angValue, kxValue, kxcaseValue});
   *
   * @param sensor The sensor
   * @return LookupTable
   * @throws java.io.IOException when failing to real LUT data
   */
  public static NskyLookupTable getNskyLookupTableDw(Sensor sensor) throws IOException {
    ImageInputStream iis = Luts.getNskyDwLutData(sensor.getInstrument());
    try {
      // read LUT dimensions and values
      float[] sza = Luts.readDimension(iis);
      int nSza = sza.length;
      float[] hsf = Luts.readDimension(iis);
      int nHsf = hsf.length;
      float[] aot = Luts.readDimension(iis);
      int nAot = aot.length;

      int nSpec = iis.readInt();
      float[] spec = new float[nSpec];
      for (int i = 0; i < spec.length; i++) {
        spec[i] = (i + 1) * 1.0f;
      }

      double kppVol = iis.readDouble();
      double kppGeo = iis.readDouble();

      // todo: again, we have an array of length 2 as innermost part of the LUT,
      // which has no meanigful name in breadboard --> clarify
      float[] values = new float[] {1.0f, 2.0f};
      int nValues = values.length;

      float[] lut = new float[nValues * nSza * nHsf * nAot * nSpec];
      iis.readFully(lut, 0, lut.length);

      // store in original sequence (see breadboard: GA_read_LUT_Nsky)
      NskyLookupTable nskyLut = new NskyLookupTable();
      nskyLut.setLut(new LookupTable(lut, spec, aot, hsf, sza, values));
      nskyLut.setKppGeo(kppGeo);
      nskyLut.setKppVol(kppVol);

      return nskyLut;
    } finally {
      iis.close();
    }
  }
예제 #29
0
  /**
   * 图片截取
   *
   * @param file
   * @param newName
   * @param path
   * @param x
   * @param y
   * @param width
   * @param height
   * @return author:caobo date:Oct 14, 2009 12:38:05 PM
   */
  public static File cutting(
      File file, String newName, String path, int x, int y, int width, int height) {
    ImageOutputStream out = null;
    InputStream is = null;
    ImageInputStream iis = null;
    try {
      String endName = file.getName();
      endName = endName.substring(endName.lastIndexOf(".") + 1);
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(endName);
      ImageReader reader = (ImageReader) readers.next();
      is = new FileInputStream(file);
      iis = ImageIO.createImageInputStream(is);
      reader.setInput(iis, true);

      ImageReadParam param = reader.getDefaultReadParam();
      Rectangle rect = new Rectangle(x, y, width, height);
      param.setSourceRegion(rect);
      BufferedImage bi = reader.read(0, param);
      File newFile = new File(path);

      if (!newFile.exists()) newFile.mkdirs();
      newFile = new File(path, newName);
      out = ImageIO.createImageOutputStream(new FileOutputStream(newFile));
      ImageIO.write(bi, endName, out);
      file = newFile;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        iis.close();
        is.close();
        out.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return file;
  }
  public static void extract(File original, final File thumb, final File proof) throws IOException {
    ImageInputStream in = new FileImageInputStream(original);

    new CiffReader()
        .read(
            in,
            new ReaderHandler() {

              public boolean startFolder(int tag, String name) {
                return (tag == 0);
              }

              public void endFolder() {}

              public ValueAction atValue(int tag, String name, int count) {
                boolean stream =
                    ((thumb != null) && (tag == THUMB_TAG))
                        || ((proof != null) && (tag == PROOF_TAG));

                return (stream) ? ValueAction.RAW : ValueAction.SKIP;
              }

              public void handleValue(int tag, String name, int count, Object value) {}

              public void handleRawValue(int tag, String name, int count, ImageInputStream is)
                  throws IOException {
                File file = (tag == THUMB_TAG) ? thumb : proof;
                stream(is, new FileOutputStream(file), count);
              }

              public String getMake() {
                return null;
              }
            });

    in.close();
  }