Exemplo n.º 1
0
  @Test
  public void testYCbCr() {
    assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus());
    // check the presence of the PYCC.pf file that contains the profile for the YCbCr color space
    if (ImageWorker.CS_PYCC == null) {
      System.out.println(
          "testYCbCr disabled since we are unable to locate the YCbCr color profile");
      return;
    }
    // RGB component color model
    ImageWorker worker = new ImageWorker(getSyntheticRGB(false));

    RenderedImage image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);
    assertTrue(!image.getColorModel().hasAlpha());
    int sample = image.getTile(0, 0).getSample(0, 0, 2);
    assertEquals(0, sample);

    assertFalse(worker.isColorSpaceYCbCr());
    worker.forceColorSpaceYCbCr();
    assertTrue(worker.isColorSpaceYCbCr());
    worker.forceColorSpaceRGB();
    assertFalse(worker.isColorSpaceYCbCr());
    assertTrue(worker.isColorSpaceRGB());

    // RGB Palette
    worker.forceBitmaskIndexColorModel();
    image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof IndexColorModel);
    assertTrue(!image.getColorModel().hasAlpha());

    assertFalse(worker.isColorSpaceYCbCr());
    worker.forceColorSpaceYCbCr();
    assertTrue(worker.isColorSpaceYCbCr());
    worker.forceColorSpaceRGB();
    assertFalse(worker.isColorSpaceYCbCr());
    assertTrue(worker.isColorSpaceRGB());

    // RGB DirectColorModel
    worker = new ImageWorker(getSyntheticRGB(true));
    image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof DirectColorModel);
    assertTrue(!image.getColorModel().hasAlpha());
    sample = image.getTile(0, 0).getSample(0, 0, 2);
    assertEquals(0, sample);

    assertFalse(worker.isColorSpaceYCbCr());
    worker.forceColorSpaceYCbCr();
    assertTrue(worker.isColorSpaceYCbCr());
    worker.forceColorSpaceRGB();
    assertFalse(worker.isColorSpaceYCbCr());
    assertTrue(worker.isColorSpaceRGB());
  }
Exemplo n.º 2
0
  @Test
  public void testOpacityGrayAlpha() {
    assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus());
    ImageWorker worker = new ImageWorker(gray);
    worker.applyOpacity(0.5f);

    RenderedImage image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);
    assertTrue(image.getColorModel().hasAlpha());
    Raster tile = gray.getTile(0, 0);
    Raster outputTile = image.getTile(0, 0);
    for (int i = 0; i < tile.getWidth(); i++) {
      for (int j = 0; j < tile.getHeight(); j++) {
        int original = tile.getSample(i, j, 1);
        int result = outputTile.getSample(i, j, 1);
        assertEquals(Math.round(original * 0.5), result);
      }
    }
  }
Exemplo n.º 3
0
  private void testAlphaRGB(boolean direct) {
    assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus());
    ImageWorker worker = new ImageWorker(getSyntheticRGB(direct));
    worker.applyOpacity(0.5f);

    RenderedImage image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);
    assertTrue(image.getColorModel().hasAlpha());
    int sample = image.getTile(0, 0).getSample(0, 0, 3);
    assertEquals(128, sample);
  }
Exemplo n.º 4
0
  @Test
  public void testOpacityGray() {
    assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus());
    ImageWorker worker = new ImageWorker(gray);
    worker.applyOpacity(0.5f);

    RenderedImage image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);
    assertTrue(image.getColorModel().hasAlpha());
    int sample = image.getTile(0, 0).getSample(0, 0, 1);
    assertEquals(128, sample);
  }
