/** Superclass getRaster... */
  public final Raster getRaster(int x, int y, int w, int h) {
    if (w == 0 || h == 0) {
      return null;
    }

    //
    // If working raster is big enough, reuse it. Otherwise,
    // build a large enough new one.
    //
    WritableRaster raster = saved;
    if (raster == null || raster.getWidth() < w || raster.getHeight() < h) {
      raster = getCachedRaster(dataModel, w, h);
      saved = raster;
    }

    // Access raster internal int array. Because we use a DirectColorModel,
    // we know the DataBuffer is of type DataBufferInt and the SampleModel
    // is SinglePixelPackedSampleModel.
    // Adjust for initial offset in DataBuffer and also for the scanline
    // stride.
    //
    DataBufferInt rasterDB = (DataBufferInt) raster.getDataBuffer();
    int[] pixels = rasterDB.getBankData()[0];
    int off = rasterDB.getOffset();
    int scanlineStride =
        ((SinglePixelPackedSampleModel) raster.getSampleModel()).getScanlineStride();
    int adjust = scanlineStride - w;

    fillRaster(pixels, off, adjust, x, y, w, h); // delegate to subclass.

    GraphicsUtil.coerceData(raster, dataModel, model.isAlphaPremultiplied());

    return raster;
  }
 /**
  * internal use - get buffer from image
  *
  * @param scaledImage
  * @param deviceXSize
  * @param deviceYSize
  * @return
  */
 private static int[] getPixelsFromImage(
     BufferedImage scaledImage, int deviceXSize, int deviceYSize) {
   // painfull slow!
   // return scaledImage.getRGB(0, 0, deviceXSize, deviceYSize, null, 0, deviceXSize);
   DataBufferInt buf = (DataBufferInt) scaledImage.getRaster().getDataBuffer();
   return buf.getData();
 }
示例#3
0
  private boolean newImage(BufferedImage tmpImage) {
    Boolean iguales = true;
    // Si es la primer imagen
    if (lastBufferedImage == null) {
      // Devuelvo true
      return true;
    }

    // Obtengo los buffers de las imágenes
    DataBuffer newImageDataBuffer = tmpImage.getRaster().getDataBuffer();
    DataBuffer lastImageDataBuffer = lastBufferedImage.getRaster().getDataBuffer();

    // Obtengo los tipos de los buffers.
    DataBufferInt newImageDBAsDBInt = (DataBufferInt) newImageDataBuffer;
    DataBufferInt lastImageDBAsDBInt = (DataBufferInt) lastImageDataBuffer;

    // Armo arreglos de ints con la información de los buffers
    for (int bank = 0; bank < newImageDBAsDBInt.getNumBanks(); bank++) {
      int[] nueva = newImageDBAsDBInt.getData(bank);
      int[] anterior = lastImageDBAsDBInt.getData(bank);

      // si la información es la misma
      if (Arrays.equals(nueva, anterior) == true) {
        // las imágenes son iguales y devuelvo false ya que NO debo enviarla
        iguales = false;
      }
    }
    // Si las imágenes son distintas, devuelvo true ya que debo enviarla.
    return iguales;
  }
示例#4
0
  public BufferedImage renderFullImage() {
    int scrollX = (int) (getScrollPosition(Orientation.HORIZONTAL) / scale);
    int scrollY = (int) (getScrollPosition(Orientation.VERTICAL) / scale);

    int minChunkX = heightMap.getMinX() + scrollX / 16,
        minChunkZ = heightMap.getMinZ() + scrollY / 16,
        maxChunkX = 0,
        maxChunkZ = 0;
    int horiz = (int) (getWidth() / 16 / scale) + 1;
    int vert = (int) (getHeight() / 16 / scale) + 1;
    maxChunkX = minChunkX + horiz;
    maxChunkZ = minChunkZ + vert;

    minChunkX++;
    minChunkZ++;
    BufferedImage fullImage =
        new BufferedImage(
            (maxChunkX - minChunkX) * 16 + 32,
            (maxChunkZ - minChunkZ) * 16 + 32,
            BufferedImage.TYPE_INT_ARGB);
    for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) {
      for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) {
        Map map = drawChunk(chunkX, chunkZ, dirty);
        if (map != null && map != blankMap) {
          Raster raster = map.getColorRaster();
          int startX = (chunkX - minChunkX) * 16;
          int startZ = (chunkZ - minChunkZ) * 16;
          java.awt.image.DataBufferInt buf = (java.awt.image.DataBufferInt) raster.getDataBuffer();
          int[] srcbuf = buf.getData();
          fullImage.setRGB(startX, startZ, 16, 16, srcbuf, 0, 16);
        }
      }
    }
    return fullImage;
  }
