Exemplo n.º 1
0
  public BufferedImage readBufferedImage() throws IOException {
    colorModel = getColorModel();
    sampleModel = getSampleModel();
    WritableRaster raster = null;
    BufferedImage image = j2krparam.getDestination();

    int x = destinationRegion.x;
    int y = destinationRegion.y;
    destinationRegion.setLocation(j2krparam.getDestinationOffset());
    if (image == null) {
      // If the destination type is specified, use the color model of it.
      ImageTypeSpecifier type = j2krparam.getDestinationType();
      if (type != null) colorModel = type.getColorModel();

      raster =
          Raster.createWritableRaster(
              sampleModel.createCompatibleSampleModel(
                  destinationRegion.x + destinationRegion.width,
                  destinationRegion.y + destinationRegion.height),
              new Point(0, 0));
      image =
          new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), new Hashtable());
    } else raster = image.getWritableTile(0, 0);

    destImage = image;
    readSubsampledRaster(raster);
    destinationRegion.setLocation(x, y);
    destImage = null;
    return image;
  }
Exemplo n.º 2
0
  protected static BufferedImage getDestination(
      ImageReadParam param, Iterator imageTypes, int width, int height) throws IIOException {
    if (imageTypes == null || !imageTypes.hasNext()) {
      throw new IllegalArgumentException("imageTypes null or empty!");
    }

    BufferedImage dest = null;
    ImageTypeSpecifier imageType = null;

    // If param is non-null, use it
    if (param != null) {
      // Try to get the image itself
      dest = param.getDestination();
      if (dest != null) {
        return dest;
      }

      // No image, get the image type
      imageType = param.getDestinationType();
    }

    // No info from param, use fallback image type
    if (imageType == null) {
      Object o = imageTypes.next();
      if (!(o instanceof ImageTypeSpecifier)) {
        throw new IllegalArgumentException("Non-ImageTypeSpecifier retrieved from imageTypes!");
      }
      imageType = (ImageTypeSpecifier) o;
    } else {
      boolean foundIt = false;
      while (imageTypes.hasNext()) {
        ImageTypeSpecifier type = (ImageTypeSpecifier) imageTypes.next();
        if (type.equals(imageType)) {
          foundIt = true;
          break;
        }
      }

      if (!foundIt) {
        throw new IIOException("Destination type from ImageReadParam does not match!");
      }
    }

    Rectangle srcRegion = new Rectangle(0, 0, 0, 0);
    Rectangle destRegion = new Rectangle(0, 0, 0, 0);
    computeRegions(param, width, height, null, srcRegion, destRegion);

    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;
    // Create a new image based on the type specifier

    if ((long) destWidth * destHeight > Integer.MAX_VALUE) {
      throw new IllegalArgumentException("width*height > Integer.MAX_VALUE!");
    }

    return imageType.createBufferedImage(destWidth, destHeight);
  }
Exemplo n.º 3
0
  private void prepareRead(int imageIndex, ImageReadParam param) throws IOException {
    if (stream == null) {
      throw new IllegalStateException("Input not set!");
    }

    // A null ImageReadParam means we use the default
    if (param == null) {
      param = getDefaultReadParam();
    }

    this.imageReadParam = param;

    seekToImage(imageIndex);

    this.tileOrStripWidth = getTileOrStripWidth();
    this.tileOrStripHeight = getTileOrStripHeight();
    this.planarConfiguration = getPlanarConfiguration();

    this.sourceBands = param.getSourceBands();
    if (sourceBands == null) {
      sourceBands = new int[numBands];
      for (int i = 0; i < numBands; i++) {
        sourceBands[i] = i;
      }
    }

    // Initialize the destination image
    Iterator imageTypes = getImageTypes(imageIndex);
    ImageTypeSpecifier theImageType = ImageUtil.getDestinationType(param, imageTypes);

    int destNumBands = theImageType.getSampleModel().getNumBands();

    this.destinationBands = param.getDestinationBands();
    if (destinationBands == null) {
      destinationBands = new int[destNumBands];
      for (int i = 0; i < destNumBands; i++) {
        destinationBands[i] = i;
      }
    }

    if (sourceBands.length != destinationBands.length) {
      throw new IllegalArgumentException("sourceBands.length != destinationBands.length");
    }

    for (int i = 0; i < sourceBands.length; i++) {
      int sb = sourceBands[i];
      if (sb < 0 || sb >= numBands) {
        throw new IllegalArgumentException("Source band out of range!");
      }
      int db = destinationBands[i];
      if (db < 0 || db >= destNumBands) {
        throw new IllegalArgumentException("Destination band out of range!");
      }
    }
  }
  /**
   * Extract the ImageLayout from the provided reader for the first available image.
   *
   * @param reader an istance of {@link ImageReader}
   * @throws IOException in case an error occurs
   */
  protected void setLayout(ImageReader reader) throws IOException {

    Utilities.ensureNonNull("reader", reader);
    // save ImageLayout
    ImageLayout2 layout = new ImageLayout2();
    ImageTypeSpecifier its = reader.getImageTypes(0).next();
    layout.setColorModel(its.getColorModel()).setSampleModel(its.getSampleModel());
    layout.setMinX(0).setMinY(0).setWidth(reader.getWidth(0)).setHeight(reader.getHeight(0));
    layout
        .setTileGridXOffset(0)
        .setTileGridYOffset(0)
        .setTileWidth(reader.getTileWidth(0))
        .setTileHeight(reader.getTileHeight(0));
    setlayout(layout);
  }
  public boolean canEncodeImage(ImageTypeSpecifier type) {
    int dataType = type.getSampleModel().getDataType();
    if (dataType < DataBuffer.TYPE_BYTE || dataType > DataBuffer.TYPE_INT) return false;

    SampleModel sm = type.getSampleModel();
    int numBands = sm.getNumBands();
    if (!(numBands == 1 || numBands == 3)) return false;

    if (numBands == 1 && dataType != DataBuffer.TYPE_BYTE) return false;

    if (dataType > DataBuffer.TYPE_BYTE && !(sm instanceof SinglePixelPackedSampleModel))
      return false;

    return true;
  }
  public boolean canEncodeImage(ImageTypeSpecifier type) {
    SampleModel sm = type.getSampleModel();
    if (!(sm instanceof MultiPixelPackedSampleModel)) return false;
    if (sm.getSampleSize(0) != 1) return false;

    return true;
  }
