Пример #1
0
  /** Generate a tiled image that contains a view of the mask. */
  @SuppressWarnings("restriction")
  public TiledImage getMaskImage() {
    TiledImage ti =
        new TiledImage(
            0,
            0,
            mwidth,
            mheight,
            0,
            0,
            new PixelInterleavedSampleModel(
                DataBuffer.TYPE_BYTE, mwidth, mheight, 1, mwidth, Transform.bandstride),
            new ComponentColorModel(
                ColorSpace.getInstance(ColorSpace.CS_GRAY),
                false,
                false,
                ComponentColorModel.OPAQUE,
                DataBuffer.TYPE_BYTE));

    WritableRaster gradRaster = ti.getWritableTile(0, 0);
    DataBufferByte gradDB = (DataBufferByte) gradRaster.getDataBuffer();
    byte[] gradImageData = gradDB.getData();

    int maskwh = mwidth * mheight;
    for (int i = 0; i < maskwh; i++) gradImageData[i] = (byte) mask[i];

    return ti;
  }
Пример #2
0
 /**
  * Encode the uncompressed source image stored in <code>srcImage</code> and output a YUV planar
  * image to the given destination buffer. See {@link #encodeYUV(byte[], int)} for more detail.
  *
  * @param srcImage a <code>BufferedImage</code> instance containing RGB or grayscale pixels to be
  *     encoded
  * @param dstBuf buffer that will receive the YUV planar image. Use {@link TJ#bufSizeYUV} to
  *     determine the appropriate size for this buffer based on the image width, height, and level
  *     of chrominance subsampling.
  * @param flags the bitwise OR of one or more of {@link TJ TJ.FLAG_*}
  */
 public void encodeYUV(BufferedImage srcImage, byte[] dstBuf, int flags) throws Exception {
   if (srcImage == null || dstBuf == null || flags < 0)
     throw new Exception("Invalid argument in encodeYUV()");
   int width = srcImage.getWidth();
   int height = srcImage.getHeight();
   int pixelFormat;
   boolean intPixels = false;
   if (byteOrder == null) byteOrder = ByteOrder.nativeOrder();
   switch (srcImage.getType()) {
     case BufferedImage.TYPE_3BYTE_BGR:
       pixelFormat = TJ.PF_BGR;
       break;
     case BufferedImage.TYPE_4BYTE_ABGR:
     case BufferedImage.TYPE_4BYTE_ABGR_PRE:
       pixelFormat = TJ.PF_XBGR;
       break;
     case BufferedImage.TYPE_BYTE_GRAY:
       pixelFormat = TJ.PF_GRAY;
       break;
     case BufferedImage.TYPE_INT_BGR:
       if (byteOrder == ByteOrder.BIG_ENDIAN) pixelFormat = TJ.PF_XBGR;
       else pixelFormat = TJ.PF_RGBX;
       intPixels = true;
       break;
     case BufferedImage.TYPE_INT_RGB:
     case BufferedImage.TYPE_INT_ARGB:
     case BufferedImage.TYPE_INT_ARGB_PRE:
       if (byteOrder == ByteOrder.BIG_ENDIAN) pixelFormat = TJ.PF_XRGB;
       else pixelFormat = TJ.PF_BGRX;
       intPixels = true;
       break;
     default:
       throw new Exception("Unsupported BufferedImage format");
   }
   WritableRaster wr = srcImage.getRaster();
   if (subsamp < 0) throw new Exception("Subsampling level not set");
   if (intPixels) {
     SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) srcImage.getSampleModel();
     int pitch = sm.getScanlineStride();
     DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
     int[] buf = db.getData();
     encodeYUV(buf, width, pitch, height, pixelFormat, dstBuf, subsamp, flags);
   } else {
     ComponentSampleModel sm = (ComponentSampleModel) srcImage.getSampleModel();
     int pixelSize = sm.getPixelStride();
     if (pixelSize != TJ.getPixelSize(pixelFormat))
       throw new Exception("Inconsistency between pixel format and pixel size in BufferedImage");
     int pitch = sm.getScanlineStride();
     DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
     byte[] buf = db.getData();
     encodeYUV(buf, width, pitch, height, pixelFormat, dstBuf, subsamp, flags);
   }
   compressedSize = TJ.bufSizeYUV(width, height, subsamp);
 }