示例#5
0
  public static void main(String[] args)
      throws DocumentException, MalformedURLException, IOException {

    BufferedImage image = ImageIO.read(imageFile);

    BufferedImage bi =
        new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    ColorConvertOp xformOp = new ColorConvertOp(null);
    xformOp.filter(image, bi);

    // bi.setData(icon.getData());

    WritableRaster raster = bi.getRaster();
    DataBufferInt data = (DataBufferInt) raster.getDataBuffer();

    int[] intData = data.getData();

    ByteBuffer byteBuffer = ByteBuffer.allocate(intData.length * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    intBuffer.put(intData);

    byte[] array = byteBuffer.array();

    System.out.println(Hex.encodeHex(array));
  }
示例#6
0
  protected static void mult_INT_PACK_Data(WritableRaster wr) {
    // System.out.println("Multiply Int: " + wr);

    SinglePixelPackedSampleModel sppsm;
    sppsm = (SinglePixelPackedSampleModel) wr.getSampleModel();

    final int width = wr.getWidth();

    final int scanStride = sppsm.getScanlineStride();
    DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
    final int base =
        (db.getOffset()
            + sppsm.getOffset(
                wr.getMinX() - wr.getSampleModelTranslateX(),
                wr.getMinY() - wr.getSampleModelTranslateY()));
    // Access the pixel data array
    final int pixels[] = db.getBankData()[0];
    for (int y = 0; y < wr.getHeight(); y++) {
      int sp = base + y * scanStride;
      final int end = sp + width;
      while (sp < end) {
        int pixel = pixels[sp];
        int a = pixel >>> 24;
        if ((a >= 0) && (a < 255)) {
          pixels[sp] =
              ((a << 24)
                  | ((((pixel & 0xFF0000) * a) >> 8) & 0xFF0000)
                  | ((((pixel & 0x00FF00) * a) >> 8) & 0x00FF00)
                  | ((((pixel & 0x0000FF) * a) >> 8) & 0x0000FF));
        }
        sp++;
      }
    }
  }
示例#7
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);
 }
示例#8
0
 @Override
 public int getRGB(int x, int y) {
   try {
     WritableRaster r = image.getRaster();
     DataBufferInt b = (DataBufferInt) r.getDataBuffer();
     int[] d = b.getData();
     return d[this.width * (y - this.y) + (x - this.x)];
   } catch (Exception e) {
     return image.getRGB(x - this.x, y - this.y);
   }
 }
  private void writeDataBufferInt(DataOutput out, DataBufferInt buffer) throws IOException {
    int[][] data = buffer.getBankData();
    out.writeInt(data.length);
    for (int i = 0; i < data.length; i++) {
      out.writeInt(data[i].length);
      for (int j = 0; j < data[i].length; j++) out.writeInt(data[i][j]);
    }

    out.writeInt(buffer.getSize());

    // TODO Handle DataBufferInt offsets

  }
示例#10
0
 private static BufferedImage createAlphaBackground(int width, int height) {
   BufferedImage background = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
   DataBufferInt dataBuffer = (DataBufferInt) background.getRaster().getDataBuffer();
   int[] data = dataBuffer.getData();
   int gray = Color.LIGHT_GRAY.getRGB();
   int white = Color.WHITE.getRGB();
   for (int i = 0; i < data.length; i++) {
     int x = i % width;
     int y = i / width;
     data[i] = ((x / 4) % 2 == (y / 4) % 2) ? gray : white;
   }
   return background;
 }