Exemplo n.º 7
0
 public void compressJpegFile(
     File infile, File outfile, float compressionQuality, int widthCanvas, int heightCanvas)
     throws IOException {
   // Retrieve jpg image to be compressed
   BufferedImage rendImage = ImageIO.read(infile);
   widthFile = rendImage.getWidth();
   heightFile = rendImage.getHeight();
   double aspectRatioCanvas = widthCanvas / heightCanvas;
   double aspectRatioFile = widthFile / heightFile;
   widthFile = widthCanvas;
   heightFile = widthCanvas / aspectRatioFile;
   if (heightFile > heightCanvas) {
     heightFile = heightCanvas;
     widthFile = heightCanvas * aspectRatioFile;
   }
   this.width = (int) widthFile;
   this.height = (int) heightFile;
   ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(rendImage);
   BufferedImage outImage = its.createBufferedImage(width, height);
   Graphics2D graphics2D = outImage.createGraphics();
   graphics2D.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
   //         graphics2D.drawRenderedImage(rendImage, new AffineTransform());
   graphics2D.drawImage(rendImage, 0, 0, width, height, null);
   // Find a jpeg writer
   ImageWriter writer = null;
   Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
   if (iter.hasNext()) {
     writer = (ImageWriter) iter.next();
   }
   // Prepare output file
   ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
   writer.setOutput(ios);
   // Set the compression quality
   ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
   iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
   iwparam.setCompressionQuality(compressionQuality);
   // Write the image
   writer.write(null, new IIOImage(outImage, null, null), iwparam);
   // infile.delete();
   // Cleanup
   ios.flush();
   writer.dispose();
   ios.close();
   // return
 }
Exemplo n.º 8
0
  public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, ImageWriteParam param) {
    GIFWritableImageMetadata imageMetadata = new GIFWritableImageMetadata();

    // Image dimensions

    SampleModel sampleModel = imageType.getSampleModel();

    Rectangle sourceBounds = new Rectangle(sampleModel.getWidth(), sampleModel.getHeight());
    Dimension destSize = new Dimension();
    computeRegions(sourceBounds, destSize, param);

    imageMetadata.imageWidth = destSize.width;
    imageMetadata.imageHeight = destSize.height;

    // Interlacing

    if (param != null
        && param.canWriteProgressive()
        && param.getProgressiveMode() == ImageWriteParam.MODE_DISABLED) {
      imageMetadata.interlaceFlag = false;
    } else {
      imageMetadata.interlaceFlag = true;
    }

    // Local color table

    ColorModel colorModel = imageType.getColorModel();

    imageMetadata.localColorTable = createColorTable(colorModel, sampleModel);

    // Transparency

    if (colorModel instanceof IndexColorModel) {
      int transparentIndex = ((IndexColorModel) colorModel).getTransparentPixel();
      if (transparentIndex != -1) {
        imageMetadata.transparentColorFlag = true;
        imageMetadata.transparentColorIndex = transparentIndex;
      }
    }

    return imageMetadata;
  }
  private static byte[] convertChartToByteArray(
      Chart chartDetails, JFreeChart chart, int width, int height)
      throws IOException, IIOInvalidTreeException {
    BufferedImage buffImg =
        chart.createBufferedImage(
            width, height, BufferedImage.BITMASK | BufferedImage.SCALE_SMOOTH, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();

    ImageWriteParam writeParam = writer.getDefaultWriteParam();
    ImageTypeSpecifier typeSpecifier =
        ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
    IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);

    if (chartDetails != null) {
      if (chartDetails.getId() == null) {
        chartDetails.setId("%ID%");
      }
      IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry");
      textEntry.setAttribute("keyword", "chart-google-data");
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(bout);
      objectOutputStream.writeObject(chartDetails);
      objectOutputStream.flush();
      textEntry.setAttribute(
          "value",
          (String)
              ChartRendererFactory.getRendererForOutput(ChartRendererGoogleTools.TYPE)
                  .renderChart(chartDetails));

      IIOMetadataNode text = new IIOMetadataNode("tEXt");
      text.appendChild(textEntry);

      IIOMetadataNode root = new IIOMetadataNode("javax_imageio_png_1.0");
      root.appendChild(text);

      metadata.mergeTree("javax_imageio_png_1.0", root);
    }
    // setDPI(metadata);

    final ImageOutputStream stream = ImageIO.createImageOutputStream(baos);
    try {
      writer.setOutput(stream);
      writer.write(metadata, new IIOImage(buffImg, null, metadata), writeParam);
    } finally {
      stream.close();
    }

    byte[] bytes = baos.toByteArray(); // ChartUtilities.encodeAsPNG(buffImg, true, 9);
    return bytes;
  }
