Example #1
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();
      }
    }
  }
 public static void finalizeReaders(ImageReader... ireaders) throws IOException {
   for (ImageReader reader : ireaders) {
     if (reader != null) {
       reader.dispose();
     }
   }
 }
Example #3
0
  @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);
  }
Example #4
0
  /**
   * 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);
  }
Example #5
0
  @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;
  }
  @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
        }
      }
    }
  }
Example #7
0
  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();
    }
  }
Example #8
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;
 }
Example #9
0
  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;
  }
Example #10
0
    @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);
        }
      }
    }
Example #11
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;
    }
  }
  /**
   * Gets resolution information about the coverage itself.
   *
   * @param reader an {@link ImageReader} to use for getting the resolution information.
   * @throws IOException
   * @throws TransformException
   * @throws DataSourceException
   */
  private void getResolutionInfo(ImageReader reader) throws IOException, TransformException {
    // //
    //
    // get the dimension of the high resolution image and compute the
    // resolution
    //
    // //
    final Rectangle originalDim = new Rectangle(0, 0, reader.getWidth(0), reader.getHeight(0));
    if (originalGridRange == null) {
      originalGridRange = new GridEnvelope2D(originalDim);
    }

    // ///
    //
    // setting the higher resolution available for this coverage
    //
    // ///
    highestRes = CoverageUtilities.getResolution((AffineTransform) raster2Model);

    if (LOGGER.isLoggable(Level.FINE))
      LOGGER.fine(
          new StringBuffer("Highest Resolution = [")
              .append(highestRes[0])
              .append(",")
              .append(highestRes[1])
              .toString());
  }
Example #13
0
  @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();
    }
  }
Example #14
0
 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;
   }
 }
Example #15
0
  /**
   * 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();
  }
  public void readDescendingRasterBand(
      final int sourceOffsetX,
      final int sourceOffsetY,
      final int sourceStepX,
      final int sourceStepY,
      final ProductData destBuffer,
      final int destOffsetX,
      final int destOffsetY,
      final int destWidth,
      final int destHeight,
      final int imageID,
      final ImageIOFile img,
      final int bandSampleOffset,
      final boolean isAntennaPointingRight)
      throws IOException {

    final Raster data;

    synchronized (dataDir) {
      final ImageReader reader = img.getReader();
      final ImageReadParam param = reader.getDefaultReadParam();
      param.setSourceSubsampling(
          sourceStepX, sourceStepY, sourceOffsetX % sourceStepX, sourceOffsetY % sourceStepY);

      final RenderedImage image = reader.readAsRenderedImage(0, param);
      if (flipToSARGeometry && isAntennaPointingRight) { // flip the image left to right
        data =
            image.getData(
                new Rectangle(
                    img.getSceneWidth() - destOffsetX - destWidth,
                    destOffsetY,
                    destWidth,
                    destHeight));
      } else {
        data = image.getData(new Rectangle(destOffsetX, destOffsetY, destWidth, destHeight));
      }
    }

    final DataBuffer dataBuffer = data.getDataBuffer();
    final SampleModel sampleModel = data.getSampleModel();
    final int sampleOffset = imageID + bandSampleOffset;

    if (flipToSARGeometry && isAntennaPointingRight) { // flip the image left to right
      final int[] dArray = new int[destWidth * destHeight];
      sampleModel.getSamples(0, 0, destWidth, destHeight, sampleOffset, dArray, dataBuffer);

      int srcStride, destStride;
      for (int r = 0; r < destHeight; r++) {
        srcStride = r * destWidth;
        destStride = r * destWidth + destWidth;
        for (int c = 0; c < destWidth; c++) {
          destBuffer.setElemIntAt(destStride - c - 1, dArray[srcStride + c]);
        }
      }
    } else { // no flipping is needed
      sampleModel.getSamples(
          0, 0, destWidth, destHeight, sampleOffset, (int[]) destBuffer.getElems(), dataBuffer);
    }
  }
Example #17
0
  /**
   * 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());
  }
Example #18
0
  public static BufferedImage decodeWebP(InputStream is) throws IOException {

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

    return imageReader.read(0);
  }
Example #19
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);
    }
  }
  /**
   * 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);
  }
Example #21
0
 @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());
 }
Example #22
0
 /**
  * The image should be redownloaded when the src attribute changes.
  *
  * @throws Exception if the test fails
  */
 @Test
 public void redownloadOnSrcAttributeChanged() throws Exception {
   final HtmlImage htmlimage = getHtmlElementToTest("image1");
   final ImageReader imagereader = htmlimage.getImageReader();
   htmlimage.setAttribute("src", htmlimage.getAttribute("src") + "#changed");
   Assert.assertFalse(
       "Src attribute changed but ImageReader was not reloaded",
       imagereader.equals(htmlimage.getImageReader()));
 }
 static {
   final Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png");
   if (!imageReaders.hasNext()) {
     throw new SolrException(
         SolrException.ErrorCode.SERVER_ERROR,
         "Can't find png image reader, neaded for heatmaps!");
   }
   ImageReader imageReader = imageReaders.next();
   imageReaderSpi = imageReader.getOriginatingProvider();
 }
  /**
   * 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;
  }
 /**
  * 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.");
   }
 }
Example #26
0
  @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());
  }
Example #27
0
  /**
   * 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);
  }
Example #28
0
  @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);
  }
Example #29
0
 /*
  * 图片裁剪通用接口
  */
 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));
 }
Example #30
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;
 }