示例#11
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());
    }
  }
  /**
   * Constructs a IntegerComponentRaster with the given SampleModel, DataBuffer, and parent.
   * DataBuffer must be a DataBufferInt and SampleModel must be of type
   * SinglePixelPackedSampleModel. When translated into the base Raster's coordinate system, aRegion
   * must be contained by the base Raster. Origin is the coodinate 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 DataBufferInt 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 IntegerComponentRaster(
      SampleModel sampleModel,
      DataBuffer dataBuffer,
      Rectangle aRegion,
      Point origin,
      IntegerComponentRaster parent) {
    super(sampleModel, dataBuffer, aRegion, origin, parent);
    this.maxX = minX + width;
    this.maxY = minY + height;
    if (!(dataBuffer instanceof DataBufferInt)) {
      throw new RasterFormatException("IntegerComponentRasters must have" + "integer DataBuffers");
    }
    DataBufferInt dbi = (DataBufferInt) dataBuffer;
    if (dbi.getNumBanks() != 1) {
      throw new RasterFormatException(
          "DataBuffer for IntegerComponentRasters" + " must only have 1 bank.");
    }
    this.data = stealData(dbi, 0);

    if (sampleModel instanceof SinglePixelPackedSampleModel) {
      SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sampleModel;
      int[] boffsets = sppsm.getBitOffsets();
      boolean notByteBoundary = false;
      for (int i = 1; i < boffsets.length; i++) {
        if ((boffsets[i] % 8) != 0) {
          notByteBoundary = true;
        }
      }
      this.type =
          (notByteBoundary
              ? IntegerComponentRaster.TYPE_INT_PACKED_SAMPLES
              : IntegerComponentRaster.TYPE_INT_8BIT_SAMPLES);

      this.scanlineStride = sppsm.getScanlineStride();
      this.pixelStride = 1;
      this.dataOffsets = new int[1];
      this.dataOffsets[0] = dbi.getOffset();
      this.bandOffset = this.dataOffsets[0];
      int xOffset = aRegion.x - origin.x;
      int yOffset = aRegion.y - origin.y;
      dataOffsets[0] += xOffset + yOffset * scanlineStride;
      this.numDataElems = sppsm.getNumDataElements();
    } else {
      throw new RasterFormatException(
          "IntegerComponentRasters must have" + " SinglePixelPackedSampleModel");
    }

    verify();
  }
  /**
   * Creates a new Scale2x object. The new object will scale images of the specified size to images
   * that are twice as large.<br>
   *
   * @param width The width of the images to be scaled
   * @param height The height of the images to be scaled
   */
  public Scale2x(int width, int height) {
    this.width = width;
    this.height = height;

    // A border of one pixel in each direction, and one down, to avoid if statements in the scale
    // loop
    sourceImage = new BufferedImage(width + 2, height + 3, BufferedImage.TYPE_INT_RGB);
    DataBufferInt sourceDataBuffer = (DataBufferInt) sourceImage.getRaster().getDataBuffer();
    sourcePixels = sourceDataBuffer.getData();
    sourceGraphics = sourceImage.getGraphics();

    targetImage = new BufferedImage(width * 2, height * 2, BufferedImage.TYPE_INT_RGB);
    DataBufferInt targetDataBuffer = (DataBufferInt) targetImage.getRaster().getDataBuffer();
    targetPixels = targetDataBuffer.getData();
  }
示例#14
0
 public void updateIconImages() {
   java.util.List<Image> imageList = ((Window) target).getIconImages();
   if (imageList == null || imageList.size() == 0) {
     setIconImagesData(null, 0, 0, null, 0, 0);
   } else {
     int w = getSysIconWidth();
     int h = getSysIconHeight();
     int smw = getSysSmIconWidth();
     int smh = getSysSmIconHeight();
     DataBufferInt iconData = SunToolkit.getScaledIconData(imageList, w, h);
     DataBufferInt iconSmData = SunToolkit.getScaledIconData(imageList, smw, smh);
     if (iconData != null && iconSmData != null) {
       setIconImagesData(iconData.getData(), w, h, iconSmData.getData(), smw, smh);
     } else {
       setIconImagesData(null, 0, 0, null, 0, 0);
     }
   }
 }
示例#15
0
 @Override
 public int[] getRGB(int x, int y, int width, int height, int[] rgb, int offset, int rowCount) {
   try {
     WritableRaster r = image.getRaster();
     DataBufferInt b = (DataBufferInt) r.getDataBuffer();
     int[] d = b.getData();
     if (rgb == null) rgb = new int[offset + rowCount * height];
     for (int sy = this.width * (y - this.y) + (x - this.x), dy = offset, iy = 0;
         iy < height;
         sy += this.width, dy += rowCount, iy++) {
       for (int sx = sy, dx = dy, ix = 0; ix < width; sx++, dx++, ix++) {
         rgb[dx] = d[sx];
       }
     }
     return rgb;
   } catch (Exception e) {
     return image.getRGB(x - this.x, y - this.y, width, height, rgb, offset, rowCount);
   }
 }
示例#16
0
    public ZeroRecter_INT_PACK(WritableRaster wr) {
      super(wr);

      SinglePixelPackedSampleModel sppsm;
      sppsm = (SinglePixelPackedSampleModel) wr.getSampleModel();

      scanStride = sppsm.getScanlineStride();
      DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
      x0 = wr.getMinY();
      y0 = wr.getMinX();
      base =
          (db.getOffset()
              + sppsm.getOffset(
                  x0 - wr.getSampleModelTranslateX(), y0 - wr.getSampleModelTranslateY()));

      pixels = db.getBankData()[0];
      if (wr.getWidth() > 10) zeros = new int[wr.getWidth()];
      else zeros = null;
    }
