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);
    }
  }
Esempio n. 2
0
  public boolean equals(RenderedImage img1, RenderedImage img2) {
    if (img1 == img2) return true;
    if (img1 == null || img2 == null) return false;
    Raster r1 = img1.getData();
    Raster r2 = img2.getData();

    if (!sameBounds(r1, r2)) return false;
    if (!sameBands(r1, r2)) return false;

    if (!sameRasterData(r1, r2)) return false;

    return true;
  }
  protected void printImage(RenderedImage renderedImage) {
    SampleModel sampleModel = renderedImage.getSampleModel();

    int height = renderedImage.getHeight();
    int width = renderedImage.getWidth();
    int numOfBands = sampleModel.getNumBands();

    int[] pixels = new int[height * width * numOfBands];

    Raster raster = renderedImage.getData();

    raster.getPixels(0, 0, width, height, pixels);

    int offset = 0;

    for (int h = 0; h < height; h++) {
      for (int w = 0; w < width; w++) {
        offset = (h * width * numOfBands) + (w * numOfBands);

        System.out.print("[" + w + ", " + h + "] = ");

        for (int b = 0; b < numOfBands; b++) {
          System.out.print(pixels[offset + b] + " ");
        }
      }

      System.out.println();
    }
  }
  public void testTileStackImage() throws Exception {
    final SunTileCache tileCache = (SunTileCache) JAI.getDefaultInstance().getTileCache();
    tileCache.flush();
    long cacheTileCount = tileCache.getCacheTileCount();
    assertEquals(0, cacheTileCount);

    Operator operator =
        new Operator() {
          @Override
          public void initialize() throws OperatorException {
            Product product = new Product("name", "desc", 1, 1);

            RenderedOp d =
                ConstantDescriptor.create(
                    (float) product.getSceneRasterWidth(),
                    (float) product.getSceneRasterHeight(),
                    new Float[] {0.5f},
                    null);

            product.addBand("a", ProductData.TYPE_INT32);
            product.addBand("b", ProductData.TYPE_INT32);
            product.addBand("c", ProductData.TYPE_INT32);
            product.addBand("d", ProductData.TYPE_FLOAT32).setSourceImage(d);
            setTargetProduct(product);
          }

          @Override
          public void computeTileStack(
              Map<Band, Tile> targetTiles, Rectangle targetRectangle, ProgressMonitor pm)
              throws OperatorException {
            assertEquals(3, targetTiles.size());

            for (Tile tt : targetTiles.values()) {
              ProductData dataBuffer = tt.getDataBuffer();
              int numElems = dataBuffer.getNumElems();
              for (int i = 0; i < numElems; i++) {
                dataBuffer.setElemIntAt(i, i);
              }
            }

            assertEquals(0, tileCache.getCacheTileCount());
          }
        };

    Product targetProduct = operator.getTargetProduct();
    assertNotNull(targetProduct);
    assertEquals(4, targetProduct.getNumBands());

    MultiLevelImage sourceImage = targetProduct.getBandAt(0).getSourceImage();
    RenderedImage image = sourceImage.getImage(0);
    assertNotNull(image);
    assertEquals(OperatorImageTileStack.class, image.getClass());
    // pull data to trigger computation
    image.getData();

    cacheTileCount = tileCache.getCacheTileCount();
    assertEquals(3, cacheTileCount);
  }
Esempio n. 5
0
 /**
  * Makes sure the image starts at 0,0, all images coming from files do but the ones coming from a
  * JAI chain might not
  *
  * @param image
  * @return
  */
 static final RenderedImage realignImage(RenderedImage image) {
   if (image.getMinX() > 0 || image.getMinY() > 0) {
     return new BufferedImage(
         image.getColorModel(),
         ((WritableRaster) image.getData()).createWritableTranslatedChild(0, 0),
         image.getColorModel().isAlphaPremultiplied(),
         null);
   } else {
     return image;
   }
 }