Exemplo n.º 5
0
  private void writeRows(
      RenderedImage image,
      LZWCompressor compressor,
      int sx,
      int sdx,
      int sy,
      int sdy,
      int sw,
      int dy,
      int ddy,
      int dw,
      int dh,
      int numRowsWritten,
      int progressReportRowPeriod)
      throws IOException {
    if (DEBUG) System.out.println("Writing unoptimized");

    int[] sbuf = new int[sw];
    byte[] dbuf = new byte[dw];

    Raster raster =
        image.getNumXTiles() == 1 && image.getNumYTiles() == 1
            ? image.getTile(0, 0)
            : image.getData();
    for (int y = dy; y < dh; y += ddy) {
      if (numRowsWritten % progressReportRowPeriod == 0) {
        if (abortRequested()) {
          processWriteAborted();
          return;
        }
        processImageProgress((numRowsWritten * 100.0F) / dh);
      }

      raster.getSamples(sx, sy, sw, 1, 0, sbuf);
      for (int i = 0, j = 0; i < dw; i++, j += sdx) {
        dbuf[i] = (byte) sbuf[j];
      }
      compressor.compress(dbuf, 0, dw);
      numRowsWritten++;
      sy += sdy;
    }
  }
  /**
   * Returns a contiguous <code>Raster</code> of data over the specified <code>Rectangle</code>. If
   * the region is a sub-region of a single tile, then a child of that tile will be returned. If the
   * region overlaps more than one tile and has 8 bits per sample, then a pixel interleaved Raster
   * having band offsets 0,1,... will be returned. Otherwise the Raster returned by <code>
   * im.copyData(null)</code> will be returned.
   */
  private static final Raster getContiguousData(RenderedImage im, Rectangle region) {
    if (im == null) {
      throw new IllegalArgumentException("im == null");
    } else if (region == null) {
      throw new IllegalArgumentException("region == null");
    }

    Raster raster;
    if (im.getNumXTiles() == 1 && im.getNumYTiles() == 1) {
      // Image is not tiled so just get a reference to the tile.
      raster = im.getTile(im.getMinTileX(), im.getMinTileY());

      // Ensure result has requested coverage.
      Rectangle bounds = raster.getBounds();
      if (!bounds.equals(region)) {
        raster =
            raster.createChild(
                region.x, region.y, region.width, region.height, region.x, region.y, null);
      }
    } else {
      // Image is tiled.

      // Create an interleaved raster for copying for 8-bit case.
      // This ensures that for RGB data the band offsets are {0,1,2}.
      SampleModel sampleModel = im.getSampleModel();
      WritableRaster target =
          sampleModel.getSampleSize(0) == 8
              ? Raster.createInterleavedRaster(
                  DataBuffer.TYPE_BYTE,
                  im.getWidth(),
                  im.getHeight(),
                  sampleModel.getNumBands(),
                  new Point(im.getMinX(), im.getMinY()))
              : null;

      // Copy the data.
      raster = im.copyData(target);
    }

    return raster;
  }
 /**
  * Create Byte type default rendered image iterator.
  *
  * @param renderedImage image which will be follow by iterator.
  * @param subArea {@code Rectangle} which represent image sub area iteration.
  * @throws IllegalArgumentException if subArea don't intersect image boundary.
  */
 DefaultDirectFloatIterator(final RenderedImage renderedImage, final Rectangle subArea) {
   super(renderedImage, subArea);
   assert (renderedImage.getTile(tMinX, tMinY).getDataBuffer().getDataType()
           == DataBuffer.TYPE_FLOAT)
       : "renderedImage datas or not Byte type";
 }