Exemplo n.º 10
0
  /**
   * @see ImageWriter#writeImage(java.awt.image.RenderedImage, java.io.OutputStream,
   *     ImageWriterParams)
   */
  public void writeImage(RenderedImage image, OutputStream out, ImageWriterParams params)
      throws IOException {
    Iterator iter;
    iter = ImageIO.getImageWritersByMIMEType(getMIMEType());
    javax.imageio.ImageWriter iiowriter = null;
    try {
      iiowriter = (javax.imageio.ImageWriter) iter.next();
      if (iiowriter != null) {
        iiowriter.addIIOWriteWarningListener(this);

        ImageOutputStream imgout = null;
        try {
          imgout = ImageIO.createImageOutputStream(out);
          ImageWriteParam iwParam = getDefaultWriteParam(iiowriter, image, params);

          ImageTypeSpecifier type;
          if (iwParam.getDestinationType() != null) {
            type = iwParam.getDestinationType();
          } else {
            type = ImageTypeSpecifier.createFromRenderedImage(image);
          }

          // Handle metadata
          IIOMetadata meta = iiowriter.getDefaultImageMetadata(type, iwParam);
          // meta might be null for some JAI codecs as they don't support metadata
          if (params != null && meta != null) {
            meta = updateMetadata(meta, params);
          }

          // Write image
          iiowriter.setOutput(imgout);
          IIOImage iioimg = new IIOImage(image, null, meta);
          iiowriter.write(null, iioimg, iwParam);
        } finally {
          if (imgout != null) {
            System.err.println("closing");
            imgout.close();
          }
        }
      } else {
        throw new UnsupportedOperationException(
            "No ImageIO codec for writing " + getMIMEType() + " is available!");
      }
    } finally {
      if (iiowriter != null) {
        System.err.println("disposing");
        iiowriter.dispose();
      }
    }
  }
Exemplo n.º 11
0
  public static List<File> createTiffFiles(List<IIOImage> imageList, int index, int dpiX, int dpiY)
      throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    // 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();

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

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

    // all if index == -1; otherwise, only index-th
    for (IIOImage oimage : (index == -1 ? imageList : imageList.subList(index, index + 1))) {
      if (dpiX != 0 && dpiY != 0) {
        // Get the default image metadata.
        ImageTypeSpecifier imageType =
            ImageTypeSpecifier.createFromRenderedImage(oimage.getRenderedImage());
        IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, null);
        imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
        oimage.setMetadata(imageMetadata);
      }

      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();

    return tiffFiles;
  }
Exemplo n.º 12
0
  public Iterator getImageTypes(int imageIndex) throws IOException {
    readFile();

    checkIndex(imageIndex);

    // Create a List of ImageTypeSpecifiers that identify the possible image
    // types to which the single JBIG2 image can be decoded. An
    // ImageTypeSpecifier is used with ImageReader's getDestination() method
    // to return an appropriate BufferedImage that contains the decoded
    // image, and is accessed by an application.

    List l = new ArrayList();

    // The JBIG2 reader only uses a single List entry. This entry describes
    // a
    // BufferedImage of TYPE_INT_RGB, which is a commonly used image type.

    l.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY));

    // Return an iterator that retrieves elements from the list.

    return l.iterator();
  }