Пример #3
0
  public void write(IIOMetadata streamMetadata, IIOImage img, ImageWriteParam param)
      throws IOException {
    ImageOutputStream out = (ImageOutputStream) getOutput();

    if (!(img.getRenderedImage() instanceof BufferedImage)) {
      throw new IOException(getClass().getName() + "write:\nCan only write BufferedImage objects");
    }
    BufferedImage image = (BufferedImage) img.getRenderedImage();

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

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      JFIFOutputStream os;

      if (image.getType() == BufferedImage.TYPE_BYTE_GRAY) { // one   component;  grey scale
        os = new JFIFOutputStream(baos, false, height, width); // SOF:start of frame

        WritableRaster raster = image.getRaster();
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        byte[] imgdata = (byte[]) buffer.getData();

        os.write(imgdata);
        os.close(); // EOF: end of frame
      } else if (image.getType() == BufferedImage.TYPE_INT_RGB) { // three components; YCbCr
        os = new JFIFOutputStream(baos, true, height, width); // SOF:start of frame

        WritableRaster raster = image.getRaster();
        DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
        int[] imgdata = (int[]) buffer.getData();

        os.write(imgdata);
        os.close(); // EOF: end of frame
      } else { // three components; YCbCr
        os = new JFIFOutputStream(baos, true, height, width); // SOF:start of frame
        for (int y = 0; y < height; y++) {
          for (int x = 0; x < width; x++) {
            os.write(image.getRGB(x, y));
          }
        }
        os.close(); // EOF: end of frame
      }
      out.write(baos.toByteArray()); // write to image stream
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(
          getClass().getName() + ".write:\n\tCould not write image due to :\n\t" + e.getMessage());
    }
  }
Пример #4
0
    BufferedImage getThumbnail(ImageInputStream iis, JPEGImageReader reader) throws IOException {
      iis.mark();
      iis.seek(streamPos);
      DataBufferByte buffer = new DataBufferByte(getLength());
      readByteBuffer(iis, buffer.getData(), reader, 1.0F, 0.0F);
      iis.reset();

      WritableRaster raster =
          Raster.createInterleavedRaster(
              buffer, thumbWidth, thumbHeight, thumbWidth * 3, 3, new int[] {0, 1, 2}, null);
      ColorModel cm =
          new ComponentColorModel(
              JPEG.JCS.sRGB, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_BYTE);
      return new BufferedImage(cm, raster, false, null);
    }
Пример #5
0
    BufferedImage getThumbnail(ImageInputStream iis, JPEGImageReader reader) throws IOException {
      iis.mark();
      iis.seek(streamPos);
      // read the palette
      byte[] palette = new byte[PALETTE_SIZE];
      float palettePart = ((float) PALETTE_SIZE) / getLength();
      readByteBuffer(iis, palette, reader, palettePart, 0.0F);
      DataBufferByte buffer = new DataBufferByte(thumbWidth * thumbHeight);
      readByteBuffer(iis, buffer.getData(), reader, 1.0F - palettePart, palettePart);
      iis.read();
      iis.reset();

      IndexColorModel cm = new IndexColorModel(8, 256, palette, 0, false);
      SampleModel sm = cm.createCompatibleSampleModel(thumbWidth, thumbHeight);
      WritableRaster raster = Raster.createWritableRaster(sm, buffer, null);
      return new BufferedImage(cm, raster, false, null);
    }
  private byte[] getROIData(ROI roi, Rectangle rectIMG) {
    byte[] dataROI;
    PlanarImage roiIMG = roi.getAsImage();
    Rectangle rectROI = roiIMG.getBounds();
    // Forcing to component colormodel in order to avoid packed bits
    ImageWorker w = new ImageWorker();
    w.setImage(roiIMG);
    w.forceComponentColorModel();
    RenderedImage img = w.getRenderedImage();
    //
    BufferedImage test =
        new BufferedImage(rectIMG.width, rectIMG.height, BufferedImage.TYPE_BYTE_GRAY);
    ImageLayout2 layout = new ImageLayout2(test);
    layout.setMinX(img.getMinX());
    layout.setMinY(img.getMinY());
    layout.setWidth(img.getWidth());
    layout.setHeight(img.getHeight());
    // Lookup
    byte[] lut = new byte[256];
    lut[255] = 1;
    lut[1] = 1;
    LookupTableJAI table = new LookupTableJAI(lut);
    RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
    RenderedOp transformed = LookupDescriptor.create(img, table, hints);

    Graphics2D gc2d = null;
    // Translation parameters in order to position the ROI data correctly in the Raster Space
    int trX = -rectIMG.x + rectROI.x - rectIMG.x;
    int trY = -rectIMG.y + rectROI.y - rectIMG.y;
    try {
      gc2d = test.createGraphics();
      gc2d.drawRenderedImage(transformed, AffineTransform.getTranslateInstance(trX, trY));
    } finally {
      gc2d.dispose();
    }
    Rectangle testRect = new Rectangle(rectIMG.width, rectIMG.height);
    DataBufferByte dbRoi = (DataBufferByte) test.getData(testRect).getDataBuffer();
    dataROI = dbRoi.getData();
    // BufferedImage is stored in memory so the planarImage chain before can be disposed
    ImageUtilities.disposePlanarImageChain(transformed);
    // Flush of the BufferedImage
    test.flush();

    return dataROI;
  }