Exemplo n.º 8
0
  public void testRescale(
      RenderedImage source,
      boolean roiUsed,
      boolean noDataUsed,
      boolean useRoiAccessor,
      TestSelection select) {

    // The precalculated roi is used, if selected by the related boolean.
    ROI roiData;

    if (roiUsed) {
      roiData = roi;
    } else {
      roiData = null;
    }

    // The precalculated NoData Range is used, if selected by the related boolean.
    Range noDataRange;
    // Image data type
    int dataType = source.getSampleModel().getDataType();

    if (noDataUsed) {

      switch (dataType) {
        case DataBuffer.TYPE_BYTE:
          noDataRange = noDataByte;
          break;
        case DataBuffer.TYPE_USHORT:
          noDataRange = noDataUShort;
          break;
        case DataBuffer.TYPE_SHORT:
          noDataRange = noDataShort;
          break;
        case DataBuffer.TYPE_INT:
          noDataRange = noDataInt;
          break;
        case DataBuffer.TYPE_FLOAT:
          noDataRange = noDataFloat;
          break;
        case DataBuffer.TYPE_DOUBLE:
          noDataRange = noDataDouble;
          break;
        default:
          throw new IllegalArgumentException("Wrong data type");
      }
    } else {
      noDataRange = null;
    }

    // Rescale operation
    PlanarImage rescaled =
        RescaleDescriptor.create(
            source, scales, offsets, roiData, noDataRange, useRoiAccessor, destNoData, null);

    // Display Image
    if (INTERACTIVE && TEST_SELECTOR == select.getType()) {
      RenderedImageBrowser.showChain(rescaled, false, roiUsed);
      try {
        System.in.read();
      } catch (IOException e) {
        e.printStackTrace();
      }

    } else {
      // Calculation of all the image tiles
      rescaled.getTiles();
    }

    // Rescale control on the first band
    int tileMinX = rescaled.getMinTileX();
    int tileMinY = rescaled.getMinTileY();
    // Selection of the source and destination first tile
    Raster tileDest = rescaled.getTile(tileMinX, tileMinY);
    Raster tileSource = source.getTile(tileMinX, tileMinY);

    int tileMinXpix = tileDest.getMinX();
    int tileMinYpix = tileDest.getMinY();

    int tileMaxXpix = tileDest.getWidth() + tileMinXpix;
    int tileMaxYpix = tileDest.getHeight() + tileMinYpix;

    double scaleFactor = scales[0];
    double offset = offsets[0];
    // loop through the tile pixels
    for (int i = tileMinXpix; i < tileMaxXpix; i++) {
      for (int j = tileMinYpix; j < tileMaxYpix; j++) {

        switch (dataType) {
          case DataBuffer.TYPE_BYTE:
            // selection of the rescaled pixel
            byte destValueB = (byte) tileDest.getSample(i, j, 0);
            // rescale operation on the source pixel
            int srcValueB = tileSource.getSample(i, j, 0) & 0xFF;
            byte calculationB = ImageUtil.clampRoundByte(srcValueB * scaleFactor + offset);
            // comparison
            if (roiUsed && noDataUsed) {
              if (roiBounds.contains(i, j) && !noDataRange.contains((byte) srcValueB)) {
                assertEquals(calculationB, destValueB);
              }
            } else if (roiUsed) {
              if (roiBounds.contains(i, j)) {
                assertEquals(calculationB, destValueB);
              }
            } else if (noDataUsed) {
              if (!noDataRange.contains((byte) srcValueB)) {
                assertEquals(calculationB, destValueB);
              }
            } else {
              assertEquals(calculationB, destValueB);
            }
            break;
          case DataBuffer.TYPE_USHORT:
            short destValueU = (short) tileDest.getSample(i, j, 0);
            int srcValueU = tileSource.getSample(i, j, 0) & 0xFFFF;
            short calculationU = ImageUtil.clampRoundUShort(srcValueU * scaleFactor + offset);
            if (roiUsed && noDataUsed) {
              if (roiBounds.contains(i, j) && !noDataRange.contains((short) srcValueU)) {
                assertEquals(calculationU, destValueU);
              }
            } else if (roiUsed) {
              if (roiBounds.contains(i, j)) {
                assertEquals(calculationU, destValueU);
              }
            } else if (noDataUsed) {
              if (!noDataRange.contains((short) srcValueU)) {
                assertEquals(calculationU, destValueU);
              }
            } else {
              assertEquals(calculationU, destValueU);
            }
            break;
          case DataBuffer.TYPE_SHORT:
            short destValueS = (short) tileDest.getSample(i, j, 0);
            short srcValueS = (short) tileSource.getSample(i, j, 0);
            short calculationS = ImageUtil.clampRoundShort(srcValueS * scaleFactor + offset);
            if (roiUsed && noDataUsed) {
              if (roiBounds.contains(i, j) && !noDataRange.contains(srcValueS)) {
                assertEquals(calculationS, destValueS);
              }
            } else if (roiUsed) {
              if (roiBounds.contains(i, j)) {
                assertEquals(calculationS, destValueS);
              }
            } else if (noDataUsed) {
              if (!noDataRange.contains(srcValueS)) {
                assertEquals(calculationS, destValueS);
              }
            } else {
              assertEquals(calculationS, destValueS);
            }
            break;
          case DataBuffer.TYPE_INT:
            int destValueI = tileDest.getSample(i, j, 0);
            int srcValueI = tileSource.getSample(i, j, 0);
            int calculationI = ImageUtil.clampRoundInt(srcValueI * scaleFactor + offset);
            if (roiUsed && noDataUsed) {
              if (roiBounds.contains(i, j) && !noDataRange.contains(srcValueI)) {
                assertEquals(calculationI, destValueI);
              }
            } else if (roiUsed) {
              if (roiBounds.contains(i, j)) {
                assertEquals(calculationI, destValueI);
              }
            } else if (noDataUsed) {
              if (!noDataRange.contains(srcValueI)) {
                assertEquals(calculationI, destValueI);
              }
            } else {
              assertEquals(calculationI, destValueI);
            }
            break;
          case DataBuffer.TYPE_FLOAT:
            float destValueF = tileDest.getSampleFloat(i, j, 0);
            float srcValueF = tileSource.getSampleFloat(i, j, 0);
            float calculationF = (float) ((srcValueF * scaleFactor) + offset);
            if (roiUsed && noDataUsed) {
              if (roiBounds.contains(i, j) && !noDataRange.contains(srcValueF)) {
                assertEquals(calculationF, destValueF, TOLERANCE);
              }
            } else if (roiUsed) {
              if (roiBounds.contains(i, j)) {
                assertEquals(calculationF, destValueF, TOLERANCE);
              }
            } else if (noDataUsed) {
              if (!noDataRange.contains(srcValueF)) {
                assertEquals(calculationF, destValueF, TOLERANCE);
              }
            } else {
              assertEquals(calculationF, destValueF, TOLERANCE);
            }
            break;
          case DataBuffer.TYPE_DOUBLE:
            double destValueD = tileDest.getSampleDouble(i, j, 0);
            double srcValueD = tileSource.getSampleDouble(i, j, 0);
            double calculationD = ((srcValueD * scaleFactor) + offset);
            if (roiUsed && noDataUsed) {
              if (roiBounds.contains(i, j) && !noDataRange.contains(srcValueD)) {
                assertEquals(calculationD, destValueD, TOLERANCE);
              }
            } else if (roiUsed) {
              if (roiBounds.contains(i, j)) {
                assertEquals(calculationD, destValueD, TOLERANCE);
              }
            } else if (noDataUsed) {
              if (!noDataRange.contains(srcValueD)) {
                assertEquals(calculationD, destValueD, TOLERANCE);
              }
            } else {
              assertEquals(calculationD, destValueD, TOLERANCE);
            }
            break;
          default:
            throw new IllegalArgumentException("Wrong data type");
        }
      }
    }
  }