示例#17
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);
   }
 }
示例#18
0
  protected static void divide_INT_PACK_Data(WritableRaster wr) {
    // System.out.println("Divide Int");

    SinglePixelPackedSampleModel sppsm;
    sppsm = (SinglePixelPackedSampleModel) wr.getSampleModel();

    final int width = wr.getWidth();

    final int scanStride = sppsm.getScanlineStride();
    DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
    final int base =
        (db.getOffset()
            + sppsm.getOffset(
                wr.getMinX() - wr.getSampleModelTranslateX(),
                wr.getMinY() - wr.getSampleModelTranslateY()));
    int pixel, a, aFP;
    // Access the pixel data array
    final int pixels[] = db.getBankData()[0];
    for (int y = 0; y < wr.getHeight(); y++) {
      int sp = base + y * scanStride;
      final int end = sp + width;
      while (sp < end) {
        pixel = pixels[sp];
        a = pixel >>> 24;
        if (a <= 0) {
          pixels[sp] = 0x00FFFFFF;
        } else if (a < 255) {
          aFP = (0x00FF0000 / a);
          pixels[sp] =
              ((a << 24)
                  | (((((pixel & 0xFF0000) >> 16) * aFP) & 0xFF0000))
                  | (((((pixel & 0x00FF00) >> 8) * aFP) & 0xFF0000) >> 8)
                  | (((((pixel & 0x0000FF)) * aFP) & 0xFF0000) >> 16));
        }
        sp++;
      }
    }
  }
 /*     */ public final Raster getRaster(
     int paramInt1, int paramInt2, int paramInt3, int paramInt4)
       /*     */ {
   /* 618 */ Raster localRaster = this.saved;
   /* 619 */ if ((localRaster == null)
       || (localRaster.getWidth() < paramInt3)
       || (localRaster.getHeight() < paramInt4))
   /*     */ {
     /* 622 */ localRaster = getCachedRaster(this.model, paramInt3, paramInt4);
     /* 623 */ this.saved = localRaster;
     /*     */ }
   /*     */
   /* 633 */ DataBufferInt localDataBufferInt = (DataBufferInt) localRaster.getDataBuffer();
   /* 634 */ int[] arrayOfInt = localDataBufferInt.getData(0);
   /* 635 */ int i = localDataBufferInt.getOffset();
   /* 636 */ int j =
       ((SinglePixelPackedSampleModel) localRaster.getSampleModel()).getScanlineStride();
   /*     */
   /* 638 */ int k = j - paramInt3;
   /*     */
   /* 640 */ fillRaster(arrayOfInt, i, k, paramInt1, paramInt2, paramInt3, paramInt4);
   /*     */
   /* 642 */ return localRaster;
   /*     */ }
 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;
 }
 /**
  * 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);
   }
 }
示例#22
0
 public static int[] getBank(BufferedImage img) {
   WritableRaster imgRaster = img.getRaster();
   DataBufferInt dbuf = (DataBufferInt) imgRaster.getDataBuffer();
   return dbuf.getData(0);
 }
示例#23
0
  private void createView() {

    int scale = getScaleModeScale(scaleMode);

    if (!useHWScaling(scaleMode)) {

      // Create new BufferedImage with scaled width & height:
      img = new BufferedImage(width * scale, height * scale, BufferedImage.TYPE_INT_RGB);

    } else {

      // Create new BufferedImage with normal width & height:
      img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

      // Create graphics object to use for FPS display:
      gfx = img.createGraphics();
      gfx.setFont(fpsFont);

      // Set rendering hints:
      Graphics2D g2d = (Graphics2D) gfx;
      g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

      try {

        // Create hardware accellerated image:
        vimg = createVolatileImage(width, height, new ImageCapabilities(true));

      } catch (Exception e) {

        // Unable to create image. Fall back to software scaling:
        // System.out.println("Unable to create HW accellerated image.");
        scaleMode = SCALE_NORMAL;
        img = new BufferedImage(width * scale, height * scale, BufferedImage.TYPE_INT_RGB);
      }
    }

    // Create graphics object to use for FPS display:
    gfx = img.createGraphics();
    gfx.setFont(fpsFont);

    // Set rendering hints:
    Graphics2D g2d = (Graphics2D) gfx;
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    // Retrieve raster from image:
    DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer();
    int[] raster = dbi.getData();

    // Replace current rasters with the one used by the image:
    if (scaleMode == SCALE_NONE || scaleMode == SCALE_HW2X || scaleMode == SCALE_HW3X) {

      pix = raster;
      nes.ppu.buffer = raster;

    } else {

      pix_scaled = raster;
    }

    // Set background color:
    for (int i = 0; i < raster.length; i++) {
      raster[i] = bgColor;
    }

    // Set component size & bounds:
    setSize(width * scale, height * scale);
    setBounds(getX(), getY(), width * scale, height * scale);

    // Repaint component:
    this.invalidate();
    repaint();
  }
  /**
   * <code>createTexture</code> takes the current height map and the current loaded textures and
   * produces an <code>ImageIcon</code> which can be retrieved with a call to <code>getImageIcon
   * </code>.
   */
  public void createTexture(int textureSize) {
    BufferedImage img = new BufferedImage(textureSize, textureSize, BufferedImage.TYPE_INT_RGB);
    DataBufferInt data = (DataBufferInt) img.getRaster().getDataBuffer();
    int[] pixels = data.getData();

    // tempvalues for the color
    int red = 0;
    int green = 0;
    int blue = 0;

    int tlSize = textureList.size();
    int twidths[] = new int[tlSize];
    int theights[] = new int[tlSize];
    for (int i = 0; i < tlSize; i++) {
      BufferedImage tempImg = textureList.get(i).imageData;
      twidths[i] = tempImg.getWidth();
      theights[i] = tempImg.getHeight();
    }

    int scaledX;
    int scaledZ;

    float mapRatio = (float) size / (float) textureSize;

    // check each pixel of the heightmap
    BufferedImage tempImg;
    float scalar;
    for (int x = 0; x < textureSize; x++) {
      for (int z = 0; z < textureSize; z++) {
        // combine every texture for this pixel
        for (int i = 0; i < tlSize; i++) {
          tempImg = textureList.get(i).imageData;
          data = (DataBufferInt) tempImg.getRaster().getDataBuffer();
          pixels = data.getData();

          // We may have to tile the texture if the terrain is
          // larger than the texture.
          scaledX = x % twidths[i];
          scaledZ = z % theights[i];

          // Retrieve the amount of the color to use for this
          // texture.
          scalar = getTextureScale(interpolateHeight(x, z, mapRatio), i);
          red += scalar * ((pixels[scaledZ * twidths[i] + scaledX] & 0x00FF0000) >> 16);
          green += scalar * ((pixels[scaledZ * twidths[i] + scaledX] & 0x0000FF00) >> 8);
          blue += scalar * ((pixels[scaledZ * twidths[i] + scaledX] & 0x000000FF));
        }

        // set the color for the final texture.
        int rgb = red << 16 | green << 8 | blue;
        img.setRGB(x, textureSize - (z + 1), rgb);

        red = 0;
        green = 0;
        blue = 0;
      }
    }

    // create the new image from the data.
    proceduralTexture = new ImageIcon(img);
    proceduralTexture.setDescription("TerrainTexture");

    logger.fine("Created procedural texture successfully.");
  }