Пример #7
0
  protected static void divide_BYTE_COMP_Data(WritableRaster wr) {
    // System.out.println("Multiply Int: " + wr);

    ComponentSampleModel csm;
    csm = (ComponentSampleModel) wr.getSampleModel();

    final int width = wr.getWidth();

    final int scanStride = csm.getScanlineStride();
    final int pixStride = csm.getPixelStride();
    final int[] bandOff = csm.getBandOffsets();

    DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
    final int base =
        (db.getOffset()
            + csm.getOffset(
                wr.getMinX() - wr.getSampleModelTranslateX(),
                wr.getMinY() - wr.getSampleModelTranslateY()));

    int a = 0;
    int aOff = bandOff[bandOff.length - 1];
    int bands = bandOff.length - 1;
    int b, i;
    // Access the pixel data array
    final byte pixels[] = db.getBankData()[0];
    for (int y = 0; y < wr.getHeight(); y++) {
      int sp = base + y * scanStride;
      final int end = sp + width * pixStride;
      while (sp < end) {
        a = pixels[sp + aOff] & 0xFF;
        if (a == 0) {
          for (b = 0; b < bands; b++) pixels[sp + bandOff[b]] = (byte) 0xFF;
        } else if (a < 255) {
          int aFP = (0x00FF0000 / a);
          for (b = 0; b < bands; b++) {
            i = sp + bandOff[b];
            pixels[i] = (byte) (((pixels[i] & 0xFF) * aFP) >>> 16);
          }
        }
        sp += pixStride;
      }
    }
  }
Пример #8
0
 private static void initImg(BufferedImage img, int pf, int flags) throws Exception {
   WritableRaster wr = img.getRaster();
   int imgType = img.getType();
   if (imgType == BufferedImage.TYPE_INT_RGB
       || imgType == BufferedImage.TYPE_INT_BGR
       || imgType == BufferedImage.TYPE_INT_ARGB
       || imgType == BufferedImage.TYPE_INT_ARGB_PRE) {
     SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) img.getSampleModel();
     int pitch = sm.getScanlineStride();
     DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
     int[] buf = db.getData();
     initIntBuf(buf, img.getWidth(), pitch, img.getHeight(), pf, flags);
   } else {
     ComponentSampleModel sm = (ComponentSampleModel) img.getSampleModel();
     int pitch = sm.getScanlineStride();
     DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
     byte[] buf = db.getData();
     initBuf(buf, img.getWidth(), pitch, img.getHeight(), pf, flags);
   }
 }
Пример #9
0
  /**
   * Constructs a BytePackedRaster with the given SampleModel, DataBuffer, and parent. DataBuffer
   * must be a DataBufferByte and SampleModel must be of type MultiPixelPackedSampleModel. When
   * translated into the base Raster's coordinate system, aRegion must be contained by the base
   * Raster. Origin is the coordinate in the new Raster's coordinate system of the origin of the
   * base Raster. (The base Raster is the Raster's ancestor which has no parent.)
   *
   * <p>Note that this constructor should generally be called by other constructors or create
   * methods, it should not be used directly.
   *
   * @param sampleModel The SampleModel that specifies the layout.
   * @param dataBuffer The DataBufferShort that contains the image data.
   * @param aRegion The Rectangle that specifies the image area.
   * @param origin The Point that specifies the origin.
   * @param parent The parent (if any) of this raster.
   * @exception RasterFormatException if the parameters do not conform to requirements of this
   *     Raster type.
   */
  public BytePackedRaster(
      SampleModel sampleModel,
      DataBuffer dataBuffer,
      Rectangle aRegion,
      Point origin,
      BytePackedRaster parent) {
    super(sampleModel, dataBuffer, aRegion, origin, parent);
    this.maxX = minX + width;
    this.maxY = minY + height;

    if (!(dataBuffer instanceof DataBufferByte)) {
      throw new RasterFormatException("BytePackedRasters must have" + "byte DataBuffers");
    }
    DataBufferByte dbb = (DataBufferByte) dataBuffer;
    this.data = stealData(dbb, 0);
    if (dbb.getNumBanks() != 1) {
      throw new RasterFormatException(
          "DataBuffer for BytePackedRasters" + " must only have 1 bank.");
    }
    int dbOffset = dbb.getOffset();

    if (sampleModel instanceof MultiPixelPackedSampleModel) {
      MultiPixelPackedSampleModel mppsm = (MultiPixelPackedSampleModel) sampleModel;
      this.type = IntegerComponentRaster.TYPE_BYTE_BINARY_SAMPLES;
      pixelBitStride = mppsm.getPixelBitStride();
      if (pixelBitStride != 1 && pixelBitStride != 2 && pixelBitStride != 4) {
        throw new RasterFormatException("BytePackedRasters must have a bit depth of 1, 2, or 4");
      }
      scanlineStride = mppsm.getScanlineStride();
      dataBitOffset = mppsm.getDataBitOffset() + dbOffset * 8;
      int xOffset = aRegion.x - origin.x;
      int yOffset = aRegion.y - origin.y;
      dataBitOffset += xOffset * pixelBitStride + yOffset * scanlineStride * 8;
      bitMask = (1 << pixelBitStride) - 1;
      shiftOffset = 8 - pixelBitStride;
    } else {
      throw new RasterFormatException(
          "BytePackedRasters must have" + "MultiPixelPackedSampleModel");
    }
    verify(false);
  }