Exemplo n.º 9
0
  public void encode(RenderedImage im) throws IOException {
    // Get the SampleModel.
    SampleModel sm = im.getSampleModel();

    // Check the data type, band count, and sample size.
    int dataType = sm.getTransferType();
    if (dataType == DataBuffer.TYPE_FLOAT || dataType == DataBuffer.TYPE_DOUBLE) {
      throw new IllegalArgumentException(JaiI18N.getString("WBMPImageEncoder0"));
    } else if (sm.getNumBands() != 1) {
      throw new IllegalArgumentException(JaiI18N.getString("WBMPImageEncoder1"));
    } else if (sm.getSampleSize(0) != 1) {
      throw new IllegalArgumentException(JaiI18N.getString("WBMPImageEncoder2"));
    }

    // Save image dimensions.
    int width = im.getWidth();
    int height = im.getHeight();

    // Write WBMP header.
    output.write(0); // TypeField
    output.write(0); // FixHeaderField
    output.write(intToMultiByte(width)); // width
    output.write(intToMultiByte(height)); // height

    Raster tile = null;

    // If the data are not formatted nominally then reformat.
    if (sm.getDataType() != DataBuffer.TYPE_BYTE
        || !(sm instanceof MultiPixelPackedSampleModel)
        || ((MultiPixelPackedSampleModel) sm).getDataBitOffset() != 0) {
      MultiPixelPackedSampleModel mppsm =
          new MultiPixelPackedSampleModel(
              DataBuffer.TYPE_BYTE, width, height, 1, (width + 7) / 8, 0);
      WritableRaster raster =
          Raster.createWritableRaster(mppsm, new Point(im.getMinX(), im.getMinY()));
      raster.setRect(im.getData());
      tile = raster;
    } else if (im.getNumXTiles() == 1 && im.getNumYTiles() == 1) {
      tile = im.getTile(im.getMinTileX(), im.getMinTileY());
    } else {
      tile = im.getData();
    }

    // Check whether the image is white-is-zero.
    boolean isWhiteZero = false;
    if (im.getColorModel() instanceof IndexColorModel) {
      IndexColorModel icm = (IndexColorModel) im.getColorModel();
      isWhiteZero =
          (icm.getRed(0) + icm.getGreen(0) + icm.getBlue(0))
              > (icm.getRed(1) + icm.getGreen(1) + icm.getBlue(1));
    }

    // Get the line stride, bytes per row, and data array.
    int lineStride = ((MultiPixelPackedSampleModel) sm).getScanlineStride();
    int bytesPerRow = (width + 7) / 8;
    byte[] bdata = ((DataBufferByte) tile.getDataBuffer()).getData();

    // Write the data.
    if (!isWhiteZero && lineStride == bytesPerRow) {
      // Write the entire image.
      output.write(bdata, 0, height * bytesPerRow);
    } else {
      // Write the image row-by-row.
      int offset = 0;
      if (!isWhiteZero) {
        // Black-is-zero
        for (int row = 0; row < height; row++) {
          output.write(bdata, offset, bytesPerRow);
          offset += lineStride;
        }
      } else {
        // White-is-zero: need to invert data.
        byte[] inverted = new byte[bytesPerRow];
        for (int row = 0; row < height; row++) {
          for (int col = 0; col < bytesPerRow; col++) {
            inverted[col] = (byte) (~(bdata[col + offset]));
          }
          output.write(inverted, 0, bytesPerRow);
          offset += lineStride;
        }
      }
    }
  }