Exemplo n.º 13
0
  @Override
  public BufferedImage read(final int imageIndex, final ImageReadParam param) throws IOException {
    Iterator<ImageTypeSpecifier> imageTypes = getImageTypes(imageIndex);
    ImageTypeSpecifier rawType = getRawImageType(imageIndex);

    if (header.getPaletteInfo() != PCX.PALETTEINFO_COLOR
        && header.getPaletteInfo() != PCX.PALETTEINFO_GRAY) {
      processWarningOccurred(
          String.format(
              "Unsupported color mode: %d, colors may look incorrect", header.getPaletteInfo()));
    }

    int width = getWidth(imageIndex);
    int height = getHeight(imageIndex);

    BufferedImage destination = getDestination(param, imageTypes, width, height);

    Rectangle srcRegion = new Rectangle();
    Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, destination, srcRegion, destRegion);

    WritableRaster destRaster =
        clipToRect(
            destination.getRaster(),
            destRegion,
            param != null ? param.getDestinationBands() : null);
    checkReadParamBandSettings(param, rawType.getNumBands(), destRaster.getNumBands());

    int compression = header.getCompression();

    // Wrap input (COMPRESSION_RLE is really the only value allowed)
    DataInput input =
        compression == PCX.COMPRESSION_RLE
            ? new DataInputStream(
                new DecoderStream(IIOUtil.createStreamAdapter(imageInput), new RLEDecoder()))
            : imageInput;

    int xSub = param != null ? param.getSourceXSubsampling() : 1;
    int ySub = param != null ? param.getSourceYSubsampling() : 1;

    processImageStarted(imageIndex);

    if (rawType.getColorModel() instanceof IndexColorModel && header.getChannels() > 1) {
      // Bit planes!
      // Create raster from a default 8 bit layout
      WritableRaster rowRaster = GRAYSCALE.createBufferedImage(header.getWidth(), 1).getRaster();

      // Clip to source region
      Raster clippedRow =
          clipRowToRect(
              rowRaster,
              srcRegion,
              param != null ? param.getSourceBands() : null,
              param != null ? param.getSourceXSubsampling() : 1);

      int planeWidth = header.getBytesPerLine();
      byte[] planeData = new byte[planeWidth * 8];

      byte[] rowDataByte = ((DataBufferByte) rowRaster.getDataBuffer()).getData();

      for (int y = 0; y < height; y++) {
        switch (header.getBitsPerPixel()) {
          case 1:
            readRowByte(
                input,
                srcRegion,
                xSub,
                ySub,
                planeData,
                0,
                planeWidth * header.getChannels(),
                destRaster,
                clippedRow,
                y);
            break;
          default:
            throw new AssertionError();
        }

        int pixelPos = 0;
        for (int planePos = 0; planePos < planeWidth; planePos++) {
          BitRotator.bitRotateCW(planeData, planePos, planeWidth, rowDataByte, pixelPos, 1);
          pixelPos += 8;
        }

        processImageProgress(100f * y / height);

        if (y >= srcRegion.y + srcRegion.height) {
          break;
        }

        if (abortRequested()) {
          processReadAborted();
          break;
        }
      }
    } else if (header.getBitsPerPixel() == 24 || header.getBitsPerPixel() == 32) {
      // Can't use width here, as we need to take bytesPerLine into account, and re-create a width
      // based on this
      int rowWidth = (header.getBytesPerLine() * 8) / header.getBitsPerPixel();
      WritableRaster rowRaster = rawType.createBufferedImage(rowWidth, 1).getRaster();

      // Clip to source region
      Raster clippedRow =
          clipRowToRect(
              rowRaster,
              srcRegion,
              param != null ? param.getSourceBands() : null,
              param != null ? param.getSourceXSubsampling() : 1);

      for (int y = 0; y < height; y++) {
        byte[] rowDataByte = ((DataBufferByte) rowRaster.getDataBuffer()).getData();
        readRowByte(
            input,
            srcRegion,
            xSub,
            ySub,
            rowDataByte,
            0,
            rowDataByte.length,
            destRaster,
            clippedRow,
            y);

        processImageProgress(100f * y / height);

        if (y >= srcRegion.y + srcRegion.height) {
          break;
        }

        if (abortRequested()) {
          processReadAborted();
          break;
        }
      }
    } else {
      // Can't use width here, as we need to take bytesPerLine into account, and re-create a width
      // based on this
      int rowWidth = (header.getBytesPerLine() * 8) / header.getBitsPerPixel();
      WritableRaster rowRaster = rawType.createBufferedImage(rowWidth, 1).getRaster();

      // Clip to source region
      Raster clippedRow =
          clipRowToRect(
              rowRaster,
              srcRegion,
              param != null ? param.getSourceBands() : null,
              param != null ? param.getSourceXSubsampling() : 1);

      for (int y = 0; y < height; y++) {
        for (int c = 0; c < header.getChannels(); c++) {
          WritableRaster destChannel =
              destRaster.createWritableChild(
                  destRaster.getMinX(),
                  destRaster.getMinY(),
                  destRaster.getWidth(),
                  destRaster.getHeight(),
                  0,
                  0,
                  new int[] {c});
          Raster srcChannel =
              clippedRow.createChild(
                  clippedRow.getMinX(), 0, clippedRow.getWidth(), 1, 0, 0, new int[] {c});

          switch (header.getBitsPerPixel()) {
            case 1:
            case 2:
            case 4:
            case 8:
              byte[] rowDataByte = ((DataBufferByte) rowRaster.getDataBuffer()).getData(c);
              readRowByte(
                  input,
                  srcRegion,
                  xSub,
                  ySub,
                  rowDataByte,
                  0,
                  rowDataByte.length,
                  destChannel,
                  srcChannel,
                  y);
              break;
            default:
              throw new AssertionError();
          }

          if (abortRequested()) {
            break;
          }
        }

        processImageProgress(100f * y / height);

        if (y >= srcRegion.y + srcRegion.height) {
          break;
        }

        if (abortRequested()) {
          processReadAborted();
          break;
        }
      }
    }

    processImageComplete();

    return destination;
  }
 public SampleModel getSampleModel() {
   return its.getSampleModel();
 }
  /**
   * @see GridCoverageReader#read(GeneralParameterValue[])
   * @return A new {@linkplain GridCoverage grid coverage} from the input source, or {@code null} if
   *     the requested envelope is outside the data bounds
   */
  public GridCoverage2D read(GeneralParameterValue[] params) throws IOException {
    final GeneralEnvelope requestedEnvelope;
    final GridEnvelope requestedDim;
    final OverviewPolicy overviewPolicy;
    {
      final ReadParameters opParams = parseReadParams(params);
      overviewPolicy = opParams.overviewPolicy;
      requestedEnvelope = opParams.requestedEnvelope;
      requestedDim = opParams.dim;
    }

    /*
     * For each raster in the raster dataset, obtain the tiles, pixel range, and resulting
     * envelope
     */
    final List<RasterQueryInfo> queries;
    queries = findMatchingRasters(requestedEnvelope, requestedDim, overviewPolicy);
    if (queries.isEmpty()) {
      if (requestedEnvelope.intersects(getOriginalEnvelope(), true)) {
        /*
         * No matching rasters but envelopes intersect, meaning it's a raster catalog with
         * irregular coverage and the request lies on an area with no coverage
         */
        ImageTypeSpecifier imageTypeSpecifier;
        imageTypeSpecifier = RasterUtils.createFullImageTypeSpecifier(rasterInfo, 0);
        SampleModel sampleModel = imageTypeSpecifier.getSampleModel();
        Point location = new Point(0, 0);
        WritableRaster raster = Raster.createWritableRaster(sampleModel, location);
        GridCoverage2D emptyCoverage;
        emptyCoverage = coverageFactory.create(coverageName, raster, requestedEnvelope);
        return emptyCoverage;
      }
      /*
       * none of the rasters match the requested envelope.
       */
      return null;
    }

    final LoggingHelper log = new LoggingHelper();

    /*
     * Once we collected the matching rasters and their image subsets, find out where in the
     * overall resulting mosaic they fit. If the rasters does not share the spatial resolution,
     * the QueryInfo.resultDimension and QueryInfo.mosaicLocation width or height won't match
     */
    final GridEnvelope mosaicGeometry;
    mosaicGeometry = RasterUtils.setMosaicLocations(rasterInfo, queries);

    if (mosaicGeometry.getSpan(0) == 0 || mosaicGeometry.getSpan(1) == 0) {
      LOGGER.finer(
          "Mosaic geometry width or height is zero,"
              + " returning fake coverage for pixels "
              + mosaicGeometry);
      return null;
    }
    /*
     * Gather the rendered images for each of the rasters that match the requested envelope
     */
    final TiledRasterReader rasterReader = rasterReaderFactory.create(rasterInfo);

    try {
      readAllTiledRasters(queries, rasterReader, log);
    } finally {
      // rasterReader.dispose();
    }

    log.log(LoggingHelper.REQ_ENV);
    log.log(LoggingHelper.RES_ENV);
    log.log(LoggingHelper.MOSAIC_ENV);
    log.log(LoggingHelper.MOSAIC_EXPECTED);

    final RenderedImage coverageRaster = createMosaic(queries, mosaicGeometry, log);

    assert mosaicGeometry.getSpan(0) == coverageRaster.getWidth();
    assert mosaicGeometry.getSpan(1) == coverageRaster.getHeight();

    /*
     * BUILDING COVERAGE
     */
    GridSampleDimension[] bands = getSampleDimensions(coverageRaster);

    final GeneralEnvelope resultEnvelope = getResultEnvelope(queries, mosaicGeometry);
    log.appendLoggingGeometries(LoggingHelper.REQ_ENV, requestedEnvelope);
    log.appendLoggingGeometries(LoggingHelper.RES_ENV, resultEnvelope);

    GridCoverage2D resultCoverage =
        coverageFactory.create(coverageName, coverageRaster, resultEnvelope, bands, null, null);

    // MathTransform gridToCRS = rasterInfo.getRasterToModel(queries.get(0).getRasterIndex(),
    // queries.get(0).getPyramidLevel());
    //
    // GridGeometry2D gridGeometry = new GridGeometry2D(PixelInCell.CELL_CORNER, gridToCRS,
    // resultEnvelope, hints);
    //
    // GridCoverage[] sources = null;
    // Map<?, ?> properties = null;
    // GridCoverage2D resultCoverage = coverageFactory.create(coverageName, coverageRaster,
    // gridGeometry, bands, sources, properties);
    return resultCoverage;
  }