Esempio n. 6
0
  public static ImageData createImageData(RenderedImage image) {
    ImageData swtdata = null;
    int width = image.getWidth();
    int height = image.getHeight();
    PaletteData palette;
    int depth;

    depth = 24;
    palette = new PaletteData(0xFF0000, 0xFF00, 0xFF);
    swtdata = new ImageData(width, height, depth, palette);
    swtdata.transparentPixel = TRANSPARENT;

    byte blueT = (byte) ((TRANSPARENT) & 0xFF);
    byte greenT = (byte) ((TRANSPARENT >> 8) & 0xFF);
    byte redT = (byte) ((TRANSPARENT >> 16) & 0xFF);
    // System.out.println("red="+redT+"blue"+blueT+"green"+greenT);
    // System.out.println("Transparent"+TRANSPARENT);

    // awtImage2.getRGB();
    Raster raster = image.getData();
    int[] awtdata =
        raster.getPixels(
            0, 0, width, height, new int[width * height * 3]); // raster.getNumBands()]);
    int step = swtdata.depth / 8;

    byte[] data = swtdata.data;
    int baseindex = 0;
    // System.out.println( "AWT size:" + awtdata.length );
    for (int y = 0; y < height; y++) {
      int idx = ((0 + y) * swtdata.bytesPerLine) + (0 * step);

      for (int x = 0; x < width; x++) {
        baseindex = (x + (y * width)) * 4;

        if (awtdata[baseindex + 3] == 0) {
          data[idx++] = blueT;
          data[idx++] = greenT;
          data[idx++] = redT;
        } else {
          data[idx++] = (byte) awtdata[baseindex];
          data[idx++] = (byte) awtdata[baseindex + 1];
          data[idx++] = (byte) awtdata[baseindex + 2];
        }
      }
    }
    return swtdata;
  }
Esempio n. 7
0
  public static java.awt.Image load(
      String codecName,
      java.io.InputStream inputStream,
      edu.cmu.cs.stage3.image.codec.ImageDecodeParam imageDecodeParam)
      throws java.io.IOException {
    java.io.BufferedInputStream bufferedInputStream;
    if (inputStream instanceof java.io.BufferedInputStream) {
      bufferedInputStream = (java.io.BufferedInputStream) inputStream;
    } else {
      bufferedInputStream = new java.io.BufferedInputStream(inputStream);
    }
    edu.cmu.cs.stage3.image.codec.ImageDecoder imageDecoder =
        edu.cmu.cs.stage3.image.codec.ImageCodec.createImageDecoder(
            codecName, bufferedInputStream, imageDecodeParam);
    java.awt.image.RenderedImage renderedImage = imageDecoder.decodeAsRenderedImage();

    if (renderedImage instanceof java.awt.Image) {
      return (java.awt.Image) renderedImage;
    } else {
      java.awt.image.Raster raster = renderedImage.getData();
      java.awt.image.ColorModel colorModel = renderedImage.getColorModel();
      java.util.Hashtable properties = null;
      String[] propertyNames = renderedImage.getPropertyNames();
      if (propertyNames != null) {
        properties = new java.util.Hashtable();
        for (String propertyName : propertyNames) {
          properties.put(propertyName, renderedImage.getProperty(propertyName));
        }
      }
      java.awt.image.WritableRaster writableRaster;
      if (raster instanceof java.awt.image.WritableRaster) {
        writableRaster = (java.awt.image.WritableRaster) raster;
      } else {
        writableRaster = raster.createCompatibleWritableRaster();
      }
      java.awt.image.BufferedImage bufferedImage =
          new java.awt.image.BufferedImage(
              renderedImage.getColorModel(),
              writableRaster,
              colorModel.isAlphaPremultiplied(),
              properties);
      return bufferedImage;
    }
  }
  private synchronized Raster readRect(
      int sourceOffsetX,
      int sourceOffsetY,
      int sourceStepX,
      int sourceStepY,
      int destOffsetX,
      int destOffsetY,
      int destWidth,
      int destHeight)
      throws IOException {
    ImageReadParam readParam = imageReader.getDefaultReadParam();
    int subsamplingXOffset = sourceOffsetX % sourceStepX;
    int subsamplingYOffset = sourceOffsetY % sourceStepY;
    readParam.setSourceSubsampling(
        sourceStepX, sourceStepY, subsamplingXOffset, subsamplingYOffset);
    RenderedImage subsampledImage = imageReader.readAsRenderedImage(FIRST_IMAGE, readParam);

    return subsampledImage.getData(new Rectangle(destOffsetX, destOffsetY, destWidth, destHeight));
  }