Exemplo n.º 10
0
  /**
   * Tests the {@link ImageWorker#makeColorTransparent} methods. Some trivial tests are performed
   * before.
   *
   * @throws IOException
   * @throws FileNotFoundException
   * @throws IllegalStateException
   */
  @Test
  public void testMakeColorTransparent()
      throws IllegalStateException, FileNotFoundException, IOException {
    assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus());
    ImageWorker worker = new ImageWorker(sstImage);

    assertSame(sstImage, worker.getRenderedImage());
    assertEquals(1, worker.getNumBands());
    assertEquals(-1, worker.getTransparentPixel());
    assertTrue(worker.isBytes());
    assertFalse(worker.isBinary());
    assertTrue(worker.isIndexed());
    assertTrue(worker.isColorSpaceRGB());
    assertFalse(worker.isColorSpaceGRAYScale());
    assertFalse(worker.isTranslucent());

    assertSame(
        "Expected no operation.", sstImage, worker.forceIndexColorModel(false).getRenderedImage());
    assertSame(
        "Expected no operation.", sstImage, worker.forceIndexColorModel(true).getRenderedImage());
    assertSame("Expected no operation.", sstImage, worker.forceColorSpaceRGB().getRenderedImage());
    assertSame("Expected no operation.", sstImage, worker.retainFirstBand().getRenderedImage());
    assertSame("Expected no operation.", sstImage, worker.retainLastBand().getRenderedImage());

    // Following will change image, so we need to test after the above assertions.
    assertEquals(0, worker.getMinimums()[0], 0);
    assertEquals(255, worker.getMaximums()[0], 0);
    assertNotSame(sstImage, worker.getRenderedImage());
    assertSame(
        "Expected same databuffer, i.e. pixels should not be duplicated.",
        sstImage.getTile(0, 0).getDataBuffer(),
        worker.getRenderedImage().getTile(0, 0).getDataBuffer());

    assertSame(worker, worker.makeColorTransparent(Color.WHITE));
    assertEquals(255, worker.getTransparentPixel());
    assertFalse(worker.isTranslucent());
    assertSame(
        "Expected same databuffer, i.e. pixels should not be duplicated.",
        sstImage.getTile(0, 0).getDataBuffer(),
        worker.getRenderedImage().getTile(0, 0).getDataBuffer());

    // INDEX TO INDEX-ALPHA
    worker = new ImageWorker(chlImage).makeColorTransparent(Color.black);
    show(worker, "CHL01195.png");
    assertEquals(1, worker.getNumBands());
    assertEquals(0, worker.getTransparentPixel());
    assertTrue(worker.isBytes());
    assertTrue(worker.isIndexed());
    assertTrue(worker.isColorSpaceRGB());
    assertFalse(worker.isColorSpaceGRAYScale());
    assertFalse(worker.isTranslucent());
    RenderedImage image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof IndexColorModel);
    IndexColorModel iColorModel = (IndexColorModel) image.getColorModel();
    int transparentColor = iColorModel.getRGB(worker.getTransparentPixel()) & 0x00ffffff;
    assertTrue(transparentColor == 0);

    // INDEX TO INDEX-ALPHA
    worker = new ImageWorker(bathy).makeColorTransparent(Color.WHITE);
    show(worker, "BATHY.png");
    assertEquals(1, worker.getNumBands());
    assertEquals(206, worker.getTransparentPixel());
    assertTrue(worker.isBytes());
    assertTrue(worker.isIndexed());
    assertTrue(worker.isColorSpaceRGB());
    assertFalse(worker.isColorSpaceGRAYScale());
    assertFalse(worker.isTranslucent());
    image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof IndexColorModel);
    iColorModel = (IndexColorModel) image.getColorModel();
    transparentColor = iColorModel.getRGB(worker.getTransparentPixel()) & 0x00ffffff;
    assertTrue(transparentColor == (Color.WHITE.getRGB() & 0x00ffffff));

    // RGB TO RGBA
    worker = new ImageWorker(smallWorld).makeColorTransparent(new Color(11, 10, 50));
    show(worker, "small_world.png");
    assertEquals(4, worker.getNumBands());
    assertEquals(-1, worker.getTransparentPixel());
    assertTrue(worker.isBytes());
    assertFalse(worker.isIndexed());
    assertTrue(worker.isColorSpaceRGB());
    assertFalse(worker.isColorSpaceGRAYScale());
    assertTrue(worker.isTranslucent());
    image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);

    // RGBA to RGBA
    worker = new ImageWorker(worldImage).makeColorTransparent(Color.white);
    show(worker, "world.png");
    assertEquals(4, worker.getNumBands());
    assertEquals(-1, worker.getTransparentPixel());
    assertTrue(worker.isBytes());
    assertFalse(worker.isIndexed());
    assertTrue(worker.isColorSpaceRGB());
    assertFalse(worker.isColorSpaceGRAYScale());
    assertTrue(worker.isTranslucent());
    image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);

    // GRAY TO GRAY-ALPHA
    worker = new ImageWorker(gray).makeColorTransparent(Color.black);
    show(worker, "gray.png");
    assertEquals(2, worker.getNumBands());
    assertEquals(-1, worker.getTransparentPixel());
    assertTrue(worker.isBytes());
    assertFalse(worker.isIndexed());
    assertFalse(worker.isColorSpaceRGB());
    assertTrue(worker.isColorSpaceGRAYScale());
    assertTrue(worker.isTranslucent());
    image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);

    // GRAY-ALPHA TO GRAY-ALPHA.
    worker = new ImageWorker(grayAlpha).makeColorTransparent(Color.black);
    show(worker, "gray-alpha.png");
    assertEquals(2, worker.getNumBands());
    assertEquals(-1, worker.getTransparentPixel());
    assertTrue(worker.isBytes());
    assertFalse(worker.isIndexed());
    assertFalse(worker.isColorSpaceRGB());
    assertTrue(worker.isColorSpaceGRAYScale());
    assertTrue(worker.isTranslucent());
    image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);
  }