Exemplo n.º 16
0
  public RawRenderedImage(
      RawImageInputStream iis, RawImageReader reader, ImageReadParam param, int imageIndex)
      throws IOException {
    this.iis = iis;
    this.reader = reader;
    this.param = param;
    this.imageIndex = imageIndex;
    this.position = iis.getImageOffset(imageIndex);
    this.originalDimension = iis.getImageDimension(imageIndex);

    ImageTypeSpecifier type = iis.getImageType();
    sampleModel = originalSampleModel = type.getSampleModel();
    colorModel = type.getColorModel();

    // If the destination band is set used it
    sourceBands = (param == null) ? null : param.getSourceBands();

    if (sourceBands == null) {
      nComp = originalSampleModel.getNumBands();
      sourceBands = new int[nComp];
      for (int i = 0; i < nComp; i++) sourceBands[i] = i;
    } else {
      sampleModel = originalSampleModel.createSubsetSampleModel(sourceBands);
      colorModel = ImageUtil.createColorModel(null, sampleModel);
    }

    nComp = sourceBands.length;

    destinationBands = (param == null) ? null : param.getDestinationBands();
    if (destinationBands == null) {
      destinationBands = new int[nComp];
      for (int i = 0; i < nComp; i++) destinationBands[i] = i;
    }

    Dimension dim = iis.getImageDimension(imageIndex);
    this.width = dim.width;
    this.height = dim.height;

    Rectangle sourceRegion = new Rectangle(0, 0, this.width, this.height);

    originalRegion = (Rectangle) sourceRegion.clone();

    destinationRegion = (Rectangle) sourceRegion.clone();

    if (param != null) {
      RawImageReader.computeRegionsWrapper(
          param, this.width, this.height, param.getDestination(), sourceRegion, destinationRegion);
      scaleX = param.getSourceXSubsampling();
      scaleY = param.getSourceYSubsampling();
      xOffset = param.getSubsamplingXOffset();
      yOffset = param.getSubsamplingYOffset();
    }

    sourceOrigin = new Point(sourceRegion.x, sourceRegion.y);
    if (!destinationRegion.equals(sourceRegion)) noTransform = false;

    this.tileDataSize = ImageUtil.getTileSize(originalSampleModel);

    this.tileWidth = originalSampleModel.getWidth();
    this.tileHeight = originalSampleModel.getHeight();
    this.tileGridXOffset = destinationRegion.x;
    this.tileGridYOffset = destinationRegion.y;
    this.originalNumXTiles = getNumXTiles();

    this.width = destinationRegion.width;
    this.height = destinationRegion.height;
    this.minX = destinationRegion.x;
    this.minY = destinationRegion.y;

    sampleModel = sampleModel.createCompatibleSampleModel(tileWidth, tileHeight);

    maxXTile = originalDimension.width / tileWidth;
    maxYTile = originalDimension.height / tileHeight;
  }