Пример #10
0
  /** Constructs a DirectRasterAccessor object */
  public DirectRasterAccessor(Raster raster, ColorModel cm) {
    DataBuffer db = raster.getDataBuffer();

    offsetX = raster.getMinX() - raster.getSampleModelTranslateX();
    offsetY = raster.getMinY() - raster.getSampleModelTranslateY();

    if (!(db instanceof DataBufferByte)) {
      throw new RuntimeException(
          "DataBuffer of Raster not of correct type "
              + "(expected DataBufferByte, got "
              + db.getClass().getName()
              + ")");
    }

    DataBufferByte dbb = (DataBufferByte) db;

    SampleModel sm = raster.getSampleModel();

    if (!(sm instanceof MultiPixelPackedSampleModel)) {
      throw new RuntimeException(
          "SampleModel of Raster not of correct type "
              + "(expected MultiPixelPackedSampleModel, got "
              + sm.getClass().getName()
              + ")");
    }

    MultiPixelPackedSampleModel mppsm = (MultiPixelPackedSampleModel) sm;

    data = dbb.getData();
    scanlineStride = mppsm.getScanlineStride();

    if (cm.getRGB(0) == Color.white.getRGB()) {
      white = 0;
      black = 1;
    } else {
      white = 1;
      black = 0;
    }
  }
  /**
   * Constructs a ByteBandedRaster with the given sampleModel, DataBuffer, and parent. DataBuffer
   * must be a DataBufferShort and SampleModel must be of type BandedSampleModel. When translated
   * into the base Raster's coordinate system, aRegion must be contained by the base Raster. Origin
   * is the coordinate in the new Raster's coordinate system of the origin of the base Raster. (The
   * base Raster is the Raster's ancestor which has no parent.)
   *
   * <p>Note that this constructor should generally be called by other constructors or create
   * methods, it should not be used directly.
   *
   * @param sampleModel The SampleModel that specifies the layout.
   * @param dataBuffer The DataBufferShort that contains the image data.
   * @param aRegion The Rectangle that specifies the image area.
   * @param origin The Point that specifies the origin.
   * @param parent The parent (if any) of this raster.
   */
  public ByteBandedRaster(
      SampleModel sampleModel,
      DataBuffer dataBuffer,
      Rectangle aRegion,
      Point origin,
      ByteBandedRaster parent) {

    super(sampleModel, dataBuffer, aRegion, origin, parent);
    this.maxX = minX + width;
    this.maxY = minY + height;

    if (!(dataBuffer instanceof DataBufferByte)) {
      throw new RasterFormatException("ByteBandedRaster must have" + "byte DataBuffers");
    }
    DataBufferByte dbb = (DataBufferByte) dataBuffer;

    if (sampleModel instanceof BandedSampleModel) {
      BandedSampleModel bsm = (BandedSampleModel) sampleModel;
      this.scanlineStride = bsm.getScanlineStride();
      int bankIndices[] = bsm.getBankIndices();
      int bandOffsets[] = bsm.getBandOffsets();
      int dOffsets[] = dbb.getOffsets();
      dataOffsets = new int[bankIndices.length];
      data = new byte[bankIndices.length][];
      int xOffset = aRegion.x - origin.x;
      int yOffset = aRegion.y - origin.y;
      for (int i = 0; i < bankIndices.length; i++) {
        data[i] = stealData(dbb, bankIndices[i]);
        dataOffsets[i] =
            dOffsets[bankIndices[i]] + xOffset + yOffset * scanlineStride + bandOffsets[i];
      }
    } else {
      throw new RasterFormatException("ByteBandedRasters must have" + "BandedSampleModels");
    }
    verify();
  }
 private static BufferedImage makeUnmanagedBI(final int type) {
   final BufferedImage bi = new BufferedImage(511, 255, type);
   final DataBuffer db = bi.getRaster().getDataBuffer();
   if (db instanceof DataBufferInt) {
     ((DataBufferInt) db).getData();
   } else if (db instanceof DataBufferShort) {
     ((DataBufferShort) db).getData();
   } else if (db instanceof DataBufferByte) {
     ((DataBufferByte) db).getData();
   } else {
     try {
       bi.setAccelerationPriority(0.0f);
     } catch (final Throwable ignored) {
     }
   }
   return bi;
 }
  // speed up for the case of 4x4
  // and data buffer bitOffset is 0 or 4
  private void byteLoop4x4(Raster source, WritableRaster dest, Rectangle destRect) {
    PixelAccessor pa = new PixelAccessor(source.getSampleModel(), null);
    PackedImageData pid = pa.getPackedPixels(source, source.getBounds(), false, false);

    if (pid.bitOffset % 4 != 0) {
      // special treatment only for offsets 0 and 4
      byteLoop(source, dest, destRect);
      return;
    }

    byte[] sourceData = pid.data;
    int sourceDBOffset = pid.offset;
    int dx = destRect.x;
    int dy = destRect.y;
    int dwi = destRect.width;
    int dhi = destRect.height;
    int sourceTransX = pid.rect.x; // source.getSampleModelTranslateX();
    int sourceTransY = pid.rect.y; // source.getSampleModelTranslateY();
    int sourceDataBitOffset = pid.bitOffset;
    int sourceScanlineStride = pid.lineStride;

    PixelInterleavedSampleModel destSM = (PixelInterleavedSampleModel) dest.getSampleModel();
    DataBufferByte destDB = (DataBufferByte) dest.getDataBuffer();
    int destTransX = dest.getSampleModelTranslateX();
    int destTransY = dest.getSampleModelTranslateY();
    int destScanlineStride = destSM.getScanlineStride();

    byte[] destData = destDB.getData();
    int destDBOffset = destDB.getOffset();

    int[] sAreaBitsOn = new int[2];

    for (int j = 0; j < dhi; j++) {
      int y = (dy + j) << 2; // int y = (dy + j) * blockY;
      int sourceYOffset = (y - sourceTransY) * sourceScanlineStride + sourceDBOffset;

      int destYOffset = (j + dy - destTransY) * destScanlineStride + destDBOffset;
      destYOffset += dx - destTransX;

      int selement, sbitnumi, sstartbiti, sbytenumi;
      // sbitnumi   - the 1st bit position from the minX of the raster
      // sstartbiti - the 1st bit position in the byte data
      // sbitnumi = blockX * dx - sourceTransX + sourceDataBitOffset;
      sbitnumi = (dx << 2) - sourceTransX + sourceDataBitOffset;

      for (int i = 0; i < dwi; ) {
        sbytenumi = sbitnumi >> 3;
        sstartbiti = sbitnumi % 8;
        int byteindex = sourceYOffset + sbytenumi;
        sAreaBitsOn[0] = sAreaBitsOn[1] = 0;
        for (int k = 0; k < 4; k++, byteindex += sourceScanlineStride) {
          selement = 0x00ff & (int) sourceData[byteindex];
          sAreaBitsOn[1] += lut[selement & 0x000f];
          sAreaBitsOn[0] += lut[selement >> 4];
        }
        // set dest elements
        // count in 4s
        // sstartbiti = 0 means the 0th of sAreaBitsOn is added to
        //     current dest position, ie destYOffset + i;
        // sstartbiti = 4 means the 1th of sAreaBitsOn is added to
        //     current dest position, ie destYOffset + i;
        // sstartbiti now means different
        // sstartbiti = sstartbiti / 4;
        sstartbiti >>= 2;

        while (sstartbiti < 2 && i < dwi) {
          destData[destYOffset + i] = lutGray[sAreaBitsOn[sstartbiti]];
          sstartbiti++;
          i++;
          sbitnumi += blockX;
        }
      }
    }
  }