Exemplo n.º 11
0
  private void writeRasterData(
      RenderedImage image,
      Rectangle sourceBounds,
      Dimension destSize,
      ImageWriteParam param,
      boolean interlaceFlag)
      throws IOException {

    int sourceXOffset = sourceBounds.x;
    int sourceYOffset = sourceBounds.y;
    int sourceWidth = sourceBounds.width;
    int sourceHeight = sourceBounds.height;

    int destWidth = destSize.width;
    int destHeight = destSize.height;

    int periodX;
    int periodY;
    if (param == null) {
      periodX = 1;
      periodY = 1;
    } else {
      periodX = param.getSourceXSubsampling();
      periodY = param.getSourceYSubsampling();
    }

    SampleModel sampleModel = image.getSampleModel();
    int bitsPerPixel = sampleModel.getSampleSize()[0];

    int initCodeSize = bitsPerPixel;
    if (initCodeSize == 1) {
      initCodeSize++;
    }
    stream.write(initCodeSize);

    LZWCompressor compressor = new LZWCompressor(stream, initCodeSize, false);

    boolean isOptimizedCase =
        periodX == 1
            && periodY == 1
            && sampleModel instanceof ComponentSampleModel
            && image.getNumXTiles() == 1
            && image.getNumYTiles() == 1
            && image.getTile(0, 0).getDataBuffer() instanceof DataBufferByte;

    int numRowsWritten = 0;

    int progressReportRowPeriod = Math.max(destHeight / 20, 1);

    processImageStarted(imageIndex);

    if (interlaceFlag) {
      if (DEBUG) System.out.println("Writing interlaced");

      if (isOptimizedCase) {
        Raster tile = image.getTile(0, 0);
        byte[] data = ((DataBufferByte) tile.getDataBuffer()).getData();
        ComponentSampleModel csm = (ComponentSampleModel) tile.getSampleModel();
        int offset =
            csm.getOffset(
                sourceXOffset - tile.getSampleModelTranslateX(),
                sourceYOffset - tile.getSampleModelTranslateY(),
                0);
        int lineStride = csm.getScanlineStride();

        writeRowsOpt(
            data,
            offset,
            lineStride,
            compressor,
            0,
            8,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);

        if (abortRequested()) {
          return;
        }

        numRowsWritten += destHeight / 8;

        writeRowsOpt(
            data,
            offset,
            lineStride,
            compressor,
            4,
            8,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);

        if (abortRequested()) {
          return;
        }

        numRowsWritten += (destHeight - 4) / 8;

        writeRowsOpt(
            data,
            offset,
            lineStride,
            compressor,
            2,
            4,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);

        if (abortRequested()) {
          return;
        }

        numRowsWritten += (destHeight - 2) / 4;

        writeRowsOpt(
            data,
            offset,
            lineStride,
            compressor,
            1,
            2,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);
      } else {
        writeRows(
            image,
            compressor,
            sourceXOffset,
            periodX,
            sourceYOffset,
            8 * periodY,
            sourceWidth,
            0,
            8,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);

        if (abortRequested()) {
          return;
        }

        numRowsWritten += destHeight / 8;

        writeRows(
            image,
            compressor,
            sourceXOffset,
            periodX,
            sourceYOffset + 4 * periodY,
            8 * periodY,
            sourceWidth,
            4,
            8,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);

        if (abortRequested()) {
          return;
        }

        numRowsWritten += (destHeight - 4) / 8;

        writeRows(
            image,
            compressor,
            sourceXOffset,
            periodX,
            sourceYOffset + 2 * periodY,
            4 * periodY,
            sourceWidth,
            2,
            4,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);

        if (abortRequested()) {
          return;
        }

        numRowsWritten += (destHeight - 2) / 4;

        writeRows(
            image,
            compressor,
            sourceXOffset,
            periodX,
            sourceYOffset + periodY,
            2 * periodY,
            sourceWidth,
            1,
            2,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);
      }
    } else {
      if (DEBUG) System.out.println("Writing non-interlaced");

      if (isOptimizedCase) {
        Raster tile = image.getTile(0, 0);
        byte[] data = ((DataBufferByte) tile.getDataBuffer()).getData();
        ComponentSampleModel csm = (ComponentSampleModel) tile.getSampleModel();
        int offset =
            csm.getOffset(
                sourceXOffset - tile.getSampleModelTranslateX(),
                sourceYOffset - tile.getSampleModelTranslateY(),
                0);
        int lineStride = csm.getScanlineStride();

        writeRowsOpt(
            data,
            offset,
            lineStride,
            compressor,
            0,
            1,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);
      } else {
        writeRows(
            image,
            compressor,
            sourceXOffset,
            periodX,
            sourceYOffset,
            periodY,
            sourceWidth,
            0,
            1,
            destWidth,
            destHeight,
            numRowsWritten,
            progressReportRowPeriod);
      }
    }

    if (abortRequested()) {
      return;
    }

    processImageProgress(100.0F);

    compressor.flush();

    stream.write(0x00);

    processImageComplete();
  }