Esempio n. 9
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;
    }
  }
Esempio n. 10
0
  @Test
  public void testRasterFilterRed() throws Exception {
    String queryString =
        "wcs?sourcecoverage="
            + getLayerId(MOSAIC)
            + "&request=getcoverage"
            + "&service=wcs&version=1.0.0&format=image/tiff&crs=EPSG:4326"
            + "&bbox=0,0,1,1&CQL_FILTER=location like 'red%25'&width=150&height=150";

    MockHttpServletResponse response = getAsServletResponse(queryString);

    RenderedImage image = readTiff(response);

    // check the pixel
    int[] pixel = new int[3];
    image.getData().getPixel(0, 0, pixel);
    assertEquals(255, pixel[0]);
    assertEquals(0, pixel[1]);
    assertEquals(0, pixel[2]);
  }
  protected RenderedImage convert(RenderedImage renderedImage) throws Exception {

    int height = renderedImage.getHeight();
    int width = renderedImage.getWidth();

    SampleModel sampleModel = renderedImage.getSampleModel();
    ColorModel colorModel = renderedImage.getColorModel();

    Raster raster = renderedImage.getData();

    DataBuffer dataBuffer = raster.getDataBuffer();

    if (colorModel instanceof IndexColorModel) {
      IndexColorModel indexColorModel = (IndexColorModel) colorModel;

      int mapSize = indexColorModel.getMapSize();

      byte[][] data = new byte[4][mapSize];

      indexColorModel.getReds(data[0]);
      indexColorModel.getGreens(data[1]);
      indexColorModel.getBlues(data[2]);
      indexColorModel.getAlphas(data[3]);

      LookupTableJAI lookupTableJAI = new LookupTableJAI(data);

      renderedImage = LookupDescriptor.create(renderedImage, lookupTableJAI, null);
    } else if (sampleModel.getNumBands() == 2) {
      List<Byte> bytesList = new ArrayList<Byte>(height * width * _NUM_OF_BANDS);

      List<Byte> tempBytesList = new ArrayList<Byte>(_NUM_OF_BANDS);

      for (int i = 0; i < dataBuffer.getSize(); i++) {
        int mod = (i + 1) % 2;

        int elemPos = i;

        if (mod == 0) {
          tempBytesList.add((byte) dataBuffer.getElem(elemPos - 1));
          tempBytesList.add((byte) dataBuffer.getElem(elemPos - 1));
        }

        tempBytesList.add((byte) dataBuffer.getElem(elemPos));

        if (mod == 0) {
          Collections.reverse(tempBytesList);

          bytesList.addAll(tempBytesList);

          tempBytesList.clear();
        }
      }

      byte[] data = ArrayUtil.toArray(bytesList.toArray(new Byte[bytesList.size()]));

      DataBuffer newDataBuffer = new DataBufferByte(data, data.length);

      renderedImage = createRenderedImage(renderedImage, height, width, newDataBuffer);
    } else if (colorModel.getTransparency() != Transparency.TRANSLUCENT) {
      List<Byte> bytesList = new ArrayList<Byte>(height * width * _NUM_OF_BANDS);

      List<Byte> tempBytesList = new ArrayList<Byte>(_NUM_OF_BANDS);

      for (int i = 0; i < dataBuffer.getSize(); i++) {
        int mod = (i + 1) % 3;

        int elemPos = i;

        tempBytesList.add((byte) dataBuffer.getElem(elemPos));

        if (mod == 0) {
          tempBytesList.add((byte) 255);

          Collections.reverse(tempBytesList);

          bytesList.addAll(tempBytesList);

          tempBytesList.clear();
        }
      }

      byte[] data = ArrayUtil.toArray(bytesList.toArray(new Byte[bytesList.size()]));

      DataBuffer newDataBuffer = new DataBufferByte(data, data.length);

      renderedImage = createRenderedImage(renderedImage, height, width, newDataBuffer);
    }

    return renderedImage;
  }