Пример #14
0
 /**
  * Obtiene el arreglo de bytes de una imagen.
  *
  * @param image La imagen de la cual se va a extraer la información.
  * @return Regresa el arreglo de bytes de la imagen proporcionada.
  * @see java.awt.image.BufferedImage
  * @see java.awt.image.WritableRaster
  * @see java.awt.image.DataBufferByte
  */
 private byte[] getByteData(BufferedImage image) {
   WritableRaster raster = image.getRaster();
   DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
   return buffer.getData();
 }
Пример #15
0
  private IFD writeGrayImage(
      ImageOutputStream out, BufferedImage image, int comp, TIFFImageWriteParam param)
      throws IOException {
    image = convert(image, BufferedImage.TYPE_BYTE_GRAY);
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(width)); // 256
      ifd.add(new DEFactory.ImageLengthDE(height)); // 257

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(1);
      bpss.setBitsPerSample(0, 8); // gray scale
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(comp)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(BlackIsZero)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per strip
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      if (comp == JPEG) {
        maxrps = ((maxrps + 8 - 1) / 8) * 8;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(1)); // 277
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279
      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStream os = baos;
      JPEGOutputStream jpegos = null;

      if (comp == JPEG) { // add JPEGTables tag
        jpegos = new JPEGOutputStream(baos);

        int quality = (param == null) ? 50 : (int) (param.getCompressionQuality() * 100);

        jpegos.setZZQuantizationTable(0, JPEGConstants.LQT, quality);
        jpegos.setRawDCHuffmanTable(0, JPEGConstants.HLDCTable);
        jpegos.setRawACHuffmanTable(0, JPEGConstants.HLACTable);

        jpegos.defineQuantizationTables();
        jpegos.defineHuffmanTables();
        jpegos.close();

        DEFactory.JPEGTablesDE jpegtables = new DEFactory.JPEGTablesDE(baos.toByteArray());
        ifd.add(jpegtables); // 347

        baos.reset();

        os = jpegos;
      }

      WritableRaster raster = image.getRaster();
      DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
      byte[] imgdata = (byte[]) buffer.getData();

      int index = 0;
      for (int y = 0; y < height; y += maxrps) {
        /*
        Assume rgb image.

        Each strip: evaluate gray scale colour
                    save in byte array
                    write to image file
        */

        if ((height - y) < maxrps) {
          maxrps = height - y;
        }

        if (jpegos != null) { // jpeg: SOI,SOF,SOS marker
          jpegos.startOfImage();
          int[] hv = {0x11}; // (Hi<<4)|Vi
          int[] q = {0}; // quantization table 0
          jpegos.startOfFrame(maxrps, width, hv, q);
          int[] sel = {0}; // DC,AC code table 0
          jpegos.startOfScan(sel);
        }

        os.write(imgdata, y * width, maxrps * width);
        os.close(); // jpeg EOF: end of frame

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream
        baos.reset();
        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeRGBImage:\n\t" + e.getMessage());
    }
  }
  /**
   * Quick method for populating the {@link CUDABean} instance provided.
   *
   * @param bean
   * @param reference
   * @param coverage
   * @param geo
   * @param transform
   * @throws IOException
   * @throws MismatchedDimensionException
   * @throws TransformException
   */
  private void populateBean(
      CUDABean bean,
      boolean reference,
      GridCoverage2D coverage,
      Geometry geo,
      MathTransform transform,
      int buffer)
      throws IOException, MismatchedDimensionException, TransformException {

    RenderedImage image = coverage.getRenderedImage();

    // 0) Check if a buffer must be applied
    Geometry originalGeo = (Geometry) geo.clone();
    if (buffer > 0) {
      try {
        if (!"EPSG:4326"
            .equals(CRS.lookupIdentifier(coverage.getCoordinateReferenceSystem(), false))) {
          geo = geo.buffer(buffer);
        } else {
          geo = geo.buffer(buffer / 111.128);
        }
      } catch (FactoryException e) {
        geo = geo.buffer(buffer);
      }
    }

    // 1) Crop the two coverages with the selected Geometry
    GridCoverage2D crop = CROP.execute(coverage, geo, null);
    transform =
        ProjectiveTransform.create(
                (AffineTransform) crop.getGridGeometry().getGridToCRS(PixelInCell.CELL_CORNER))
            .inverse();

    // 2) Extract the BufferedImage from each image
    image = crop.getRenderedImage();

    Rectangle rectIMG =
        new Rectangle(image.getMinX(), image.getMinY(), image.getWidth(), image.getHeight());
    ImageWorker w = new ImageWorker(image);
    BufferedImage buf = w.getBufferedImage();
    if (image instanceof RenderedOp) {
      ((RenderedOp) image).dispose();
    }

    // 3) Generate an array of data from each image
    Raster data = buf.getData();
    final DataBufferByte db = (DataBufferByte) data.getDataBuffer();
    byte[] byteData = db.getData();

    if (reference) {
      // 4) Transform the Geometry to Raster space
      Geometry rs = JTS.transform(geo, transform);
      Geometry rsFilter = JTS.transform(geo.difference(originalGeo), transform);
      ROI roiGeo = new ROIGeometry(rs);
      ROI roiFilter = new ROIGeometry(rsFilter);

      // 5) Extract an array of data from the transformed ROI
      byte[] roiData = getROIData((buffer > 0 ? roiFilter : roiGeo), rectIMG);
      bean.setRoi(roiData);
      bean.setRoiObj(roiGeo);

      // 6) Setting the Coverage data array
      bean.setReferenceImage(byteData);

      // 7) Setting the Image dimensions
      bean.setHeight(rectIMG.height);
      bean.setWidth(rectIMG.width);
      bean.setMinX(rectIMG.x);
      bean.setMinY(rectIMG.y);
    } else {
      // 6) Setting the Coverage data array
      bean.setCurrentImage(byteData);
    }

    // 7) Store the Reference Covergae containing the geospatial info
    bean.setReferenceCoverage(coverage);
  }
  // same as SubsampleBinaryToGray, and change byteLoop to protected in superclass?
  // extends that and save this? using prote
  private void byteLoop(Raster source, WritableRaster dest, Rectangle destRect) {
    PixelAccessor pa = new PixelAccessor(source.getSampleModel(), null);
    PackedImageData pid = pa.getPackedPixels(source, source.getBounds(), false, false);
    byte[] sourceData = pid.data;
    int sourceDBOffset = pid.offset;
    int dx = destRect.x;
    int dy = destRect.y;
    int dwi = destRect.width;
    int dhi = destRect.height;
    int sourceTransX = pid.rect.x; // source.getSampleModelTranslateX();
    int sourceTransY = pid.rect.y; // source.getSampleModelTranslateY();
    int sourceDataBitOffset = pid.bitOffset;
    int sourceScanlineStride = pid.lineStride;

    PixelInterleavedSampleModel destSM = (PixelInterleavedSampleModel) dest.getSampleModel();
    DataBufferByte destDB = (DataBufferByte) dest.getDataBuffer();
    int destTransX = dest.getSampleModelTranslateX();
    int destTransY = dest.getSampleModelTranslateY();
    int destScanlineStride = destSM.getScanlineStride();

    byte[] destData = destDB.getData();
    int destDBOffset = destDB.getOffset();

    int[] sbytenum = new int[dwi];
    int[] sstartbit = new int[dwi];
    int[] sAreaBitsOn = new int[dwi];
    for (int i = 0; i < dwi; i++) {
      int x = xValues[dx + i];
      int sbitnum = sourceDataBitOffset + (x - sourceTransX);
      sbytenum[i] = sbitnum >> 3;
      sstartbit[i] = sbitnum % 8;
    }

    for (int j = 0; j < dhi; j++) {

      for (int i = 0; i < dwi; i++) {
        sAreaBitsOn[i] = 0;
      }

      for (int y = yValues[dy + j]; y < yValues[dy + j] + blockY; y++) {

        int sourceYOffset = (y - sourceTransY) * sourceScanlineStride + sourceDBOffset;

        int delement, selement, sendbiti, sendbytenumi;
        for (int i = 0; i < dwi; i++) {
          delement = 0;
          sendbiti = sstartbit[i] + blockX - 1;
          sendbytenumi = sbytenum[i] + (sendbiti >> 3); // byte num of the end bit
          sendbiti %= 8; // true src end bit position
          selement = 0x00ff & (int) sourceData[sourceYOffset + sbytenum[i]];

          int swingBits = 24 + sstartbit[i];
          if (sbytenum[i] == sendbytenumi) {
            // selement  <<= 24 + sstartbit[i];
            selement <<= swingBits;
            selement >>>= 31 - sendbiti + sstartbit[i];
            delement += lut[selement];
          } else {
            selement <<= swingBits;
            selement >>>= swingBits;
            // selement >>>= 24;

            delement += lut[selement];
            for (int b = sbytenum[i] + 1; b < sendbytenumi; b++) {
              selement = 0x00ff & (int) sourceData[sourceYOffset + b];
              delement += lut[selement];
            }
            selement = 0x00ff & (int) sourceData[sourceYOffset + sendbytenumi];
            selement >>>= 7 - sendbiti;
            delement += lut[selement];
          }
          sAreaBitsOn[i] += delement;
        }
      }
      int destYOffset = (j + dy - destTransY) * destScanlineStride + destDBOffset;

      destYOffset += dx - destTransX;

      // update dest values for row j in raster

      for (int i = 0; i < dwi; i++) {
        destData[destYOffset + i] = lutGray[sAreaBitsOn[i]];
      }
    }
  }