示例#25
0
 public void attachBuffer(int type, BufferedImage img) {
   DataBufferInt db = (DataBufferInt) img.getRaster().getDataBuffer();
   int stride =
       ((SinglePixelPackedSampleModel) img.getRaster().getSampleModel()).getScanlineStride();
   attachBuffer(type, db.getData(), db.getOffset(), stride);
 }
示例#26
0
  /**
   * Paint the Canvas in an Image
   *
   * @param g
   * @param buffer
   * @param width
   * @param height
   */
  public final void paint(Graphics2D g, int width, int height) {
    if (highQuality) {
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
      g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
    }
    background = Color.black;
    String stereo = getStereoMode();

    if ("parallel".equals(stereo)) {
      final double d = 3 * Math.PI / 180;
      visualizer3D.rotate(-d, 0);
      visualizer3D.setScreenDimension(width / 2, height);
      g.setClip(0, 0, width / 2, height);
      paintShapes(g);
      visualizer3D.rotate(d, 0);

      visualizer3D.rotate(d, 0);
      visualizer3D.setScreenDimension(width / 2, height);
      g.setClip(width / 2, 0, width / 2, height);
      g.translate(width / 2, 0);
      paintShapes(g);
      g.translate(-width / 2, 0);
      g.setClip(null);
      visualizer3D.rotate(-d, 0);

    } else if ("interlaced".equals(stereo)) {
      background = new Color(100, 100, 150);
      // Point p = getLocationOnScreen();
      boolean even = true; // p.x%2==0;
      // Creates buffer
      BufferedImage buf = new BufferedImage(width * 2, height, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = (Graphics2D) buf.getGraphics();
      final double d = 1.8 * Math.PI / 180;
      final double t = -100000000;
      visualizer3D.getCenterOfRotation().z += t;
      visualizer3D.rotate(-d, 0);
      visualizer3D.getCenterOfRotation().z -= t;
      visualizer3D.setScreenDimension(width, height);
      paintShapes(g2);
      visualizer3D.getCenterOfRotation().z += t;
      visualizer3D.rotate(d, 0);
      visualizer3D.getCenterOfRotation().z -= t;
      visualizer3D.getCenterOfRotation().z += t;
      visualizer3D.rotate(d, 0);
      visualizer3D.getCenterOfRotation().z -= t;
      visualizer3D.setScreenDimension(width, height);
      g2.translate(width, 0);
      paintShapes(g2);
      g2.translate(-width, 0);
      visualizer3D.getCenterOfRotation().z += t;
      visualizer3D.rotate(-d, 0);
      visualizer3D.getCenterOfRotation().z -= t;
      g2.dispose();

      // Interlace in g
      int width2 = 2 * width;
      // int[] rgb = (int[]) buf.getRaster().getDataElements(0, 0, width2, height, new
      // int[width2*height]);
      DataBufferInt b = (DataBufferInt) buf.getRaster().getDataBuffer();
      int[] rgb = b.getData();
      // System.out.println(b.);
      // int[] rgb = (int[]) .;
      // buf.getRGB(0, 0, width2, height, rgb, 0, width2);
      final int dev = 5;
      for (int x = 0; x + 1 < width - dev; x += 2) {
        {
          int i = x, j = x;
          for (int y = 0; y < height; y++) {
            rgb[i] = ((rgb[j] & 0xFEFEFEFE) >> 1) + ((rgb[j + 1] & 0xFEFEFEFE) >> 1);
            i += width2;
            j += width2;
          }
        }
        {
          int i = x + 1, j = width + x + dev;
          for (int y = 0; y < height; y++) {
            rgb[i] = ((rgb[j] & 0xFEFEFEFE) >> 1) + ((rgb[j + 1] & 0xFEFEFEFE) >> 1);
            i += width2;
            j += width2;
          }
        }
      }
      // Arrays.fill(rgb, 0xFF);
      // buf.getRaster().setDataElements(0, 0, width2, height, rgb);
      // buf.setRGB(0, 0, width2, height, rgb, 0, width2);

      g.drawImage(buf, even ? 0 : 1, 0, width, height, 0, 0, width - (even ? 0 : 1), height, this);
    } else {
      visualizer3D.setScreenDimension(width, height);
      paintShapes(g);
    }
  }
示例#27
0
  private WritableRaster boxFilterV(
      Raster src, WritableRaster dest, int skipX, int skipY, int boxSz, int loc) {

    final int w = src.getWidth();
    final int h = src.getHeight();

    // Check if the raster is wide enough to do _any_ work
    if (w < (2 * skipX)) return dest;
    if (h < (2 * skipY) + boxSz) return dest;

    final SinglePixelPackedSampleModel srcSPPSM =
        (SinglePixelPackedSampleModel) src.getSampleModel();

    final SinglePixelPackedSampleModel dstSPPSM =
        (SinglePixelPackedSampleModel) dest.getSampleModel();

    // Stride is the distance between two consecutive column elements,
    // in the one-dimention dataBuffer
    final int srcScanStride = srcSPPSM.getScanlineStride();
    final int dstScanStride = dstSPPSM.getScanlineStride();

    // Access the integer buffer for each image.
    DataBufferInt srcDB = (DataBufferInt) src.getDataBuffer();
    DataBufferInt dstDB = (DataBufferInt) dest.getDataBuffer();

    // Offset defines where in the stack the real data begin
    final int srcOff =
        (srcDB.getOffset()
            + srcSPPSM.getOffset(
                src.getMinX() - src.getSampleModelTranslateX(),
                src.getMinY() - src.getSampleModelTranslateY()));
    final int dstOff =
        (dstDB.getOffset()
            + dstSPPSM.getOffset(
                dest.getMinX() - dest.getSampleModelTranslateX(),
                dest.getMinY() - dest.getSampleModelTranslateY()));

    // Access the pixel value array
    final int[] srcPixels = srcDB.getBankData()[0];
    final int[] destPixels = dstDB.getBankData()[0];

    final int[] buffer = new int[boxSz];
    int curr, prev;

    // Fixed point normalization factor (8.24)
    final int scale = (1 << 24) / boxSz;

    /*
     * System.out.println("Info: srcOff: " + srcOff +
     *                    " x: " + skipX +
     *                    " y: " + skipY +
     *                    " w: " + w +
     *                    " h: " + h +
     *                    " boxSz " + boxSz +
     *                    " srcStride: " + srcScanStride);
     */

    for (int x = skipX; x < (w - skipX); x++) {
      int sp = srcOff + x;
      int dp = dstOff + x;
      int colEnd = sp + (h - skipY) * srcScanStride;

      int k = 0;
      int sumA = 0;
      int sumR = 0;
      int sumG = 0;
      int sumB = 0;

      sp += skipY * srcScanStride;
      int end = sp + (boxSz * srcScanStride);

      while (sp < end) {
        curr = buffer[k] = srcPixels[sp];
        sumA += (curr >>> 24);
        sumR += (curr >> 16) & 0xFF;
        sumG += (curr >> 8) & 0xFF;
        sumB += (curr) & 0xFF;
        k++;
        sp += srcScanStride;
      }

      dp += (skipY + loc) * dstScanStride;
      prev =
          destPixels[dp] =
              (((sumA * scale) & 0xFF000000)
                  | (((sumR * scale) & 0xFF000000) >>> 8)
                  | (((sumG * scale) & 0xFF000000) >>> 16)
                  | (((sumB * scale) & 0xFF000000) >>> 24));
      dp += dstScanStride;
      k = 0;
      while (sp < colEnd) {
        curr = buffer[k];
        if (curr == srcPixels[sp]) {
          destPixels[dp] = prev;
        } else {
          sumA -= (curr >>> 24);
          sumR -= (curr >> 16) & 0xFF;
          sumG -= (curr >> 8) & 0xFF;
          sumB -= (curr) & 0xFF;

          curr = buffer[k] = srcPixels[sp];

          sumA += (curr >>> 24);
          sumR += (curr >> 16) & 0xFF;
          sumG += (curr >> 8) & 0xFF;
          sumB += (curr) & 0xFF;
          prev =
              destPixels[dp] =
                  (((sumA * scale) & 0xFF000000)
                      | (((sumR * scale) & 0xFF000000) >>> 8)
                      | (((sumG * scale) & 0xFF000000) >>> 16)
                      | (((sumB * scale) & 0xFF000000) >>> 24));
        }
        k = (k + 1) % boxSz;
        sp += srcScanStride;
        dp += dstScanStride;
      }
    }
    return dest;
  }
示例#28
0
  private IFD writeRGBImage(
      ImageOutputStream out, BufferedImage image, int comp, TIFFImageWriteParam param)
      throws IOException {
    image = convert(image, BufferedImage.TYPE_INT_RGB);
    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(3);
      bpss.setBitsPerSample(0, 8); // red
      bpss.setBitsPerSample(1, 8); // green
      bpss.setBitsPerSample(2, 8); // blue
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(comp)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(RGB)); // 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(3)); // 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();
      DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
      int[] imgdata = (int[]) buffer.getData();

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

        Each strip: evaluate r g b 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, 0x11, 0x11}; // (Hi<<4)|Vi
          int[] q = {0, 0, 0}; // quantization table 0
          jpegos.startOfFrame(maxrps, width, hv, q);
          int[] sel = {0, 0, 0}; // DC,AC code table 0
          jpegos.startOfScan(sel);
        }

        for (int i = 0; i < maxrps; i++) { // write RGB data
          for (int x = 0; x < width; x++) {
            int c = imgdata[x + (y + i) * width];
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
          }
        }
        os.close(); // jpeg: EOI marker

        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());
    }
  }