Exemplo n.º 17
0
 /**
  * Returns <code>true</code> if the <code>ImageWriter</code> implementation associated with this
  * service provider is able to encode the given <code>RenderedImage</code> instance. Note that
  * this includes instances of <code>java.awt.image.BufferedImage</code>.
  *
  * <p>See the discussion for <code>canEncodeImage(ImageTypeSpecifier)</code> for information on
  * the semantics of this method.
  *
  * @param im an instance of <code>RenderedImage</code> to be encoded.
  * @return <code>true</code> if this writer is likely to be able to encode this image.
  * @exception IllegalArgumentException if <code>im</code> is <code>null</code>.
  */
 public boolean canEncodeImage(RenderedImage im) {
   return canEncodeImage(ImageTypeSpecifier.createFromRenderedImage(im));
 }
Exemplo n.º 18
0
  /**
   * Initializes these instance variables from the image metadata:
   *
   * <pre>
   * compression
   * width
   * height
   * samplesPerPixel
   * numBands
   * colorMap
   * photometricInterpretation
   * sampleFormat
   * bitsPerSample
   * extraSamples
   * tileOrStripWidth
   * tileOrStripHeight
   * </pre>
   */
  private void initializeFromMetadata() {
    TIFFField f;

    // Compression
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_COMPRESSION);
    if (f == null) {
      processWarningOccurred("Compression field is missing; assuming no compression");
      compression = BaselineTIFFTagSet.COMPRESSION_NONE;
    } else {
      compression = f.getAsInt(0);
    }

    // Whether key dimensional information is absent.
    boolean isMissingDimension = false;

    // ImageWidth -> width
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_WIDTH);
    if (f != null) {
      this.width = f.getAsInt(0);
    } else {
      processWarningOccurred("ImageWidth field is missing.");
      isMissingDimension = true;
    }

    // ImageLength -> height
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_LENGTH);
    if (f != null) {
      this.height = f.getAsInt(0);
    } else {
      processWarningOccurred("ImageLength field is missing.");
      isMissingDimension = true;
    }

    // SamplesPerPixel
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL);
    if (f != null) {
      samplesPerPixel = f.getAsInt(0);
    } else {
      samplesPerPixel = 1;
      isMissingDimension = true;
    }

    // If any dimension is missing and there is a JPEG stream available
    // get the information from it.
    int defaultBitDepth = 1;
    if (isMissingDimension
        && (f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT))
            != null) {
      Iterator iter = ImageIO.getImageReadersByFormatName("JPEG");
      if (iter != null && iter.hasNext()) {
        ImageReader jreader = (ImageReader) iter.next();
        try {
          stream.mark();
          stream.seek(f.getAsLong(0));
          jreader.setInput(stream);
          if (imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_WIDTH) == null) {
            this.width = jreader.getWidth(0);
          }
          if (imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_LENGTH) == null) {
            this.height = jreader.getHeight(0);
          }
          ImageTypeSpecifier imageType = jreader.getRawImageType(0);
          if (imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL) == null) {
            this.samplesPerPixel = imageType.getSampleModel().getNumBands();
          }
          stream.reset();
          defaultBitDepth = imageType.getColorModel().getComponentSize(0);
        } catch (IOException e) {
          // Ignore it and proceed: an error will occur later.
        }
        jreader.dispose();
      }
    }

    if (samplesPerPixel < 1) {
      processWarningOccurred("Samples per pixel < 1!");
    }

    // SamplesPerPixel -> numBands
    numBands = samplesPerPixel;

    // ColorMap
    this.colorMap = null;
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_COLOR_MAP);
    if (f != null) {
      // Grab color map
      colorMap = f.getAsChars();
    }

    // PhotometricInterpretation
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_PHOTOMETRIC_INTERPRETATION);
    if (f == null) {
      if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_RLE
          || compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_4
          || compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
        processWarningOccurred(
            "PhotometricInterpretation field is missing; " + "assuming WhiteIsZero");
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO;
      } else if (this.colorMap != null) {
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_PALETTE_COLOR;
      } else if (samplesPerPixel == 3 || samplesPerPixel == 4) {
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_RGB;
      } else {
        processWarningOccurred(
            "PhotometricInterpretation field is missing; " + "assuming BlackIsZero");
        photometricInterpretation = BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO;
      }
    } else {
      photometricInterpretation = f.getAsInt(0);
    }

    // SampleFormat
    boolean replicateFirst = false;
    int first = -1;

    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLE_FORMAT);
    sampleFormat = new int[samplesPerPixel];
    replicateFirst = false;
    if (f == null) {
      replicateFirst = true;
      first = BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED;
    } else if (f.getCount() != samplesPerPixel) {
      replicateFirst = true;
      first = f.getAsInt(0);
    }

    for (int i = 0; i < samplesPerPixel; i++) {
      sampleFormat[i] = replicateFirst ? first : f.getAsInt(i);
      if (sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_UNSIGNED_INTEGER
          && sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_SIGNED_INTEGER
          && sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_FLOATING_POINT
          && sampleFormat[i] != BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED) {
        processWarningOccurred("Illegal value for SAMPLE_FORMAT, assuming SAMPLE_FORMAT_UNDEFINED");
        sampleFormat[i] = BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED;
      }
    }

    // BitsPerSample
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE);
    this.bitsPerSample = new int[samplesPerPixel];
    replicateFirst = false;
    if (f == null) {
      replicateFirst = true;
      first = defaultBitDepth;
    } else if (f.getCount() != samplesPerPixel) {
      replicateFirst = true;
      first = f.getAsInt(0);
    }

    for (int i = 0; i < samplesPerPixel; i++) {
      // Replicate initial value if not enough values provided
      bitsPerSample[i] = replicateFirst ? first : f.getAsInt(i);

      if (DEBUG) {
        System.out.println("bitsPerSample[" + i + "] = " + bitsPerSample[i]);
      }
    }

    // ExtraSamples
    this.extraSamples = null;
    f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_EXTRA_SAMPLES);
    if (f != null) {
      extraSamples = f.getAsInts();
    }

    //         System.out.println("colorMap = " + colorMap);
    //         if (colorMap != null) {
    //             for (int i = 0; i < colorMap.length; i++) {
    //              System.out.println("colorMap[" + i + "] = " + (int)(colorMap[i]));
    //             }
    //         }

  }