Esempio n. 12
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;
        }
      }
    }
  }
  public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param)
      throws IOException {
    if (stream == null) {
      throw new IllegalStateException(I18N.getString("WBMPImageWriter3"));
    }

    if (image == null) {
      throw new IllegalArgumentException(I18N.getString("WBMPImageWriter4"));
    }

    clearAbortRequest();
    processImageStarted(0);
    if (param == null) param = getDefaultWriteParam();

    RenderedImage input = null;
    Raster inputRaster = null;
    boolean writeRaster = image.hasRaster();
    Rectangle sourceRegion = param.getSourceRegion();
    SampleModel sampleModel = null;

    if (writeRaster) {
      inputRaster = image.getRaster();
      sampleModel = inputRaster.getSampleModel();
    } else {
      input = image.getRenderedImage();
      sampleModel = input.getSampleModel();

      inputRaster = input.getData();
    }

    checkSampleModel(sampleModel);
    if (sourceRegion == null) sourceRegion = inputRaster.getBounds();
    else sourceRegion = sourceRegion.intersection(inputRaster.getBounds());

    if (sourceRegion.isEmpty()) throw new RuntimeException(I18N.getString("WBMPImageWriter1"));

    int scaleX = param.getSourceXSubsampling();
    int scaleY = param.getSourceYSubsampling();
    int xOffset = param.getSubsamplingXOffset();
    int yOffset = param.getSubsamplingYOffset();

    sourceRegion.translate(xOffset, yOffset);
    sourceRegion.width -= xOffset;
    sourceRegion.height -= yOffset;

    int minX = sourceRegion.x / scaleX;
    int minY = sourceRegion.y / scaleY;
    int w = (sourceRegion.width + scaleX - 1) / scaleX;
    int h = (sourceRegion.height + scaleY - 1) / scaleY;

    Rectangle destinationRegion = new Rectangle(minX, minY, w, h);
    sampleModel = sampleModel.createCompatibleSampleModel(w, h);

    SampleModel destSM = sampleModel;

    // If the data are not formatted nominally then reformat.
    if (sampleModel.getDataType() != DataBuffer.TYPE_BYTE
        || !(sampleModel instanceof MultiPixelPackedSampleModel)
        || ((MultiPixelPackedSampleModel) sampleModel).getDataBitOffset() != 0) {
      destSM = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, w, h, 1, w + 7 >> 3, 0);
    }

    if (!destinationRegion.equals(sourceRegion)) {
      if (scaleX == 1 && scaleY == 1)
        inputRaster =
            inputRaster.createChild(
                inputRaster.getMinX(), inputRaster.getMinY(), w, h, minX, minY, null);
      else {
        WritableRaster ras = Raster.createWritableRaster(destSM, new Point(minX, minY));

        byte[] data = ((DataBufferByte) ras.getDataBuffer()).getData();

        for (int j = minY, y = sourceRegion.y, k = 0; j < minY + h; j++, y += scaleY) {

          for (int i = 0, x = sourceRegion.x; i < w; i++, x += scaleX) {
            int v = inputRaster.getSample(x, y, 0);
            data[k + (i >> 3)] |= v << (7 - (i & 7));
          }
          k += w + 7 >> 3;
        }
        inputRaster = ras;
      }
    }

    // If the data are not formatted nominally then reformat.
    if (!destSM.equals(inputRaster.getSampleModel())) {
      WritableRaster raster =
          Raster.createWritableRaster(
              destSM, new Point(inputRaster.getMinX(), inputRaster.getMinY()));
      raster.setRect(inputRaster);
      inputRaster = raster;
    }

    // Check whether the image is white-is-zero.
    boolean isWhiteZero = false;
    if (!writeRaster && input.getColorModel() instanceof IndexColorModel) {
      IndexColorModel icm = (IndexColorModel) input.getColorModel();
      isWhiteZero = icm.getRed(0) > icm.getRed(1);
    }

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

    // Write WBMP header.
    stream.write(0); // TypeField
    stream.write(0); // FixHeaderField
    stream.write(intToMultiByte(w)); // width
    stream.write(intToMultiByte(h)); // height

    // Write the data.
    if (!isWhiteZero && lineStride == bytesPerRow) {
      // Write the entire image.
      stream.write(bdata, 0, h * bytesPerRow);
      processImageProgress(100.0F);
    } else {
      // Write the image row-by-row.
      int offset = 0;
      if (!isWhiteZero) {
        // Black-is-zero
        for (int row = 0; row < h; row++) {
          if (abortRequested()) break;
          stream.write(bdata, offset, bytesPerRow);
          offset += lineStride;
          processImageProgress(100.0F * row / h);
        }
      } else {
        // White-is-zero: need to invert data.
        byte[] inverted = new byte[bytesPerRow];
        for (int row = 0; row < h; row++) {
          if (abortRequested()) break;
          for (int col = 0; col < bytesPerRow; col++) {
            inverted[col] = (byte) (~(bdata[col + offset]));
          }
          stream.write(inverted, 0, bytesPerRow);
          offset += lineStride;
          processImageProgress(100.0F * row / h);
        }
      }
    }

    if (abortRequested()) processWriteAborted();
    else {
      processImageComplete();
      stream.flushBefore(stream.getStreamPosition());
    }
  }