Пример #18
0
 public static byte[] image_byte_data(BufferedImage image) {
   WritableRaster raster = image.getRaster();
   DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
   return buffer.getData();
 }
Пример #19
0
  public ByteImage(BufferedImage inputImage, HashMap<String, Number> options) {
    scale = options.get("scale").intValue();
    nscales = options.get("nscales").intValue();
    scales_mode = options.get("scales_mode").intValue();
    cvar = options.get("cvar").doubleValue();
    alpha = options.get("alpha").floatValue();
    gain = options.get("gain").floatValue();
    offset = options.get("offset").floatValue();
    lowmem = options.get("lowmem").intValue() == 1;
    useNative = options.get("native").intValue() == 1;

    System.out.println("native:\t" + useNative);

    retinex_scales_distribution();
    width = inputImage.getWidth();
    height = inputImage.getHeight();
    channelSize = width * height;
    dest = new float[width * height * 3];
    // inRaw = new float[width*height*3];
    for (int i = 0; i < dest.length; i++) {
      dest[i] = 0;
      // inRaw[i] = 0;
    }

    // System.out.println("Width\t"+width+"\tHeight\t"+height);

    Raster inRaster = inputImage.getRaster();

    DataBufferByte dbIn = (DataBufferByte) inRaster.getDataBuffer();

    original = dbIn.getData();

    /*/for(int i = 0;i<100;i++)
        System.out.print(original[i]+"\t");
    System.out.println();*/

    hasAlpha = (width * height * 4 == original.length);
    // System.out.println(original.length+"\t"+hasAlpha);

    weight = (float) 1.0 / nscales;
    Worker[] workers = new Worker[3];
    for (int channel = 0; channel < 3; channel++) {
      if (useNative) {
        workers[channel] = new NativeWorker(channel);
      } else {
        workers[channel] = new Worker(channel);
      }
      workers[channel].start();
      if (lowmem) {
        try {
          workers[channel].join();
        } catch (InterruptedException ex) {
          Logger.getLogger(ByteImage.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
    if (!lowmem) {
      for (int i = 0; i < 3; i++) {
        try {
          workers[i].join();
        } catch (InterruptedException ex) {
          Logger.getLogger(ByteImage.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
    // recordDest("-afterworker");

    Thread[] gainers = new Thread[3];

    for (int i = 0; i < 3; i++) {
      if (useNative) {
        gainers[i] = new NativeGainer(i);
      } else {
        gainers[i] = new Gainer(i);
      }

      gainers[i].start();
    }

    try {
      for (int i = 0; i < 3; i++) {
        gainers[i].join();
      }
    } catch (InterruptedException ex) {
      Logger.getLogger(ByteImage.class.getName()).log(Level.SEVERE, null, ex);
    }

    // recordDest("-aftergain");

    mean = 0;
    vsquared = 0;

    meanRaw = new float[3];
    vsquaredRaw = new float[3];
    meanRaw[0] = vsquaredRaw[0] = 0;
    meanRaw[1] = vsquaredRaw[1] = 0;
    meanRaw[2] = vsquaredRaw[2] = 0;
    Thread[] summers = new Thread[3];
    for (int i = 0; i < 3; i++) {
      summers[i] = new Summer(i);
      summers[i].start();
    }

    try {
      for (int i = 0; i < 3; i++) {
        summers[i].join();
      }
    } catch (InterruptedException ex) {
      Logger.getLogger(ByteImage.class.getName()).log(Level.SEVERE, null, ex);
    }

    mean = meanRaw[0] + meanRaw[1] + meanRaw[2];
    vsquared = vsquaredRaw[0] + vsquaredRaw[1] + vsquaredRaw[2];

    mean /= dest.length;
    vsquared /= dest.length;

    float var = (vsquared - (mean * mean));
    var = (float) Math.sqrt(var);

    mini = (float) (mean - cvar * var);
    maxi = (float) (mean + cvar * var);
    range = maxi - mini;

    System.out.println("range:\t" + range);
    System.out.println("var:\t" + var);
    System.out.println("mean:\t" + mean);
    System.out.println("vsquared\t" + vsquared);
    System.out.println("cvar\t" + cvar);

    Thread[] last = new Thread[3];
    for (int i = 0; i < 3; i++) {
      last[i] = new Pixeler(i);
      last[i].start();
      /*try {
          last[i].join();
      } catch (InterruptedException ex) {
          Logger.getLogger(ByteImage.class.getName()).log(Level.SEVERE, null, ex);
      }*/
    }

    // System.out.println("before");

    try {
      for (int i = 0; i < 3; i++) last[i].join();
    } catch (InterruptedException ex) {
      Logger.getLogger(ByteImage.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (int i = 0; i < 100; i++) System.out.print(original[i] + "\t");
    System.out.println();
    /* try {
        bw.close();
    } catch (IOException ex) {
        Logger.getLogger(ByteImage.class.getName()).log(Level.SEVERE, null, ex);
    }*/
  }
 /**
  * Decompress the JPEG source image associated with this decompressor instance and output a
  * decompressed image to the given <code>BufferedImage</code> instance.
  *
  * @param dstImage a <code>BufferedImage</code> instance that will receive the decompressed image
  * @param flags the bitwise OR of one or more of {@link TJ TJ.FLAG_*}
  */
 public void decompress(BufferedImage dstImage, int flags) throws Exception {
   if (dstImage == null || flags < 0) throw new Exception("Invalid argument in decompress()");
   int desiredWidth = dstImage.getWidth();
   int desiredHeight = dstImage.getHeight();
   int scaledWidth = getScaledWidth(desiredWidth, desiredHeight);
   int scaledHeight = getScaledHeight(desiredWidth, desiredHeight);
   if (scaledWidth != desiredWidth || scaledHeight != desiredHeight)
     throw new Exception(
         "BufferedImage dimensions do not match a scaled image size that TurboJPEG is capable of generating.");
   int pixelFormat;
   boolean intPixels = false;
   if (byteOrder == null) byteOrder = ByteOrder.nativeOrder();
   switch (dstImage.getType()) {
     case BufferedImage.TYPE_3BYTE_BGR:
       pixelFormat = TJ.PF_BGR;
       break;
     case BufferedImage.TYPE_4BYTE_ABGR:
     case BufferedImage.TYPE_4BYTE_ABGR_PRE:
       pixelFormat = TJ.PF_XBGR;
       break;
     case BufferedImage.TYPE_BYTE_GRAY:
       pixelFormat = TJ.PF_GRAY;
       break;
     case BufferedImage.TYPE_INT_BGR:
       if (byteOrder == ByteOrder.BIG_ENDIAN) pixelFormat = TJ.PF_XBGR;
       else pixelFormat = TJ.PF_RGBX;
       intPixels = true;
       break;
     case BufferedImage.TYPE_INT_RGB:
       if (byteOrder == ByteOrder.BIG_ENDIAN) pixelFormat = TJ.PF_XRGB;
       else pixelFormat = TJ.PF_BGRX;
       intPixels = true;
       break;
     case BufferedImage.TYPE_INT_ARGB:
     case BufferedImage.TYPE_INT_ARGB_PRE:
       if (byteOrder == ByteOrder.BIG_ENDIAN) pixelFormat = TJ.PF_ARGB;
       else pixelFormat = TJ.PF_BGRA;
       intPixels = true;
       break;
     default:
       throw new Exception("Unsupported BufferedImage format");
   }
   WritableRaster wr = dstImage.getRaster();
   if (intPixels) {
     SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) dstImage.getSampleModel();
     int stride = sm.getScanlineStride();
     DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
     int[] buf = db.getData();
     if (jpegBuf == null) throw new Exception(NO_ASSOC_ERROR);
     decompress(jpegBuf, jpegBufSize, buf, scaledWidth, stride, scaledHeight, pixelFormat, flags);
   } else {
     ComponentSampleModel sm = (ComponentSampleModel) dstImage.getSampleModel();
     int pixelSize = sm.getPixelStride();
     if (pixelSize != TJ.getPixelSize(pixelFormat))
       throw new Exception("Inconsistency between pixel format and pixel size in BufferedImage");
     int pitch = sm.getScanlineStride();
     DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
     byte[] buf = db.getData();
     decompress(buf, scaledWidth, pitch, scaledHeight, pixelFormat, flags);
   }
 }
Пример #21
0
 public String calculateHash(BufferedImage image) {
   WritableRaster raster = image.getRaster();
   DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
   messageDigest.update(buffer.getData());
   return new BigInteger(1, messageDigest.digest()).toString(16);
 }