Exemplo n.º 19
0
  public Iterator getImageTypes(int imageIndex) throws IIOException {
    List l; // List of ImageTypeSpecifiers

    Integer imageIndexInteger = new Integer(imageIndex);
    if (imageTypeMap.containsKey(imageIndexInteger)) {
      // Return the cached ITS List.
      l = (List) imageTypeMap.get(imageIndexInteger);
    } else {
      // Create a new ITS List.
      l = new ArrayList(1);

      // Create the ITS and cache if for later use so that this method
      // always returns an Iterator containing the same ITS objects.
      seekToImage(imageIndex);
      ImageTypeSpecifier itsRaw =
          TIFFDecompressor.getRawImageTypeSpecifier(
              photometricInterpretation,
              compression,
              samplesPerPixel,
              bitsPerSample,
              sampleFormat,
              extraSamples,
              colorMap);

      // Check for an ICCProfile field.
      TIFFField iccProfileField = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_ICC_PROFILE);

      // If an ICCProfile field is present change the ImageTypeSpecifier
      // to use it if the data layout is component type.
      if (iccProfileField != null && itsRaw.getColorModel() instanceof ComponentColorModel) {
        // Create a ColorSpace from the profile.
        byte[] iccProfileValue = iccProfileField.getAsBytes();
        ICC_Profile iccProfile = ICC_Profile.getInstance(iccProfileValue);
        ICC_ColorSpace iccColorSpace = new ICC_ColorSpace(iccProfile);

        // Get the raw sample and color information.
        ColorModel cmRaw = itsRaw.getColorModel();
        ColorSpace csRaw = cmRaw.getColorSpace();
        SampleModel smRaw = itsRaw.getSampleModel();

        // Get the number of samples per pixel and the number
        // of color components.
        int numBands = smRaw.getNumBands();
        int numComponents = iccColorSpace.getNumComponents();

        // Replace the ColorModel with the ICC ColorModel if the
        // numbers of samples and color components are amenable.
        if (numBands == numComponents || numBands == numComponents + 1) {
          // Set alpha flags.
          boolean hasAlpha = numComponents != numBands;
          boolean isAlphaPre = hasAlpha && cmRaw.isAlphaPremultiplied();

          // Create a ColorModel of the same class and with
          // the same transfer type.
          ColorModel iccColorModel =
              new ComponentColorModel(
                  iccColorSpace,
                  cmRaw.getComponentSize(),
                  hasAlpha,
                  isAlphaPre,
                  cmRaw.getTransparency(),
                  cmRaw.getTransferType());

          // Prepend the ICC profile-based ITS to the List. The
          // ColorModel and SampleModel are guaranteed to be
          // compatible as the old and new ColorModels are both
          // ComponentColorModels with the same transfer type
          // and the same number of components.
          l.add(new ImageTypeSpecifier(iccColorModel, smRaw));

          // Append the raw ITS to the List if and only if its
          // ColorSpace has the same type and number of components
          // as the ICC ColorSpace.
          if (csRaw.getType() == iccColorSpace.getType()
              && csRaw.getNumComponents() == iccColorSpace.getNumComponents()) {
            l.add(itsRaw);
          }
        } else { // ICCProfile not compatible with SampleModel.
          // Append the raw ITS to the List.
          l.add(itsRaw);
        }
      } else { // No ICCProfile field or raw ColorModel not component.
        // Append the raw ITS to the List.
        l.add(itsRaw);
      }

      // Cache the ITS List.
      imageTypeMap.put(imageIndexInteger, l);
    }

    return l.iterator();
  }