Exemplo n.º 12
0
  private void testType(RenderedImage src, boolean nodataUsed, boolean roiUsed) {
    // Optional No Data Range used
    Range noData;
    // Source image data type
    int dataType = src.getSampleModel().getDataType();
    // If no Data are present, the No Data Range associated is used
    if (nodataUsed) {

      switch (dataType) {
        case DataBuffer.TYPE_BYTE:
          noData = noDataByte;
          break;
        case DataBuffer.TYPE_USHORT:
          noData = noDataUShort;
          break;
        case DataBuffer.TYPE_SHORT:
          noData = noDataShort;
          break;
        case DataBuffer.TYPE_INT:
          noData = noDataInt;
          break;
        case DataBuffer.TYPE_FLOAT:
          noData = noDataFloat;
          break;
        case DataBuffer.TYPE_DOUBLE:
          noData = noDataDouble;
          break;
        default:
          throw new IllegalArgumentException("Wrong data type");
      }
    } else {
      noData = null;
    }

    ROI roi;

    if (roiUsed) {
      roi = roiObject;
    } else {
      roi = null;
    }

    // BandCombined result
    RenderedOp combined =
        BandCombineDescriptor.create(src, matrix, roi, noData, destinationNoData, null);

    int tileWidth = combined.getTileWidth();
    int tileHeight = combined.getTileHeight();
    int minTileX = combined.getMinTileX();
    int minTileY = combined.getMinTileY();
    int numXTiles = combined.getNumXTiles();
    int numYTiles = combined.getNumYTiles();
    int maxTileX = minTileX + numXTiles;
    int maxTileY = minTileY + numYTiles;
    // Ensure same size
    assertEquals(combined.getWidth(), src.getWidth());
    assertEquals(combined.getHeight(), src.getHeight());
    assertEquals(combined.getMinX(), src.getMinX());
    assertEquals(combined.getMinY(), src.getMinY());
    assertEquals(minTileX, src.getMinTileX());
    assertEquals(minTileY, src.getMinTileY());
    assertEquals(numXTiles, src.getNumXTiles());
    assertEquals(numYTiles, src.getNumYTiles());
    assertEquals(tileWidth, src.getTileWidth());
    assertEquals(tileHeight, src.getTileHeight());

    int srcBands = src.getSampleModel().getNumBands();
    int dstBands = combined.getNumBands();

    // Ensure a correct band size
    assertEquals(dstBands, matrix.length);

    // Check on all the pixels if they have been calculate correctly
    for (int tileX = minTileX; tileX < maxTileX; tileX++) {
      for (int tileY = minTileY; tileY < maxTileY; tileY++) {
        Raster tile = combined.getTile(tileX, tileY);
        Raster srcTile = src.getTile(tileX, tileY);

        int minX = tile.getMinX();
        int minY = tile.getMinY();
        int maxX = minX + tileWidth - 1;
        int maxY = minY + tileHeight - 1;

        for (int x = minX; x <= maxX; x++) {
          for (int y = minY; y <= maxY; y++) {

            boolean isValidRoi = !roiUsed || (roiUsed && roiObject.contains(x, y));

            if (isValidRoi) {
              for (int b = 0; b < dstBands; b++) {
                // Getting the result
                double result = tile.getSampleDouble(x, y, b);

                // Calculating the expected result from sources
                boolean valid = false;
                double calculated = 0;

                for (int i = 0; i < srcBands; i++) {
                  double sample = srcTile.getSampleDouble(x, y, i);
                  boolean isValidData =
                      !nodataUsed || (nodataUsed && !noDataDouble.contains(sample));
                  valid |= isValidData;
                  if (isValidData) {
                    switch (dataType) {
                      case DataBuffer.TYPE_BYTE:
                        calculated += ((int) sample & 0xFF) * matrix[b][i];
                        break;
                      case DataBuffer.TYPE_USHORT:
                        calculated += ((int) sample & 0xFFFF) * matrix[b][i];
                        break;
                      case DataBuffer.TYPE_SHORT:
                      case DataBuffer.TYPE_INT:
                      case DataBuffer.TYPE_FLOAT:
                      case DataBuffer.TYPE_DOUBLE:
                        calculated += sample * matrix[b][i];
                        break;
                      default:
                        break;
                    }
                  }
                }

                if (valid) {
                  calculated += matrix[b][srcBands];
                  switch (dataType) {
                    case DataBuffer.TYPE_BYTE:
                      calculated = ImageUtil.clampRoundByte(calculated);
                      result = ImageUtil.clampRoundByte(result);
                      break;
                    case DataBuffer.TYPE_USHORT:
                      calculated = ImageUtil.clampRoundUShort(calculated);
                      result = ImageUtil.clampRoundUShort(result);
                      break;
                    case DataBuffer.TYPE_SHORT:
                      calculated = ImageUtil.clampRoundShort(calculated);
                      result = ImageUtil.clampRoundShort(result);
                      break;
                    case DataBuffer.TYPE_INT:
                      calculated = ImageUtil.clampRoundInt(calculated);
                      result = ImageUtil.clampRoundInt(result);
                      break;
                    case DataBuffer.TYPE_FLOAT:
                      calculated = (float) calculated;
                      calculated = (float) result;
                      break;
                    case DataBuffer.TYPE_DOUBLE:
                      break;
                    default:
                      break;
                  }
                  assertEquals(result, calculated, TOLERANCE);
                } else {
                  assertEquals(result, destNoData, TOLERANCE);
                }
              }
            } else {
              for (int b = 0; b < dstBands; b++) {
                assertEquals(tile.getSampleDouble(x, y, b), destNoData, TOLERANCE);
              }
            }
          }
        }
      }
    }

    // Disposal of the output image
    combined.dispose();
  }