示例#29
0
  private IFD writeYCbCrImage(
      ImageOutputStream out, BufferedImage image, int comp, TIFFImageWriteParam param)
      throws IOException {
    image = convert(image, BufferedImage.TYPE_INT_RGB);
    try {
      int width = image.getWidth();
      int height = image.getHeight();

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

      int ss = (param == null) ? 0x22 : param.getSubSampling();

      int ssh = (ss >> 4) & 0x0F;
      int ssv = ss & 0x0F;

      if (ssh
          < ssv) { // YCbCrSubsampleVert shall always be less than or equal to YCbCrSubsampleHoriz.
        throw new IOException(
            "Internal error: YCbCrSubsampleVert is not less than YCbCrSubsampleHoriz.");
      }

      //      int ww=((width +ssh-1)/ssh)*ssh;                                   // [1] p.92
      //      int hh=((height+ssv-1)/ssv)*ssv;
      int ww = width;
      int hh = height;

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

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(3);
      bpss.setBitsPerSample(0, 8); // Y
      bpss.setBitsPerSample(1, 8); // Cb
      bpss.setBitsPerSample(2, 8); // Cr
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(comp)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(YCbCr)); // 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 * ssv - 1) / (8 * ssv)) * (8 * ssv);
        maxstripes = (height + maxrps - 1) / maxrps;
      }

      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(3)); // 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) {
        jpegos = new JPEGOutputStream(baos);

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

        jpegos.setZZQuantizationTable(0, JPEGConstants.LQT, quality);
        jpegos.setZZQuantizationTable(1, JPEGConstants.CQT, quality);

        jpegos.setRawDCHuffmanTable(0, JPEGConstants.HLDCTable);
        jpegos.setRawACHuffmanTable(0, JPEGConstants.HLACTable);
        jpegos.setRawDCHuffmanTable(1, JPEGConstants.HCDCTable);
        jpegos.setRawACHuffmanTable(1, JPEGConstants.HCACTable);

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

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

        baos.reset();

        os = jpegos;
      }

      //      CCIR Recommendation 601-1  LumaRed=299/1000 LumaGreen=587/1000 LumeBlue=114/1000
      //      Y  = ( LumaRed * R + LumaGreen * G + LumaBlue * B )
      //      Cb = ( B - Y ) / ( 2 - 2 * LumaBlue )
      //      Cr = ( R - Y ) / ( 2 - 2 * LumaRed )

      double LumaRed = 299.0 / 1000.0;
      double LumaGreen = 587.0 / 1000.0;
      double LumaBlue = 114.0 / 1000.0;

      DEFactory.YCbCrCoefficientsDE YCbCrCoeff = new DEFactory.YCbCrCoefficientsDE();
      YCbCrCoeff.setLumaRed(LumaRed); // Y
      YCbCrCoeff.setLumaGreen(LumaGreen); // Cb
      YCbCrCoeff.setLumaBlue(LumaBlue); // Cr
      ifd.add(YCbCrCoeff); // 529

      DEFactory.YCbCrSubSamplingDE YCbCrSubSampling = new DEFactory.YCbCrSubSamplingDE();
      YCbCrSubSampling.setHoriz(ssh);
      YCbCrSubSampling.setVert(ssv);
      ifd.add(YCbCrSubSampling); // 530

      double RfBY = 0;
      double RfWY = 255;
      double RfBCb = 128;
      double RfWCb = 255;
      double RfBCr = 128;
      double RfWCr = 255;

      DEFactory.ReferenceBlackWhiteDE ReferenceBlackWhite = new DEFactory.ReferenceBlackWhiteDE();
      ReferenceBlackWhite.setY(RfBY, RfWY);
      ReferenceBlackWhite.setCb(RfBCb, RfWCb);
      ReferenceBlackWhite.setCr(RfBCr, RfWCr);
      ifd.add(ReferenceBlackWhite); // 532

      TIFFYCbCrOutputStream ycbcros;
      if (jpegos == null) {
        ycbcros = new TIFFYCbCrOutputStream(os, width, ssv, ssh);
        os = new TIFFSubSamplingOutputStream(ycbcros, width, ssv, ssh);
      } else {
        ycbcros = new TIFFYCbCrOutputStream(os, width, 1, 1); // jpeg does own subsampling
        os = ycbcros;
      }

      ycbcros.setPositioning(1);
      ycbcros.setColourCoefficients(LumaRed, LumaGreen, LumaBlue);
      ycbcros.setRfBWY(RfBY, RfWY);
      ycbcros.setRfBWCb(RfBCb, RfWCb);
      ycbcros.setRfBWCr(RfBCr, RfWCr);

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

      int c = 0, index = 0;
      for (int y = 0; y < height; y += maxrps) {

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

        if (jpegos != null) {
          jpegos.startOfImage();
          int[] hv = {(ssh << 4) | ssv, 0x11, 0x11}; // (Hi<<4)|Vi
          int[] q = {0, 1, 1}; // quantization table Y=0, Cb=Cr=1
          //          jpegos.startOfFrame(((maxrps+ssv-1)/ssv)*ssv,ww,hv,q);
          jpegos.startOfFrame(maxrps, ww, hv, q);
          int[] sel = {0, 1, 1}; // DC,AC code table Y=0, Cb=Cr=1
          jpegos.startOfScan(sel);
        }

        for (int i = 0; i < maxrps; i++) {
          int x = 0;
          while (x < width) {
            c = imgdata[x + (y + i) * width];
            //            c = image.getRGB(x,y+i);
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
            x++;
          }
          while (x < ww) {
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
            x++;
          }
        }
        os.close();

        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() + ".writeYCbCrImage:\n\t" + e.getMessage());
    }
  }