Exemplo n.º 20
0
  private static JSONObject getResultJson(File file, boolean extractLiveProject)
      throws IOException, JSONException, ScriptException {
    final JSONObject result = new JSONObject();
    result.put("formatChecked", true);
    final ImageInputStream iis = ImageIO.createImageInputStream(file);
    final Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
    if (!iterator.hasNext()) {
      result.put("rejected", true);
      result.put("message", "Unknown image format: can't create an ImageInputStream");
      return result;
    }
    final ImageReader reader = iterator.next();
    final JSONObject imageType = SimagisLiveUtils.openObject(result, "imageType");
    try {
      reader.setInput(iis);
      JSONObject formatSpecific = new JSONObject();
      formatSpecific.put("javaFormatType", "DICOM");
      formatSpecific.put("javaFormatName", reader.getFormatName());
      result.put("formatSpecific", formatSpecific);

      final int dimX = reader.getWidth(0);
      final int dimY = reader.getHeight(0);
      if ((long) dimX * (long) dimY >= 512L * 1024L * 1024L) {
        result.put("rejected", true);
        result.put("message", "Too large image (more than 512 million pixels)");
        return result;
        // We are little reinsuring here: Java API can try to create a single byte[]
        // or short[] array with packed RGB triples (3 * dimX * dimY), and we would like
        // to be sure that its size will be far from the Java language limit 2 GB.
      }
      result.put("dimX", dimX);
      result.put("dimY", dimY);
      final Iterator<ImageTypeSpecifier> iioImageTypes = reader.getImageTypes(0);
      if (iioImageTypes != null && iioImageTypes.hasNext()) {
        // some 3rd party implementation can still return null here, though it is prohibited in
        // JavaDoc
        ImageTypeSpecifier imageTypeSpecifier = iioImageTypes.next();
        imageType.put("numComponents", imageTypeSpecifier.getNumComponents());
        imageType.put("numBands", imageTypeSpecifier.getNumBands());
        if (imageTypeSpecifier.getNumComponents() >= 4) {
          result.put("recommendedRenderingFormat", "png");
        }
      }
      final IIOMetadata streamMetadata = reader.getStreamMetadata();
      final IIOMetadataToJsonConverter converter = new IIOMetadataToJsonConverter();
      if (streamMetadata != null) {
        DICOMImageIOMetadata imageIOMetadata = DICOMImageIOMetadata.getInstance(streamMetadata, 0);
        if (imageIOMetadata != null) {
          result.put("DICOMMetadata", new JSONObject(imageIOMetadata));
        }
        result.put("streamMetadata", converter.toJson(streamMetadata));
      }
      final IIOMetadata imageMetadata = reader.getImageMetadata(0);
      if (imageMetadata != null) {
        result.put("imageMetadata", converter.toJson(imageMetadata));
      }
    } finally {
      reader.dispose();
      iis.close();
    }
    if (extractLiveProject) {
      JSONObject liveProject = extractLiveProject(result);
      result.put("liveProject", liveProject);
      result.remove("imageMetadata");
      result.remove("streamMetadata");
    }
    result.put("rejected", false);
    return result;
  }
Exemplo n.º 21
0
  public Iterator<ImageTypeSpecifier> getImageTypes(int pIndex) throws IOException {
    checkBounds(pIndex);

    init(pIndex);

    // TODO: FIX ME!
    // - Use factory methods for ImageTypeSpecifier, create factory methods if necessary
    List<ImageTypeSpecifier> specs = new ArrayList<ImageTypeSpecifier>();
    try {
      ColorModel cm;
      // NOTE: These are all fall-through by intention
      switch (mImage.getImageType()) {
        case ImageType.BilevelType:
          specs.add(
              IndexedImageTypeSpecifier.createFromIndexColorModel(
                  MonochromeColorModel.getInstance()));
        case ImageType.GrayscaleType:
          //                    cm = MagickUtil.CM_GRAY_OPAQUE;
          //                    specs.add(new ImageTypeSpecifier(
          //                            cm,
          //                            cm.createCompatibleSampleModel(1, 1)
          //                    ));
          specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY));
        case ImageType.GrayscaleMatteType:
          cm = CM_GRAY_ALPHA;
          specs.add(new ImageTypeSpecifier(cm, cm.createCompatibleSampleModel(1, 1)));
        case ImageType.PaletteType:
          specs.add(
              IndexedImageTypeSpecifier.createFromIndexColorModel(
                  MagickUtil.createIndexColorModel(mImage.getColormap(), false)));
        case ImageType.PaletteMatteType:
          specs.add(
              IndexedImageTypeSpecifier.createFromIndexColorModel(
                  MagickUtil.createIndexColorModel(mImage.getColormap(), true)));
        case ImageType.TrueColorType:
          //                    cm = MagickUtil.CM_COLOR_OPAQUE;
          //                    specs.add(new ImageTypeSpecifier(
          //                            cm,
          //                            cm.createCompatibleSampleModel(1, 1)
          //                    ));
          specs.add(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_3BYTE_BGR));
        case ImageType.TrueColorMatteType:
          //                    cm = MagickUtil.CM_COLOR_ALPHA;
          //                    specs.add(new ImageTypeSpecifier(
          //                            cm,
          //                            cm.createCompatibleSampleModel(1, 1)
          //                    ));
          specs.add(
              ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_4BYTE_ABGR_PRE));
          break;
        case ImageType.ColorSeparationType:
        case ImageType.ColorSeparationMatteType:
        case ImageType.OptimizeType:
        default:
          throw new MagickException("Unknown JMagick image type: " + mImage.getImageType());
      }
    } catch (MagickException e) {
      throw new IIOException(e.getMessage(), e);
    }

    return specs.iterator();
  }
 public ColorModel getColorModel() {
   return its.getColorModel();
 }