Esempio n. 14
0
  /**
   * Returns the bytes of an image.
   *
   * @param image to be converted to bytes
   * @param bkg the color to be used for alpha-multiplication
   * @param code ARGB, A, or BGR, ... you may also use *ARGB to pre-multiply with alpha
   * @param pad number of bytes to pad the scanline with (1=byte, 2=short, 4=int, ...)
   */
  public static byte[] getBytes(RenderedImage image, Color bkg, String code, int pad) {
    if (pad < 1) pad = 1;

    Raster raster = image.getData();

    int width = image.getWidth();
    int height = image.getHeight();

    boolean preMultiply = (code.charAt(0) == '*');
    if (preMultiply) code = code.substring(1);

    int pixelSize = code.length();

    int size = width * height * pixelSize;
    size += (width % pad) * height;
    int index = 0;
    byte[] bytes = new byte[size];

    ColorModel colorModel = image.getColorModel();

    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {

        int argb = colorModel.getRGB(raster.getDataElements(x, y, (Object) null));
        int a = ((argb >> 24) & 0xFF);
        int r = ((argb >> 16) & 0xFF);
        int g = ((argb >> 8) & 0xFF);
        int b = ((argb >> 0) & 0xFF);

        // Check the transparancy. If transparent substitute
        // the background color.
        if (preMultiply && (a < 0xFF)) {
          if (bkg == null) bkg = Color.BLACK;
          double alpha = a / 255.0;
          r = (int) (alpha * r + (1 - alpha) * bkg.getRed());
          g = (int) (alpha * g + (1 - alpha) * bkg.getGreen());
          b = (int) (alpha * b + (1 - alpha) * bkg.getBlue());
        }

        for (int i = 0; i < code.length(); i++) {
          switch (code.charAt(i)) {
            case 'a':
            case 'A':
              bytes[index] = (byte) a;
              break;

            case 'r':
            case 'R':
              bytes[index] = (byte) r;
              break;

            case 'g':
            case 'G':
              bytes[index] = (byte) g;
              break;

            case 'b':
            case 'B':
              bytes[index] = (byte) b;
              break;

            default:
              System.err.println(
                  ImageUtilities.class.getClass()
                      + ": Invalid code in '"
                      + code
                      + "'"); //$NON-NLS-1$ //$NON-NLS-2$
              break;
          }
          index++;
        }
      }
      for (int i = 0; i < (width % pad); i++) {
        bytes[index] = 0;
        index++;
      }
    }

    return bytes;
  }
Esempio n. 15
0
  public TiledImage cutFrame(
      RenderedImage image,
      double resdpi,
      int frameWidthPix,
      int frameHeightPix,
      boolean reverseImage,
      int frameNum,
      double scaleMult,
      boolean rescale,
      boolean correctrotation) {
    noCut = false;
    if (farEdge == null || farEdge.stdDev > worstEdgeStdDevAllowed) {
      System.out.println(
          "WARNING: far film edge for frame "
              + frameNum
              + " has a stdDev of "
              + (farEdge == null ? "null" : Double.toString(farEdge.stdDev))
              + " and will not be used.");

      if (sprocketEdge == null || sprocketEdge.stdDev > worstEdgeStdDevAllowed) {
        System.out.println(
            "WARNING: near film edge for frame "
                + frameNum
                + " has a stdDev of "
                + (sprocketEdge == null ? "null" : Double.toString(sprocketEdge.stdDev))
                + " and will not be used.");
        noCut = true;
        return null;
      } else
        preMapSetupUsingSprocketEdge(
            frameWidthPix, frameHeightPix, scaleMult, reverseImage, rescale, correctrotation);
    } else
      preMapSetupUsingFarEdge(
          frameWidthPix, frameHeightPix, scaleMult, reverseImage, rescale, correctrotation);

    outOfBounds = false;

    //      double resdpmm = resdpi / FilmSpec.mmPerInch;
    //      double [] spec = FilmSpec.filmModel(filmType);

    TiledImage ret =
        new TiledImage(
            0,
            0,
            frameWidthPix,
            frameHeightPix,
            0,
            0,
            image.getSampleModel().createCompatibleSampleModel(frameWidthPix, frameHeightPix),
            image.getColorModel());

    RenderedImage[] srcs = new RenderedImage[1];
    srcs[0] = image;
    RasterFormatTag[] tags = RasterAccessor.findCompatibleTags(srcs, ret);
    RasterFormatTag srctag = tags[0];
    RasterFormatTag dsttag = tags[1];

    Raster srcraster = image.getData();
    RasterAccessor srcra =
        new RasterAccessor(srcraster, srcraster.getBounds(), srctag, image.getColorModel());

    Raster dstraster = ret.getWritableTile(0, 0);
    RasterAccessor dstra =
        new RasterAccessor(dstraster, dstraster.getBounds(), dsttag, ret.getColorModel());

    int srcwidth = srcra.getWidth();
    int srcheight = srcra.getHeight();
    //      int srcbandcount = srcra.getNumBands();
    byte bandedsrc[][] = srcra.getByteDataArrays();
    int srcBandOffsets[] = srcra.getBandOffsets();
    int srcPixelStride = srcra.getPixelStride();
    int srcScanLineStride = srcra.getScanlineStride();

    int dstwidth = dstra.getWidth();
    int dstheight = dstra.getHeight();
    int dstbandcount = dstra.getNumBands();
    byte bandeddst[][] = dstra.getByteDataArrays();
    int dstBandOffsets[] = dstra.getBandOffsets();
    int dstPixelStride = dstra.getPixelStride();
    int dstScanLineStride = dstra.getScanlineStride();

    for (int band = 0; band < dstbandcount; band++) {
      byte dst[] = bandeddst[band];
      byte src[] = bandedsrc[band];
      int srcBegCurBand = srcBandOffsets[band];
      int dstBegCurRow = dstBandOffsets[band];
      for (int dstRow = 0; dstRow < dstheight; dstRow++) {
        int dstpos = dstBegCurRow;

        for (int dstCol = 0; dstCol < dstwidth; dstCol++) {
          Point srclocation = map(dstRow, dstCol, frameWidthPix, frameHeightPix, reverseImage);

          if (leftmostCol > srclocation.x) leftmostCol = srclocation.x;
          if (rightmostCol < srclocation.x) rightmostCol = srclocation.x;
          if (topmostRow > srclocation.y) topmostRow = srclocation.y;
          if (bottommostRow < srclocation.y) bottommostRow = srclocation.y;

          if (srclocation.y < 0
              || srclocation.y >= srcheight
              || srclocation.x < 0
              || srclocation.x >= srcwidth) {
            dst[dstpos] = (byte) 0;
            outOfBounds = true;
          } else
            dst[dstpos] =
                src[
                    srcBegCurBand
                        + ((srclocation.y * srcScanLineStride) + (srclocation.x * srcPixelStride))];

          dstpos += dstPixelStride;
        }

        dstBegCurRow += dstScanLineStride;
      }
    }

    frameCut = true;
    return ret;
  }