Examples of WritableRaster


Examples of java.awt.image.WritableRaster

                    sourceCM.isAlphaPremultiplied(),
                    sourceCM.getTransparency());

            // Create a raster which can contain the entire source.
            Point origin = new Point(im.getMinX(), im.getMinY());
            WritableRaster raster =
                Raster.createWritableRaster(
                    destCM.createCompatibleSampleModel(im.getWidth(),
                                                       im.getHeight()),
                    origin);

            // Copy the source data.
            raster.setRect(im.getData());

            // Replace the source reference with the new image.
            im = new SingleTileRenderedImage(raster, destCM);
        }

  // Currently all images are stored uncompressed.
  int compression = encodeParam.getCompression();

  // Get tiled output preference.
  boolean isTiled = encodeParam.getWriteTiled();

        // Set bounds.
        int minX = im.getMinX();
        int minY = im.getMinY();
        int width = im.getWidth();
        int height = im.getHeight();

        // Get SampleModel.
        SampleModel sampleModel = im.getSampleModel();

        // Retrieve and verify sample size.
  int sampleSize[] = sampleModel.getSampleSize();
        for(int i = 1; i < sampleSize.length; i++) {
            if(sampleSize[i] != sampleSize[0]) {
                throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder0"));
            }
        }

        // Check low bit limits.
  int numBands = sampleModel.getNumBands();
        if((sampleSize[0] == 1 || sampleSize[0] == 4) && numBands != 1) {
            throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder1"));
        }

        // Retrieve and verify data type.
  int dataType = sampleModel.getDataType();
        switch(dataType) {
        case DataBuffer.TYPE_BYTE:
            if(sampleSize[0] != 1 && sampleSize[0] != 4 &&
               sampleSize[0] != 8) {
                throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder2"));
            }
            break;
        case DataBuffer.TYPE_SHORT:
        case DataBuffer.TYPE_USHORT:
            if(sampleSize[0] != 16) {
                throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder3"));
            }
            break;
        case DataBuffer.TYPE_INT:
        case DataBuffer.TYPE_FLOAT:
            if(sampleSize[0] != 32) {
                throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder4"));
            }
            break;
        default:
      throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder5"));
  }

        boolean dataTypeIsShort =
            dataType == DataBuffer.TYPE_SHORT ||
            dataType == DataBuffer.TYPE_USHORT;

  ColorModel colorModel = im.getColorModel();
        if (colorModel != null &&
            colorModel instanceof IndexColorModel &&
            dataType != DataBuffer.TYPE_BYTE) {
            // Don't support (unsigned) short palette-color images.
      throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder6"));
        }
  IndexColorModel icm = null;
  int sizeOfColormap = 0
  int colormap[] = null;

        // Set image type.
  int imageType = TIFF_UNSUPPORTED;
        int numExtraSamples = 0;
        int extraSampleType = EXTRA_SAMPLE_UNSPECIFIED;
        if(colorModel instanceof IndexColorModel) { // Bilevel or palette
            icm = (IndexColorModel)colorModel;
            int mapSize = icm.getMapSize();

            if(sampleSize[0] == 1 && numBands == 1) { // Bilevel image

    if (mapSize != 2) {
        throw new IllegalArgumentException(
          JaiI18N.getString("TIFFImageEncoder7"));
    }

    byte r[] = new byte[mapSize];
    icm.getReds(r);
    byte g[] = new byte[mapSize];
    icm.getGreens(g);
    byte b[] = new byte[mapSize];
    icm.getBlues(b);

    if ((r[0] & 0xff) == 0 &&
        (r[1] & 0xff) == 255 &&
        (g[0] & 0xff) == 0 &&
        (g[1] & 0xff) == 255 &&
        (b[0] & 0xff) == 0 &&
        (b[1] & 0xff) == 255) {

        imageType = TIFF_BILEVEL_BLACK_IS_ZERO;

    } else if ((r[0] & 0xff) == 255 &&
         (r[1] & 0xff) == 0 &&
         (g[0] & 0xff) == 255 &&
         (g[1] & 0xff) == 0 &&
         (b[0] & 0xff) == 255 &&
         (b[1] & 0xff) == 0) {
       
        imageType = TIFF_BILEVEL_WHITE_IS_ZERO;

    } else {
        imageType = TIFF_PALETTE;
    }

      } else if(numBands == 1) { // Non-bilevel image.
    // Palette color image.
    imageType = TIFF_PALETTE;
      }
  } else if(colorModel == null) {

            if(sampleSize[0] == 1 && numBands == 1) { // bilevel
                imageType = TIFF_BILEVEL_BLACK_IS_ZERO;
            } else { // generic image
                imageType = TIFF_GENERIC;
                if(numBands > 1) {
                    numExtraSamples = numBands - 1;
                }
            }

        } else { // colorModel is non-null but not an IndexColorModel
            ColorSpace colorSpace = colorModel.getColorSpace();

            switch(colorSpace.getType()) {
            case ColorSpace.TYPE_CMYK:
                imageType = TIFF_CMYK;
                break;
            case ColorSpace.TYPE_GRAY:
                imageType = TIFF_GRAY;
                break;
            case ColorSpace.TYPE_Lab:
                imageType = TIFF_CIELAB;
                break;
            case ColorSpace.TYPE_RGB:
                if(compression == COMP_JPEG_TTN2 &&
                   encodeParam.getJPEGCompressRGBToYCbCr()) {
                    imageType = TIFF_YCBCR;
                } else {
                    imageType = TIFF_RGB;
                }
                break;
            case ColorSpace.TYPE_YCbCr:
                imageType = TIFF_YCBCR;
                break;
            default:
                imageType = TIFF_GENERIC; // generic
                break;
            }

            if(imageType == TIFF_GENERIC) {
                numExtraSamples = numBands - 1;
            } else if(numBands > 1) {
                numExtraSamples = numBands - colorSpace.getNumComponents();
            }

            if(numExtraSamples == 1 && colorModel.hasAlpha()) {
                extraSampleType = colorModel.isAlphaPremultiplied() ?
                    EXTRA_SAMPLE_ASSOCIATED_ALPHA :
                    EXTRA_SAMPLE_UNASSOCIATED_ALPHA;
            }
        }

        if(imageType == TIFF_UNSUPPORTED) {
            throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder8"));
        }

        // Check JPEG compatibility.
        if(compression == COMP_JPEG_TTN2) {
            if(imageType == TIFF_PALETTE) {
                throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder11"));
            } else if(!(sampleSize[0] == 8 &&
                        (imageType == TIFF_GRAY ||
                         imageType == TIFF_RGB ||
                         imageType == TIFF_YCBCR))) {
                throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder9"));
            }
        }

        // Check bilevel encoding compatibility.
        if((imageType != TIFF_BILEVEL_WHITE_IS_ZERO &&
            imageType != TIFF_BILEVEL_BLACK_IS_ZERO) &&
           (compression == COMP_GROUP3_1D ||
            compression == COMP_GROUP3_2D ||
            compression == COMP_GROUP4)) {
            throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder12"));
        }
 
  int photometricInterpretation = -1;
  switch (imageType) {

  case TIFF_BILEVEL_WHITE_IS_ZERO:
      photometricInterpretation = 0;
      break;

  case TIFF_BILEVEL_BLACK_IS_ZERO:
      photometricInterpretation = 1;
      break;

  case TIFF_GRAY:
        case TIFF_GENERIC:
      // Since the CS_GRAY colorspace is always of type black_is_zero
      photometricInterpretation = 1;
      break;

  case TIFF_PALETTE:
      photometricInterpretation = 3;

      icm = (IndexColorModel)colorModel;
      sizeOfColormap = icm.getMapSize();

      byte r[] = new byte[sizeOfColormap];
      icm.getReds(r);
      byte g[] = new byte[sizeOfColormap];
      icm.getGreens(g);
      byte b[] = new byte[sizeOfColormap];
      icm.getBlues(b);

      int redIndex = 0, greenIndex = sizeOfColormap;
      int blueIndex = 2 * sizeOfColormap;
      colormap = new int[sizeOfColormap * 3];
      for (int i=0; i<sizeOfColormap; i++) {
    colormap[redIndex++] = (r[i] << 8) & 0xffff;
    colormap[greenIndex++] = (g[i] << 8) & 0xffff;
    colormap[blueIndex++] = (b[i] << 8) & 0xffff;
      }

      sizeOfColormap *= 3;

      break;

  case TIFF_RGB:
      photometricInterpretation = 2;
      break;

        case TIFF_CMYK:
      photometricInterpretation = 5;
            break;

        case TIFF_YCBCR:
      photometricInterpretation = 6;
            break;

        case TIFF_CIELAB:
      photometricInterpretation = 8;
            break;

        default:
            throw new RuntimeException(JaiI18N.getString("TIFFImageEncoder8"));
  }

        // Initialize tile dimensions.
        int tileWidth;
        int tileHeight;
        if(isTiled) {
            tileWidth = encodeParam.getTileWidth() > 0 ?
                encodeParam.getTileWidth() : im.getTileWidth();
            tileHeight = encodeParam.getTileHeight() > 0 ?
                encodeParam.getTileHeight() : im.getTileHeight();
        } else {
            tileWidth = width;
            // XXX Set rows per strip based on memory value if not specified?
            tileHeight = encodeParam.getTileHeight() > 0 ?
                encodeParam.getTileHeight() : DEFAULT_ROWS_PER_STRIP;
        }

        // Re-tile for JPEG conformance if needed.
        JPEGEncodeParam jep = null;
        if(compression == COMP_JPEG_TTN2) {
            // Get JPEGEncodeParam from encodeParam.
            jep = encodeParam.getJPEGEncodeParam();

            // Determine maximum subsampling.
            int maxSubH = jep.getHorizontalSubsampling(0);
            int maxSubV = jep.getVerticalSubsampling(0);
            for(int i = 1; i < numBands; i++) {
                int subH = jep.getHorizontalSubsampling(i);
                if(subH > maxSubH) {
                    maxSubH = subH;
                }
                int subV = jep.getVerticalSubsampling(i);
                if(subV > maxSubV) {
                    maxSubV = subV;
                }
            }

            int factorV = 8*maxSubV;
            tileHeight =
                (int)((float)tileHeight/(float)factorV + 0.5F)*factorV;
            if(tileHeight < factorV) {
                tileHeight = factorV;
            }

            if(isTiled) {
                int factorH = 8*maxSubH;
                tileWidth =
                    (int)((float)tileWidth/(float)factorH + 0.5F)*factorH;
                if(tileWidth < factorH) {
                    tileWidth = factorH;
                }
            }
        }

        int numTiles;
        if(isTiled) {
            // NB: Parentheses are used in this statement for correct rounding.
            numTiles =
                ((width + tileWidth - 1)/tileWidth) *
                ((height + tileHeight - 1)/tileHeight);
        } else {
            numTiles = (int)Math.ceil((double)height/(double)tileHeight);
        }

  long tileByteCounts[] = new long[numTiles];

  long bytesPerRow =
            (long)Math.ceil((sampleSize[0] / 8.0) * tileWidth * numBands);

  long bytesPerTile = bytesPerRow * tileHeight;

  for (int i=0; i<numTiles; i++) {
      tileByteCounts[i] = bytesPerTile;
  }

        if(!isTiled) {
            // Last strip may have lesser rows
            long lastStripRows = height - (tileHeight * (numTiles-1));
            tileByteCounts[numTiles-1] = lastStripRows * bytesPerRow;
        }

  long totalBytesOfData = bytesPerTile * (numTiles - 1) +
      tileByteCounts[numTiles-1];

        // The data will be written after the IFD: create the array here
        // but fill it in later.
  long tileOffsets[] = new long[numTiles];

  // Basic fields - have to be in increasing numerical order.
  // ImageWidth                     256
  // ImageLength                    257
  // BitsPerSample                  258
  // Compression                    259
  // PhotoMetricInterpretation      262
  // StripOffsets                   273
  // RowsPerStrip                   278
  // StripByteCounts                279
  // XResolution                    282
  // YResolution                    283
  // ResolutionUnit                 296 

  // Create Directory
  SortedSet fields = new TreeSet();

  // Image Width
  fields.add(new TIFFField(TIFFImageDecoder.TIFF_IMAGE_WIDTH,
                                 TIFFField.TIFF_LONG, 1,
                                 (Object)(new long[] {(long)width})));

  // Image Length
  fields.add(new TIFFField(TIFFImageDecoder.TIFF_IMAGE_LENGTH,
                                 TIFFField.TIFF_LONG, 1,
                                 new long[] {(long)height}));

  fields.add(new TIFFField(TIFFImageDecoder.TIFF_BITS_PER_SAMPLE,
                                 TIFFField.TIFF_SHORT, numBands,
                                 intsToChars(sampleSize)));

  fields.add(new TIFFField(TIFFImageDecoder.TIFF_COMPRESSION,
                                 TIFFField.TIFF_SHORT, 1,
                                 new char[] {(char)compression}));

  fields.add(
      new TIFFField(TIFFImageDecoder.TIFF_PHOTOMETRIC_INTERPRETATION,
                          TIFFField.TIFF_SHORT, 1,
                          new char[] {(char)photometricInterpretation}));

        if(!isTiled) {
            fields.add(new TIFFField(TIFFImageDecoder.TIFF_STRIP_OFFSETS,
                                     TIFFField.TIFF_LONG, numTiles,
                                     (long[])tileOffsets));
        }
 
  fields.add(new TIFFField(TIFFImageDecoder.TIFF_SAMPLES_PER_PIXEL,
                                 TIFFField.TIFF_SHORT, 1,
                                 new char[] {(char)numBands}));

        if(!isTiled) {
            fields.add(new TIFFField(TIFFImageDecoder.TIFF_ROWS_PER_STRIP,
                                     TIFFField.TIFF_LONG, 1,
                                     new long[] {(long)tileHeight}));

            fields.add(new TIFFField(TIFFImageDecoder.TIFF_STRIP_BYTE_COUNTS,
                                     TIFFField.TIFF_LONG, numTiles,
                                     (long[])tileByteCounts));
        }

  if (colormap != null) {
      fields.add(new TIFFField(TIFFImageDecoder.TIFF_COLORMAP,
                                     TIFFField.TIFF_SHORT, sizeOfColormap,
                                     intsToChars(colormap)));
  }

        if(isTiled) {
            fields.add(new TIFFField(TIFFImageDecoder.TIFF_TILE_WIDTH,
                                     TIFFField.TIFF_LONG, 1,
                                     new long[] {(long)tileWidth}));

            fields.add(new TIFFField(TIFFImageDecoder.TIFF_TILE_LENGTH,
                                     TIFFField.TIFF_LONG, 1,
                                     new long[] {(long)tileHeight}));

            fields.add(new TIFFField(TIFFImageDecoder.TIFF_TILE_OFFSETS,
                                     TIFFField.TIFF_LONG, numTiles,
                                     (long[])tileOffsets));

            fields.add(new TIFFField(TIFFImageDecoder.TIFF_TILE_BYTE_COUNTS,
                                     TIFFField.TIFF_LONG, numTiles,
                                     (long[])tileByteCounts));
        }

        if(numExtraSamples > 0) {
            int[] extraSamples = new int[numExtraSamples];
            for(int i = 0; i < numExtraSamples; i++) {
                extraSamples[i] = extraSampleType;
            }
            fields.add(new TIFFField(TIFFImageDecoder.TIFF_EXTRA_SAMPLES,
                                     TIFFField.TIFF_SHORT, numExtraSamples,
                                     intsToChars(extraSamples)));
        }

        // Data Sample Format Extension fields.
        if(dataType != DataBuffer.TYPE_BYTE) {
            // SampleFormat
            int[] sampleFormat = new int[numBands];
            if(dataType == DataBuffer.TYPE_FLOAT) {
                sampleFormat[0] = 3;
            } else if(dataType == DataBuffer.TYPE_USHORT) {
                sampleFormat[0] = 1;
            } else {
                sampleFormat[0] = 2;
            }
            for(int b = 1; b < numBands; b++) {
                sampleFormat[b] = sampleFormat[0];
            }
      fields.add(new TIFFField(TIFFImageDecoder.TIFF_SAMPLE_FORMAT,
                                     TIFFField.TIFF_SHORT, numBands,
                                     intsToChars(sampleFormat)));

            // NOTE: We don't bother setting the SMinSampleValue and
            // SMaxSampleValue fields as these both default to the
            // extrema of the respective data types.  Probably we should
            // check for the presence of the "extrema" property and
            // use it if available.
        }

        // Bilevel compression variables.
        boolean inverseFill = encodeParam.getReverseFillOrder();
        boolean T4encode2D = encodeParam.getT4Encode2D();
        boolean T4PadEOLs = encodeParam.getT4PadEOLs();
        TIFFFaxEncoder faxEncoder = null;

        // Add bilevel compression fields.
        if((imageType == TIFF_BILEVEL_BLACK_IS_ZERO ||
            imageType == TIFF_BILEVEL_WHITE_IS_ZERO) &&
           (compression == COMP_GROUP3_1D ||
            compression == COMP_GROUP3_2D ||
            compression == COMP_GROUP4)) {

            // Create the encoder.
            faxEncoder = new TIFFFaxEncoder(inverseFill);

            // FillOrder field.
            fields.add(new TIFFField(TIFFImageDecoder.TIFF_FILL_ORDER,
                                     TIFFField.TIFF_SHORT, 1,
                                     new char[] {inverseFill ?
                                                 (char)2 : (char)1}));

            if(compression == COMP_GROUP3_2D) {
                // T4Options field.
                long T4Options = 0x00000000;
                if(T4encode2D) {
                    T4Options |= 0x00000001;
                }
                if(T4PadEOLs) {
                    T4Options |= 0x00000004;
                }
                fields.add(new TIFFField(TIFFImageDecoder.TIFF_T4_OPTIONS,
                                         TIFFField.TIFF_LONG, 1,
                                         new long[] {T4Options}));
            } else if(compression == COMP_GROUP4) {
                // T6Options field.
                fields.add(new TIFFField(TIFFImageDecoder.TIFF_T6_OPTIONS,
                                         TIFFField.TIFF_LONG, 1,
                                         new long[] {(long)0x00000000}));
            }
        }

        // Initialize some JPEG variables.
        com.sun.image.codec.jpeg.JPEGEncodeParam jpegEncodeParam = null;
        com.sun.image.codec.jpeg.JPEGImageEncoder jpegEncoder = null;
        int jpegColorID = 0;

        if(compression == COMP_JPEG_TTN2) {

            // Initialize JPEG color ID.
            jpegColorID =
                com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_UNKNOWN;
            switch(imageType) {
            case TIFF_GRAY:
            case TIFF_PALETTE:
                jpegColorID =
                    com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_GRAY;
                break;
            case TIFF_RGB:
                jpegColorID =
                    com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_RGB;
                break;
            case TIFF_YCBCR:
                jpegColorID =
                    com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCr;
                break;
            }

            // Get the JDK encoding parameters.
            Raster tile00 = im.getTile(im.getMinTileX(), im.getMinTileY());
            jpegEncodeParam =
                com.sun.image.codec.jpeg.JPEGCodec.getDefaultJPEGEncodeParam(
                    tile00, jpegColorID);

            // Modify per values passed in.
            JPEGImageEncoder.modifyEncodeParam(jep, jpegEncodeParam, numBands);

            // JPEGTables field.
            if(jep.getWriteImageOnly()) {
                // Write an abbreviated tables-only stream to JPEGTables field.
                jpegEncodeParam.setImageInfoValid(false);
                jpegEncodeParam.setTableInfoValid(true);
                ByteArrayOutputStream tableStream =
                    new ByteArrayOutputStream();
                jpegEncoder =
                    com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(
                        tableStream,
                        jpegEncodeParam);
                jpegEncoder.encode(tile00);
                byte[] tableData = tableStream.toByteArray();
                fields.add(new TIFFField(TIFF_JPEG_TABLES,
                                         TIFFField.TIFF_UNDEFINED,
                                         tableData.length,
                                         tableData));

                // Reset encoder so it's recreated below.
                jpegEncoder = null;
            }
        }

        if(imageType == TIFF_YCBCR) {
            // YCbCrSubSampling: 2 is the default so we must write 1 as
            // we do not (yet) do any subsampling.
            int subsampleH = 1;
            int subsampleV = 1;

            // If JPEG, update values.
            if(compression == COMP_JPEG_TTN2) {
                // Determine maximum subsampling.
                subsampleH = jep.getHorizontalSubsampling(0);
                subsampleV = jep.getVerticalSubsampling(0);
                for(int i = 1; i < numBands; i++) {
                    int subH = jep.getHorizontalSubsampling(i);
                    if(subH > subsampleH) {
                        subsampleH = subH;
                    }
                    int subV = jep.getVerticalSubsampling(i);
                    if(subV > subsampleV) {
                        subsampleV = subV;
                    }
                }
            }

            fields.add(new TIFFField(TIFF_YCBCR_SUBSAMPLING,
                                     TIFFField.TIFF_SHORT, 2,
                                     new char[] {(char)subsampleH,
                                                 (char)subsampleV}));


            // YCbCr positioning.
            fields.add(new TIFFField(TIFF_YCBCR_POSITIONING,
                                     TIFFField.TIFF_SHORT, 1,
                                     new char[] {compression == COMP_JPEG_TTN2 ?
                                                 (char)1 : (char)2}));

            // Reference black/white.
            long[][] refbw;
            if(compression == COMP_JPEG_TTN2) {
                refbw =
                    new long[][] { // no headroon/footroom
                        {0, 1}, {255, 1}, {128, 1}, {255, 1}, {128, 1}, {255, 1}
                    };
            } else {
                refbw =
                    new long[][] { // CCIR 601.1 headroom/footroom (presumptive)
                        {15, 1}, {235, 1}, {128, 1}, {240, 1}, {128, 1}, {240, 1}
                    };
            }
            fields.add(new TIFFField(TIFF_REF_BLACK_WHITE,
                                     TIFFField.TIFF_RATIONAL, 6,
                                     refbw));
        }

        // ---- No more automatically generated fields should be added
        //      after this point. ----

        // Add extra fields specified via the encoding parameters.
        TIFFField[] extraFields = encodeParam.getExtraFields();
        if(extraFields != null) {
            ArrayList extantTags = new ArrayList(fields.size());
            Iterator fieldIter = fields.iterator();
            while(fieldIter.hasNext()) {
                TIFFField fld = (TIFFField)fieldIter.next();
                extantTags.add(new Integer(fld.getTag()));
            }

            int numExtraFields = extraFields.length;
            for(int i = 0; i < numExtraFields; i++) {
                TIFFField fld = extraFields[i];
                Integer tagValue = new Integer(fld.getTag());
                if(!extantTags.contains(tagValue)) {
                    fields.add(fld);
                    extantTags.add(tagValue);
                }
            }
        }

        // ---- No more fields of any type should be added after this. ----

        // Determine the size of the IFD which is written after the header
        // of the stream or after the data of the previous image in a
        // multi-page stream.
        int dirSize = getDirectorySize(fields);

        // The first data segment is written after the field overflow
        // following the IFD so initialize the first offset accordingly.
  tileOffsets[0] = ifdOffset + dirSize;

        // Branch here depending on whether data are being comrpressed.
        // If not, then the IFD is written immediately.
        // If so then there are three possibilities:
        // A) the OutputStream is a SeekableOutputStream (outCache null);
        // B) the OutputStream is not a SeekableOutputStream and a file cache
        //    is used (outCache non-null, tempFile non-null);
        // C) the OutputStream is not a SeekableOutputStream and a memory cache
        //    is used (outCache non-null, tempFile null).

        OutputStream outCache = null;
        byte[] compressBuf = null;
        File tempFile = null;

        int nextIFDOffset = 0;
        boolean skipByte = false;

        Deflater deflater = null;
        int deflateLevel = Deflater.DEFAULT_COMPRESSION;

        boolean jpegRGBToYCbCr = false;

        if(compression == COMP_NONE) {
            // Determine the number of bytes of padding necessary between
            // the end of the IFD and the first data segment such that the
            // alignment of the data conforms to the specification (required
            // for uncompressed data only).
            int numBytesPadding = 0;
            if(sampleSize[0] == 16 && tileOffsets[0] % 2 != 0) {
                numBytesPadding = 1;
                tileOffsets[0]++;
            } else if(sampleSize[0] == 32 && tileOffsets[0] % 4 != 0) {
                numBytesPadding = (int)(4 - tileOffsets[0] % 4);
                tileOffsets[0] += numBytesPadding;
            }

            // Update the data offsets (which TIFFField stores by reference).
            for (int i = 1; i < numTiles; i++) {
                tileOffsets[i] = tileOffsets[i-1] + tileByteCounts[i-1];
            }

            if(!isLast) {
                // Determine the offset of the next IFD.
                nextIFDOffset = (int)(tileOffsets[0] + totalBytesOfData);

                // IFD offsets must be on a word boundary.
                if(nextIFDOffset % 2 != 0) {
                    nextIFDOffset++;
                    skipByte = true;
                }
            }

            // Write the IFD and field overflow before the image data.
            writeDirectory(ifdOffset, fields, nextIFDOffset);

            // Write any padding bytes needed between the end of the IFD
            // and the start of the actual image data.
            if(numBytesPadding != 0) {
                for(int padding = 0; padding < numBytesPadding; padding++) {
                    output.write((byte)0);
                }
            }
        } else {
            // If compressing, the cannot be written yet as the size of the
            // data segments is unknown.

            if((output instanceof SeekableOutputStream)) {
                // Simply seek to the first data segment position.
                ((SeekableOutputStream)output).seek(tileOffsets[0]);
            } else {
                // Cache the original OutputStream.
                outCache = output;

                try {
                    // Attempt to create a temporary file.
                    tempFile = File.createTempFile("jai-SOS-", ".tmp");
                    tempFile.deleteOnExit();
                    RandomAccessFile raFile =
                        new RandomAccessFile(tempFile, "rw");
                    output = new SeekableOutputStream(raFile);
                    // XXX Be sure that this file is deleted no matter how
                    // this method is exited!
                } catch(Exception e) {
                    tempFile = null;
                    // Allocate memory for the entire image data (!).
                    output = new ByteArrayOutputStream((int)totalBytesOfData);
                }
            }

            int bufSize = 0;
            switch(compression) {
            case COMP_GROUP3_1D:
                // This initial buffer size is based on an alternating 1-0
                // pattern generating the most bits when converted to code
                // words: 9 bits out for each pair of bits in. So the number
                // of bit pairs is determined, multiplied by 9, converted to
                // bytes, and a ceil() is taken to account for fill bits at the
                // end of each line.  The "2" addend accounts for the case
                // of the pattern beginning with black.  The buffer is intended
                // to hold only a single row.
                bufSize = (int)Math.ceil((((tileWidth + 1)/2)*9 + 2)/8.0);
                break;
            case COMP_GROUP3_2D:
            case COMP_GROUP4:
                // Calculate the maximum row as the G3-1D size plus the EOL,
                // multiply this by the number of rows in the tile, and add
                // 6 EOLs for the RTC (return to control).
                bufSize = (int)Math.ceil((((tileWidth + 1)/2)*9 + 2)/8.0);
                bufSize = tileHeight*(bufSize + 2) + 12;
                break;
            case COMP_PACKBITS:
                bufSize = (int)(bytesPerTile +
                                ((bytesPerRow+127)/128)*tileHeight);
                break;
            case COMP_JPEG_TTN2:
                bufSize = 0;

                // Set color conversion flag.
                if(imageType == TIFF_YCBCR &&
                   colorModel != null &&
                   colorModel.getColorSpace().getType() ==
                   ColorSpace.TYPE_RGB) {
                    jpegRGBToYCbCr = true;
                }
                break;
            case COMP_DEFLATE:
                bufSize = (int)bytesPerTile;
                deflater = new Deflater(encodeParam.getDeflateLevel());
                break;
            default:
                bufSize = 0;
            }
            if(bufSize != 0) {
                compressBuf = new byte[bufSize];
            }
        }

        // ---- Writing of actual image data ----

  // Buffer for up to tileHeight rows of pixels
        int[] pixels = null;
        float[] fpixels = null;

        // Whether to test for contiguous data.
        boolean checkContiguous =
            ((sampleSize[0] == 1 &&
              sampleModel instanceof MultiPixelPackedSampleModel &&
              dataType == DataBuffer.TYPE_BYTE) ||
             (sampleSize[0] == 8 &&
              sampleModel instanceof ComponentSampleModel));

        // Also create a buffer to hold tileHeight lines of the
        // data to be written to the file, so we can use array writes.
        byte[] bpixels = null;
        if(compression != COMP_JPEG_TTN2) {
            if(dataType == DataBuffer.TYPE_BYTE) {
                bpixels = new byte[tileHeight * tileWidth * numBands];
            } else if(dataTypeIsShort) {
                bpixels = new byte[2 * tileHeight * tileWidth * numBands];
            } else if(dataType == DataBuffer.TYPE_INT ||
                      dataType == DataBuffer.TYPE_FLOAT) {
                bpixels = new byte[4 * tileHeight * tileWidth * numBands];
            }
        }

  // Process tileHeight rows at a time
  int lastRow = minY + height;
        int lastCol = minX + width;
        int tileNum = 0;
        for (int row = minY; row < lastRow; row += tileHeight) {
            int rows = isTiled ?
                tileHeight : Math.min(tileHeight, lastRow - row);
            int size = rows * tileWidth * numBands;

            for(int col = minX; col < lastCol; col += tileWidth) {
                // Grab the pixels
                Raster src =
                    im.getData(new Rectangle(col, row, tileWidth, rows));

                boolean useDataBuffer = false;
                if(compression != COMP_JPEG_TTN2) { // JPEG access Raster
                    if(checkContiguous) {
                        if(sampleSize[0] == 8) { // 8-bit
                            ComponentSampleModel csm =
                                (ComponentSampleModel)src.getSampleModel();
                            int[] bankIndices = csm.getBankIndices();
                            int[] bandOffsets = csm.getBandOffsets();
                            int pixelStride = csm.getPixelStride();
                            int lineStride = csm.getScanlineStride();

                            if(pixelStride != numBands ||
                               lineStride != bytesPerRow) {
                                useDataBuffer = false;
                            } else {
                                useDataBuffer = true;
                                for(int i = 0;
                                    useDataBuffer && i < numBands;
                                    i++) {
                                    if(bankIndices[i] != 0 ||
                                       bandOffsets[i] != i) {
                                        useDataBuffer = false;
                                    }
                                }
                            }
                        } else { // 1-bit
                            MultiPixelPackedSampleModel mpp =
                                (MultiPixelPackedSampleModel)src.getSampleModel();
                            if(mpp.getNumBands() == 1 &&
                               mpp.getDataBitOffset() == 0 &&
                               mpp.getPixelBitStride() == 1) {
                                useDataBuffer = true;
                            }
                        }
                    }

                    if(!useDataBuffer) {
                        if(dataType == DataBuffer.TYPE_FLOAT) {
                            fpixels = src.getPixels(col, row, tileWidth, rows,
                                                    fpixels);
                        } else {
                            pixels = src.getPixels(col, row, tileWidth, rows,
                                                   pixels);
                        }
                    }
                }

                int index;

                int pixel = 0;;
                int k = 0;
                switch(sampleSize[0]) {

                case 1:

                    if(useDataBuffer) {
                        byte[] btmp =
                            ((DataBufferByte)src.getDataBuffer()).getData();
                        MultiPixelPackedSampleModel mpp =
                            (MultiPixelPackedSampleModel)src.getSampleModel();
                        int lineStride = mpp.getScanlineStride();
                        int inOffset =
                            mpp.getOffset(col -
                                          src.getSampleModelTranslateX(),
                                          row -
                                          src.getSampleModelTranslateY());
                        if(lineStride == (int)bytesPerRow) {
                            System.arraycopy(btmp, inOffset,
                                             bpixels, 0,
                                             (int)bytesPerRow*rows);
                        } else {
                            int outOffset = 0;
                            for(int j = 0; j < rows; j++) {
                                System.arraycopy(btmp, inOffset,
                                                 bpixels, outOffset,
                                                 (int)bytesPerRow);
                                inOffset += lineStride;
                                outOffset += (int)bytesPerRow;
                            }
                        }
                    } else {
                        index = 0;

                        // For each of the rows in a strip
                        for (int i=0; i<rows; i++) {

                            // Write number of pixels exactly divisible by 8
                            for (int j=0; j<tileWidth/8; j++) {
     
                                pixel =
                                    (pixels[index++] << 7) |
                                    (pixels[index++] << 6) |
                                    (pixels[index++] << 5) |
                                    (pixels[index++] << 4) |
                                    (pixels[index++] << 3) |
                                    (pixels[index++] << 2) |
                                    (pixels[index++] << 1) |
                                    pixels[index++];
                                bpixels[k++] = (byte)pixel;
                            }

                            // Write the pixels remaining after division by 8
                            if (tileWidth%8 > 0) {
                                pixel = 0;
                                for (int j=0; j<tileWidth%8; j++) {
                                    pixel |= (pixels[index++] << (7 - j));
                                }
                                bpixels[k++] = (byte)pixel;
                            }
                        }
                    }

                    if(compression == COMP_NONE) {
                        output.write(bpixels, 0, rows * ((tileWidth+7)/8));
                    } else if(compression == COMP_GROUP3_1D) {
                        int rowStride = (tileWidth + 7)/8;
                        int rowOffset = 0;
                        int numCompressedBytes = 0;
                        for(int tileRow = 0; tileRow < rows; tileRow++) {
                            int numCompressedBytesInRow =
                                faxEncoder.encodeRLE(bpixels,
                                                     rowOffset, 0, tileWidth,
                                                     compressBuf);
                            output.write(compressBuf,
                                         0, numCompressedBytesInRow);
                            rowOffset += rowStride;
                            numCompressedBytes += numCompressedBytesInRow;
                        }
                        tileByteCounts[tileNum++] = numCompressedBytes;
                    } else if(compression == COMP_GROUP3_2D) {
                        int numCompressedBytes =
                            faxEncoder.encodeT4(!T4encode2D,// 1D == !2D
                                                T4PadEOLs,
                                                bpixels,
                                                (tileWidth+7)/8,
                                                0,
                                                tileWidth,
                                                rows,
                                                compressBuf);
                        tileByteCounts[tileNum++] = numCompressedBytes;
                        output.write(compressBuf, 0, numCompressedBytes);
                    } else if(compression == COMP_GROUP4) {
                        int numCompressedBytes =
                            faxEncoder.encodeT6(bpixels,
                                                (tileWidth+7)/8,
                                                0,
                                                tileWidth,
                                                rows,
                                                compressBuf);
                        tileByteCounts[tileNum++] = numCompressedBytes;
                        output.write(compressBuf, 0, numCompressedBytes);
                    } else if(compression == COMP_PACKBITS) {
                        int numCompressedBytes =
                            compressPackBits(bpixels, rows,
                                             (int)bytesPerRow,
                                             compressBuf);
                        tileByteCounts[tileNum++] = numCompressedBytes;
                        output.write(compressBuf, 0, numCompressedBytes);
                    } else if(compression == COMP_DEFLATE) {
                        int numCompressedBytes =
                            deflate(deflater, bpixels, compressBuf);
                        tileByteCounts[tileNum++] = numCompressedBytes;
                        output.write(compressBuf, 0, numCompressedBytes);
                    }

                    break;

                case 4:
   
                    index = 0;

                    // For each of the rows in a strip
                    for (int i=0; i<rows; i++) {
       
                        // Write  the number of pixels that will fit into an
                        // even number of nibbles.
                        for (int j=0; j<tileWidth/2; j++) {
                            pixel = (pixels[index++] << 4) | pixels[index++];
                            bpixels[k++] = (byte)pixel;
                        }

                        // Last pixel for odd-length lines
                        if ((tileWidth % 2) == 1) {
                            pixel = pixels[index++] << 4;
                            bpixels[k++] = (byte)pixel;
                        }
                    }

                    if(compression == COMP_NONE) {
                        output.write(bpixels, 0, rows * ((tileWidth+1)/2));
                    } else if(compression == COMP_PACKBITS) {
                        int numCompressedBytes =
                            compressPackBits(bpixels, rows,
                                             (int)bytesPerRow,
                                             compressBuf);
                        tileByteCounts[tileNum++] = numCompressedBytes;
                        output.write(compressBuf, 0, numCompressedBytes);
                    } else if(compression == COMP_DEFLATE) {
                        int numCompressedBytes =
                            deflate(deflater, bpixels, compressBuf);
                        tileByteCounts[tileNum++] = numCompressedBytes;
                        output.write(compressBuf, 0, numCompressedBytes);
                    }
                    break;
                case 8:

                    if(compression != COMP_JPEG_TTN2) {
                        if(useDataBuffer) {
                            byte[] btmp =
                                ((DataBufferByte)src.getDataBuffer()).getData();
                            ComponentSampleModel csm =
                                (ComponentSampleModel)src.getSampleModel();
                            int inOffset =
                                csm.getOffset(col -
                                              src.getSampleModelTranslateX(),
                                              row -
                                              src.getSampleModelTranslateY());
                            int lineStride = csm.getScanlineStride();
                            if(lineStride == (int)bytesPerRow) {
                                System.arraycopy(btmp,
                                                 inOffset,
                                                 bpixels, 0,
                                                 (int)bytesPerRow*rows);
                            } else {
                                int outOffset = 0;
                                for(int j = 0; j < rows; j++) {
                                    System.arraycopy(btmp, inOffset,
                                                     bpixels, outOffset,
                                                     (int)bytesPerRow);
                                    inOffset += lineStride;
                                    outOffset += (int)bytesPerRow;
                                }
                            }
                        } else {
                            for (int i = 0; i < size; i++) {
                                bpixels[i] = (byte)pixels[i];
                            }
                        }
                    }

                    if(compression == COMP_NONE) {
                        output.write(bpixels, 0, size);
                    } else if(compression == COMP_PACKBITS) {
                        int numCompressedBytes =
                            compressPackBits(bpixels, rows,
                                             (int)bytesPerRow,
                                             compressBuf);
                        tileByteCounts[tileNum++] = numCompressedBytes;
                        output.write(compressBuf, 0, numCompressedBytes);
                    } else if(compression == COMP_JPEG_TTN2) {
                        long startPos = getOffset(output);

                        // Recreate encoder and parameters if the encoder
                        // is null (first data segment) or if its size
                        // doesn't match the current data segment.
                        if(jpegEncoder == null ||
                           jpegEncodeParam.getWidth() != src.getWidth() ||
                           jpegEncodeParam.getHeight() != src.getHeight()) {

                            jpegEncodeParam =
                                com.sun.image.codec.jpeg.JPEGCodec.
                                getDefaultJPEGEncodeParam(src, jpegColorID);

                            JPEGImageEncoder.modifyEncodeParam(jep,
                                                               jpegEncodeParam,
                                                               numBands);

                            jpegEncoder =
                                com.sun.image.codec.jpeg.JPEGCodec.
                                createJPEGEncoder(output,
                                                  jpegEncodeParam);
                        }

                        if(jpegRGBToYCbCr) {
                            WritableRaster wRas = null;
                            if(src instanceof WritableRaster) {
                                wRas = (WritableRaster)src;
                            } else {
                                wRas = src.createCompatibleWritableRaster();
                                wRas.setRect(src);
                            }

                            if (wRas.getMinX() != 0 || wRas.getMinY() != 0) {
                                wRas =
                                    wRas.createWritableTranslatedChild(0, 0);
                            }
                            BufferedImage bi =
                                new BufferedImage(colorModel, wRas,
                                                  false, null);
                            jpegEncoder.encode(bi);
View Full Code Here

Examples of java.awt.image.WritableRaster

            SampleModel sm =
                sampleModel.createCompatibleSampleModel(bounds.width,
                                                        bounds.height);

            // Translate it
            WritableRaster dest =
                RasterFactory.createWritableRaster(sm, bounds.getLocation());

            // Loop over the tiles in the intersection.
            for (int j = startY; j <= endY; j++) {
                for (int i = startX; i <= endX; i++) {
                    // Retrieve the tile.
                    Raster tile = getTile(i, j);

                    // Create a child of the tile for the intersection of
                    // the tile bounds and the bounds of the requested area.
                    Rectangle tileRect = tile.getBounds();
                    Rectangle intersectRect =
                        bounds.intersection(tile.getBounds());
                    Raster liveRaster = tile.createChild(intersectRect.x,
                                                         intersectRect.y,
                                                         intersectRect.width,
                                                         intersectRect.height,
                                                         intersectRect.x,
                                                         intersectRect.y,
                                                         null);

                    // Copy the data from the child.
                    dest.setRect(liveRaster);
                }
            }

            return dest;
        }
View Full Code Here

Examples of java.awt.image.WritableRaster

    private Raster createTileCopy(int tileX, int tileY) {
        int x = tileXToX(tileX);
        int y = tileYToY(tileY);
        Point p = new Point(x, y);

        WritableRaster tile =
            RasterFactory.createWritableRaster(sampleModel, p);
        source.copyData(tile);
        return tile;
    }
View Full Code Here

Examples of java.awt.image.WritableRaster

    public Raster computeTile(int tileX, int tileY) {
        int orgX = tileXToX(tileX);
        int orgY = tileYToY(tileY);

        WritableRaster dst = RasterFactory.createWritableRaster(
            sampleModel, new Point(orgX, orgY));

        Rectangle rect = new Rectangle(orgX, orgY,
                                       sampleModel.getWidth(),
                                       sampleModel.getHeight());
        rect = rect.intersection(getBounds());

        int numBands = sampleModel.getNumBands();
        int p[] = new int[numBands];

        for (int y = rect.y; y < (rect.y + rect.height); y++) {
            for (int x = rect.x; x < (rect.x + rect.width); x++) {
                int value = Math.max(x & 0xFF, y & 0xFF);
                for (int i = 0; i < numBands; i++) {
                    p[i] = value;
                }
                dst.setPixel(x, y, p);
            }
        }
        return dst;
    }
View Full Code Here

Examples of java.awt.image.WritableRaster

    public Raster computeTile(int tileX, int tileY) {
        int orgX = tileXToX(tileX);
        int orgY = tileYToY(tileY);

        WritableRaster dst = RasterFactory.createWritableRaster(
            sampleModel, new Point(orgX, orgY));

        Rectangle rect = new Rectangle(orgX, orgY,
                                       sampleModel.getWidth(),
                                       sampleModel.getHeight());
        rect = rect.intersection(getBounds());

        int numBands = sampleModel.getNumBands();
        int p[] = new int[numBands];

        for (int y = rect.y; y < (rect.y + rect.height); y++) {
            for (int x = rect.x; x < (rect.x + rect.width); x++) {
                for (int i = 0; i < numBands; i++) {
                    switch ( transtype ) {
                    case DataBuffer.TYPE_BYTE:
                    case DataBuffer.TYPE_USHORT:
                    // For unsigned data, limint the random number to [0, 1]
                    // and the result to [0, MAX_VALUE];
                        p[i] = (int)(maxValue * Math.random());
                        break;
                    default:
                    // For signed data, limint the random number to [-1, 1]
                    // and the result to [MIN_VALUE, MAX_VALUE];
                        p[i] = (int)((maxValue+1.0F) *
                                 (Math.random() - 0.5F) * 2.0F);
                    }
                }
                dst.setPixel(x, y, p);
            }
        }
        return dst;
    }
View Full Code Here

Examples of java.awt.image.WritableRaster

            (tileY < 0) || (tileY >= tilesY)) {
            throw new IllegalArgumentException(JaiI18N.getString("TIFFImage12"));
        }

        // The tile to return.
        WritableRaster tile = null;

        // Synchronize the rest of the method in case other TIFFImage
        // instances using the same stream were created by the same
        // TIFFImageDecoder. This fixes 4690773.
        synchronized(this.stream) {

  // Get the data array out of the DataBuffer
  byte bdata[] = null;
  short sdata[] = null;
  int idata[] = null;
  float fdata[] = null;
  DataBuffer buffer = sampleModel.createDataBuffer();

  int dataType = sampleModel.getDataType();
  if (dataType == DataBuffer.TYPE_BYTE) {
      bdata = ((DataBufferByte)buffer).getData();
  } else if (dataType == DataBuffer.TYPE_USHORT) {
      sdata = ((DataBufferUShort)buffer).getData();
  } else if (dataType == DataBuffer.TYPE_SHORT) {
      sdata = ((DataBufferShort)buffer).getData();
  } else if (dataType == DataBuffer.TYPE_INT) {
      idata = ((DataBufferInt)buffer).getData();
  } else if (dataType == DataBuffer.TYPE_FLOAT) {
            if(buffer instanceof DataBufferFloat) {
                fdata = ((DataBufferFloat)buffer).getData();
            } else {
                // This is a hack to make this work with JAI which in some
                // cases downcasts the DataBuffer to a type-specific class.
                // In the case of float data this current means the JAI class
                // com.lightcrafts.mediax.jai.DataBufferFloat.
                try {
                    Method getDataMethod =
                        buffer.getClass().getMethod("getData", null);
                    fdata = (float[])getDataMethod.invoke(buffer, null);
                } catch(Exception e) {
                    String message = JaiI18N.getString("TIFFImage18");
                    ImagingListenerProxy.errorOccurred(message,
                                           new ImagingException(message, e),
                                           this, false);
//                    throw new RuntimeException(JaiI18N.getString("TIFFImage18"));
                }
            }
  }

        tile =
      (WritableRaster)RasterFactory.createWritableRaster(sampleModel,
                                                   buffer,
                                                   new Point(tileXToX(tileX),
                                                             tileYToY(tileY)));

  // Save original file pointer position and seek to tile data location.
  long save_offset = 0;
  try {
      save_offset = stream.getFilePointer();
      stream.seek(tileOffsets[tileY*tilesX + tileX]);
  } catch (IOException ioe) {
            String message = JaiI18N.getString("TIFFImage13");
            ImagingListenerProxy.errorOccurred(message,
                                   new ImagingException(message, ioe),
                                   this, false);
//      throw new RuntimeException(JaiI18N.getString("TIFFImage13"));
  }

  // Number of bytes in this tile (strip) after compression.
  int byteCount = (int)tileByteCounts[tileY*tilesX + tileX];

  // Find out the number of bytes in the current tile. If the image is
        // tiled this may include pixels which are outside of the image bounds
        // if the image width and height are not multiples of the tile width
        // and height respectively.
  Rectangle tileRect = new Rectangle(tileXToX(tileX), tileYToY(tileY),
             tileWidth, tileHeight);
  Rectangle newRect = isTiled ?
            tileRect : tileRect.intersection(getBounds());
        int unitsInThisTile = newRect.width * newRect.height * numBands;

        // Allocate read buffer if needed.
  byte data[] = compression != COMP_NONE || imageType == TYPE_PALETTE ?
            new byte[byteCount] : null;

        // Read the data, uncompressing as needed. There are four cases:
        // bilevel, palette-RGB, 4-bit grayscale, and everything else.
        if(imageType == TYPE_BILEVEL) { // bilevel
      try {
    if (compression == COMP_PACKBITS) {
        stream.readFully(data, 0, byteCount);

        // Since the decompressed data will still be packed
        // 8 pixels into 1 byte, calculate bytesInThisTile
        int bytesInThisTile;
        if ((newRect.width % 8) == 0) {
      bytesInThisTile = (newRect.width/8) * newRect.height;
        } else {
      bytesInThisTile =
                            (newRect.width/8 + 1) * newRect.height;
        }
        decodePackbits(data, bytesInThisTile, bdata);
    } else if (compression == COMP_LZW) {
        stream.readFully(data, 0, byteCount);
        lzwDecoder.decode(data, bdata, newRect.height);
    } else if (compression == COMP_FAX_G3_1D) {
        stream.readFully(data, 0, byteCount);
        decoder.decode1D(bdata, data, 0, newRect.height);
    } else if (compression == COMP_FAX_G3_2D) {
        stream.readFully(data, 0, byteCount);
        decoder.decode2D(bdata, data, 0, newRect.height,
                                     tiffT4Options);
    } else if (compression == COMP_FAX_G4_2D) {
        stream.readFully(data, 0, byteCount);
                    decoder.decodeT6(bdata, data, 0, newRect.height,
                                     tiffT6Options);
    } else if (compression == COMP_DEFLATE) {
                    stream.readFully(data, 0, byteCount);
                    inflate(data, bdata);
    } else if (compression == COMP_NONE) {
        stream.readFully(bdata, 0, byteCount);
    }

    stream.seek(save_offset);
      } catch (IOException ioe) {
                String message = JaiI18N.getString("TIFFImage13");
                ImagingListenerProxy.errorOccurred(message,
                                       new ImagingException(message, ioe),
                                       this, false);
//    throw new RuntimeException(JaiI18N.getString("TIFFImage13"));
      }
        } else if(imageType == TYPE_PALETTE) { // palette-RGB
      if (sampleSize == 16) {

    if (decodePaletteAsShorts) {

        short tempData[]= null;

        // At this point the data is 1 banded and will
        // become 3 banded only after we've done the palette
        // lookup, since unitsInThisTile was calculated with
        // 3 bands, we need to divide this by 3.
        int unitsBeforeLookup = unitsInThisTile / 3;

        // Since unitsBeforeLookup is the number of shorts,
        // but we do our decompression in terms of bytes, we
        // need to multiply it by 2 in order to figure out
        // how many bytes we'll get after decompression.
        int entries = unitsBeforeLookup * 2;

        // Read the data, if compressed, decode it, reset the pointer
        try {

      if (compression == COMP_PACKBITS) {

          stream.readFully(data, 0, byteCount);

          byte byteArray[] = new byte[entries];
          decodePackbits(data, entries, byteArray);
          tempData = new short[unitsBeforeLookup];
          interpretBytesAsShorts(byteArray, tempData,
               unitsBeforeLookup);

      else if (compression == COMP_LZW) {

          // Read in all the compressed data for this tile
          stream.readFully(data, 0, byteCount);

          byte byteArray[] = new byte[entries];
          lzwDecoder.decode(data, byteArray, newRect.height);
          tempData = new short[unitsBeforeLookup];
          interpretBytesAsShorts(byteArray, tempData,
               unitsBeforeLookup);

      else if (compression == COMP_DEFLATE) {

          stream.readFully(data, 0, byteCount);
          byte byteArray[] = new byte[entries];
          inflate(data, byteArray);
          tempData = new short[unitsBeforeLookup];
          interpretBytesAsShorts(byteArray, tempData,
               unitsBeforeLookup);

      } else if (compression == COMP_NONE) {

          // byteCount tells us how many bytes are there
          // in this tile, but we need to read in shorts,
          // which will take half the space, so while
          // allocating we divide byteCount by 2.
          tempData = new short[byteCount/2];
          readShorts(byteCount/2, tempData);
      }

      stream.seek(save_offset);

        } catch (IOException ioe) {
                        String message = JaiI18N.getString("TIFFImage13");
                        ImagingListenerProxy.errorOccurred(message,
                                               new ImagingException(message, ioe),
                                               this, false);
//      throw new RuntimeException(
//          JaiI18N.getString("TIFFImage13"));
        }

        if (dataType == DataBuffer.TYPE_USHORT) {

      // Expand the palette image into an rgb image with ushort
      // data type.
      int cmapValue;
      int count = 0, lookup, len = colormap.length/3;
      int len2 = len * 2;
      for (int i=0; i<unitsBeforeLookup; i++) {
          // Get the index into the colormap
          lookup = tempData[i] & 0xffff;
          // Get the blue value
          cmapValue = colormap[lookup+len2];
          sdata[count++] = (short)(cmapValue & 0xffff);
          // Get the green value
          cmapValue = colormap[lookup+len];
          sdata[count++] = (short)(cmapValue & 0xffff);
          // Get the red value
          cmapValue = colormap[lookup];
          sdata[count++] = (short)(cmapValue & 0xffff);
      }

        } else if (dataType == DataBuffer.TYPE_SHORT) {

      // Expand the palette image into an rgb image with
      // short data type.
      int cmapValue;
      int count = 0, lookup, len = colormap.length/3;
      int len2 = len * 2;
      for (int i=0; i<unitsBeforeLookup; i++) {
          // Get the index into the colormap
          lookup = tempData[i] & 0xffff;
          // Get the blue value
          cmapValue = colormap[lookup+len2];
          sdata[count++] = (short)cmapValue;
          // Get the green value
          cmapValue = colormap[lookup+len];
          sdata[count++] = (short)cmapValue;
          // Get the red value
          cmapValue = colormap[lookup];
          sdata[count++] = (short)cmapValue;
      }
        }

    } else {

        // No lookup being done here, when RGB values are needed,
        // the associated IndexColorModel can be used to get them.

        try {

      if (compression == COMP_PACKBITS) {

          stream.readFully(data, 0, byteCount);

          // Since unitsInThisTile is the number of shorts,
          // but we do our decompression in terms of bytes, we
          // need to multiply unitsInThisTile by 2 in order to
          // figure out how many bytes we'll get after
          // decompression.
          int bytesInThisTile = unitsInThisTile * 2;

          byte byteArray[] = new byte[bytesInThisTile];
          decodePackbits(data, bytesInThisTile, byteArray);
          interpretBytesAsShorts(byteArray, sdata,
               unitsInThisTile);

      } else if (compression == COMP_LZW) {

          stream.readFully(data, 0, byteCount);

          // Since unitsInThisTile is the number of shorts,
          // but we do our decompression in terms of bytes, we
          // need to multiply unitsInThisTile by 2 in order to
          // figure out how many bytes we'll get after
          // decompression.
          byte byteArray[] = new byte[unitsInThisTile * 2];
          lzwDecoder.decode(data, byteArray, newRect.height);
          interpretBytesAsShorts(byteArray, sdata,
               unitsInThisTile);

      else if (compression == COMP_DEFLATE) {

          stream.readFully(data, 0, byteCount);
          byte byteArray[] = new byte[unitsInThisTile * 2];
          inflate(data, byteArray);
          interpretBytesAsShorts(byteArray, sdata,
               unitsInThisTile);

      } else if (compression == COMP_NONE) {

          readShorts(byteCount/2, sdata);
      }

      stream.seek(save_offset);

        } catch (IOException ioe) {
                        String message = JaiI18N.getString("TIFFImage13");
                        ImagingListenerProxy.errorOccurred(message,
                                               new ImagingException(message, ioe),
                                               this, false);
//      throw new RuntimeException(
//          JaiI18N.getString("TIFFImage13"));
        }
    }

      } else if (sampleSize == 8) {

    if (decodePaletteAsShorts) {

        byte tempData[]= null;

        // At this point the data is 1 banded and will
        // become 3 banded only after we've done the palette
        // lookup, since unitsInThisTile was calculated with
        // 3 bands, we need to divide this by 3.
        int unitsBeforeLookup = unitsInThisTile / 3;

        // Read the data, if compressed, decode it, reset the pointer
        try {

      if (compression == COMP_PACKBITS) {

          stream.readFully(data, 0, byteCount);
          tempData = new byte[unitsBeforeLookup];
          decodePackbits(data, unitsBeforeLookup, tempData);

      else if (compression == COMP_LZW) {

          stream.readFully(data, 0, byteCount);
          tempData = new byte[unitsBeforeLookup];
          lzwDecoder.decode(data, tempData, newRect.height);

                        } else if (compression == COMP_JPEG_TTN2) {

                            stream.readFully(data, 0, byteCount);
                            Raster tempTile = decodeJPEG(data,
                                                         decodeParam,
                                                         colorConvertJPEG,
                                                         tile.getMinX(),
                                                         tile.getMinY());
                            int[] tempPixels = new int[unitsBeforeLookup];
                            tempTile.getPixels(tile.getMinX(),
                                               tile.getMinY(),
                                               tile.getWidth(),
                                               tile.getHeight(),
                                               tempPixels);
          tempData = new byte[unitsBeforeLookup];
                            for(int i = 0; i < unitsBeforeLookup; i++) {
                                tempData[i] = (byte)tempPixels[i];
                            }

      }  else if (compression == COMP_DEFLATE) {

          stream.readFully(data, 0, byteCount);
          tempData = new byte[unitsBeforeLookup];
          inflate(data, tempData);

      } else if (compression == COMP_NONE) {

          tempData = new byte[byteCount];
          stream.readFully(tempData, 0, byteCount);
      }

      stream.seek(save_offset);

        } catch (IOException ioe) {
                        String message = JaiI18N.getString("TIFFImage13");
                        ImagingListenerProxy.errorOccurred(message,
                                               new ImagingException(message, ioe),
                                               this, false);
//    throw new RuntimeException(
//          JaiI18N.getString("TIFFImage13"));
        }

        // Expand the palette image into an rgb image with ushort
        // data type.
        int cmapValue;
        int count = 0, lookup, len = colormap.length/3;
        int len2 = len * 2;
        for (int i=0; i<unitsBeforeLookup; i++) {
      // Get the index into the colormap
      lookup = tempData[i] & 0xff;
      // Get the blue value
      cmapValue = colormap[lookup+len2];
      sdata[count++] = (short)(cmapValue & 0xffff);
      // Get the green value
      cmapValue = colormap[lookup+len];
      sdata[count++] = (short)(cmapValue & 0xffff);
      // Get the red value
      cmapValue = colormap[lookup];
      sdata[count++] = (short)(cmapValue & 0xffff);
        }
    } else {

        // No lookup being done here, when RGB values are needed,
        // the associated IndexColorModel can be used to get them.

        try {

      if (compression == COMP_PACKBITS) {

          stream.readFully(data, 0, byteCount);
          decodePackbits(data, unitsInThisTile, bdata);

      } else if (compression == COMP_LZW) {

          stream.readFully(data, 0, byteCount);
          lzwDecoder.decode(data, bdata, newRect.height);

                        } else if (compression == COMP_JPEG_TTN2) {

                            stream.readFully(data, 0, byteCount);
                            tile.setRect(decodeJPEG(data,
                                                    decodeParam,
                                                    colorConvertJPEG,
                                                    tile.getMinX(),
                                                    tile.getMinY()));

      else if (compression == COMP_DEFLATE) {

                            stream.readFully(data, 0, byteCount);
                            inflate(data, bdata);

      } else if (compression == COMP_NONE) {

          stream.readFully(bdata, 0, byteCount);
      }

      stream.seek(save_offset);

        } catch (IOException ioe) {
                        String message = JaiI18N.getString("TIFFImage13");
                        ImagingListenerProxy.errorOccurred(message,
                                               new ImagingException(message, ioe),
                                               this, false);
//    throw new RuntimeException(
//          JaiI18N.getString("TIFFImage13"));
        }
    }

      } else if (sampleSize == 4) {

    int padding = (newRect.width % 2 == 0) ? 0 : 1;
    int bytesPostDecoding = ((newRect.width/2 + padding) *
           newRect.height);

    // Output short images
    if (decodePaletteAsShorts) {

        byte tempData[] = null;

        try {
      stream.readFully(data, 0, byteCount);
      stream.seek(save_offset);
        } catch (IOException ioe) {
                        String message = JaiI18N.getString("TIFFImage13");
                        ImagingListenerProxy.errorOccurred(message,
                                               new ImagingException(message, ioe),
                                               this, false);
//      throw new RuntimeException(
//          JaiI18N.getString("TIFFImage13"));
        }

        // If compressed, decode the data.
        if (compression == COMP_PACKBITS) {

      tempData = new byte[bytesPostDecoding];
      decodePackbits(data, bytesPostDecoding, tempData);

        else if (compression == COMP_LZW) {

      tempData = new byte[bytesPostDecoding];
      lzwDecoder.decode(data, tempData, newRect.height);

                    else if (compression == COMP_DEFLATE) {

      tempData = new byte[bytesPostDecoding];
      inflate(data, tempData);

        } else if (compression == COMP_NONE) {

      tempData = data;
        }

        int bytes = unitsInThisTile / 3;

        // Unpack the 2 pixels packed into each byte.
        data = new byte[bytes];

        int srcCount = 0, dstCount = 0;
        for (int j=0; j<newRect.height; j++) {
      for (int i=0; i<newRect.width/2; i++) {
          data[dstCount++] =
        (byte)((tempData[srcCount] & 0xf0) >> 4);
          data[dstCount++] =
        (byte)(tempData[srcCount++] & 0x0f);
      }

      if (padding == 1) {
          data[dstCount++] =
        (byte)((tempData[srcCount++] & 0xf0) >> 4);
      }
        }

        int len = colormap.length/3;
        int len2 = len*2;
        int cmapValue, lookup;
        int count = 0;
        for (int i=0; i<bytes; i++) {
      lookup = data[i] & 0xff;
      cmapValue = colormap[lookup+len2];
      sdata[count++] = (short)(cmapValue & 0xffff);
      cmapValue = colormap[lookup+len];
      sdata[count++] = (short)(cmapValue & 0xffff);
      cmapValue = colormap[lookup];
      sdata[count++] = (short)(cmapValue & 0xffff);
        }
    } else {

        // Output byte values, use IndexColorModel for unpacking
        try {

      // If compressed, decode the data.
      if (compression == COMP_PACKBITS) {

          stream.readFully(data, 0, byteCount);
          decodePackbits(data, bytesPostDecoding, bdata);

      else if (compression == COMP_LZW) {

          stream.readFully(data, 0, byteCount);
          lzwDecoder.decode(data, bdata, newRect.height);

                        else if (compression == COMP_DEFLATE) {

          stream.readFully(data, 0, byteCount);
          inflate(data, bdata);

      } else if (compression == COMP_NONE) {

          stream.readFully(bdata, 0, byteCount);
      }

      stream.seek(save_offset);

        } catch (IOException ioe) {
                        String message = JaiI18N.getString("TIFFImage13");
                        ImagingListenerProxy.errorOccurred(message,
                                               new ImagingException(message, ioe),
                                               this, false);
//      throw new RuntimeException(
//          JaiI18N.getString("TIFFImage13"));
        }
    }
      }
        } else if(imageType == TYPE_GRAY_4BIT) { // 4-bit gray
            try {
                if (compression == COMP_PACKBITS) {

                    stream.readFully(data, 0, byteCount);

                    // Since the decompressed data will still be packed
                    // 2 pixels into 1 byte, calculate bytesInThisTile
                    int bytesInThisTile;
                    if ((newRect.width % 8) == 0) {
                        bytesInThisTile = (newRect.width/2) * newRect.height;
                    } else {
                        bytesInThisTile = (newRect.width/2 + 1) *
                            newRect.height;
                    }

                    decodePackbits(data, bytesInThisTile, bdata);

                } else if (compression == COMP_LZW) {

                    stream.readFully(data, 0, byteCount);
                    lzwDecoder.decode(data, bdata, newRect.height);

                else if (compression == COMP_DEFLATE) {

                    stream.readFully(data, 0, byteCount);
                    inflate(data, bdata);

                } else {

                    stream.readFully(bdata, 0, byteCount);
                }

                stream.seek(save_offset);
      } catch (IOException ioe) {
                String message = JaiI18N.getString("TIFFImage13");
                ImagingListenerProxy.errorOccurred(message,
                                       new ImagingException(message, ioe),
                                       this, false);
//    throw new RuntimeException(JaiI18N.getString("TIFFImage13"));
      }
        } else { // everything else
      try {

    if (sampleSize == 8) {

        if (compression == COMP_NONE) {

      stream.readFully(bdata, 0, byteCount);

        } else if (compression == COMP_LZW) {

      stream.readFully(data, 0, byteCount);
      lzwDecoder.decode(data, bdata, newRect.height);

        } else if (compression == COMP_PACKBITS) {

      stream.readFully(data, 0, byteCount);
      decodePackbits(data, unitsInThisTile, bdata);

        } else if (compression == COMP_JPEG_TTN2) {

      stream.readFully(data, 0, byteCount);
                        tile.setRect(decodeJPEG(data,
                                                decodeParam,
                                                colorConvertJPEG,
                                                tile.getMinX(),
                                                tile.getMinY()));
        } else if (compression == COMP_DEFLATE) {

      stream.readFully(data, 0, byteCount);
                        inflate(data, bdata);
                    }

    } else if (sampleSize == 16) {

        if (compression == COMP_NONE) {

      readShorts(byteCount/2, sdata);

        } else if (compression == COMP_LZW) {

      stream.readFully(data, 0, byteCount);

      // Since unitsInThisTile is the number of shorts,
      // but we do our decompression in terms of bytes, we
      // need to multiply unitsInThisTile by 2 in order to
      // figure out how many bytes we'll get after
      // decompression.
      byte byteArray[] = new byte[unitsInThisTile * 2];
      lzwDecoder.decode(data, byteArray, newRect.height);
      interpretBytesAsShorts(byteArray, sdata,
                 unitsInThisTile);

        } else if (compression == COMP_PACKBITS) {

      stream.readFully(data, 0, byteCount);

      // Since unitsInThisTile is the number of shorts,
      // but we do our decompression in terms of bytes, we
      // need to multiply unitsInThisTile by 2 in order to
      // figure out how many bytes we'll get after
      // decompression.
      int bytesInThisTile = unitsInThisTile * 2;

      byte byteArray[] = new byte[bytesInThisTile];
      decodePackbits(data, bytesInThisTile, byteArray);
      interpretBytesAsShorts(byteArray, sdata,
                 unitsInThisTile);
        } else if (compression == COMP_DEFLATE) {

      stream.readFully(data, 0, byteCount);
      byte byteArray[] = new byte[unitsInThisTile * 2];
      inflate(data, byteArray);
      interpretBytesAsShorts(byteArray, sdata,
                 unitsInThisTile);

        }
    } else if (sampleSize == 32 &&
                           dataType == DataBuffer.TYPE_INT) { // redundant
        if (compression == COMP_NONE) {

      readInts(byteCount/4, idata);

        } else if (compression == COMP_LZW) {

      stream.readFully(data, 0, byteCount);

      // Since unitsInThisTile is the number of ints,
      // but we do our decompression in terms of bytes, we
      // need to multiply unitsInThisTile by 4 in order to
      // figure out how many bytes we'll get after
      // decompression.
      byte byteArray[] = new byte[unitsInThisTile * 4];
      lzwDecoder.decode(data, byteArray, newRect.height);
      interpretBytesAsInts(byteArray, idata,
                                             unitsInThisTile);

        } else if (compression == COMP_PACKBITS) {

      stream.readFully(data, 0, byteCount);

      // Since unitsInThisTile is the number of ints,
      // but we do our decompression in terms of bytes, we
      // need to multiply unitsInThisTile by 4 in order to
      // figure out how many bytes we'll get after
      // decompression.
      int bytesInThisTile = unitsInThisTile * 4;

      byte byteArray[] = new byte[bytesInThisTile];
      decodePackbits(data, bytesInThisTile, byteArray);
      interpretBytesAsInts(byteArray, idata,
                                             unitsInThisTile);
        } else if (compression == COMP_DEFLATE) {

      stream.readFully(data, 0, byteCount);
      byte byteArray[] = new byte[unitsInThisTile * 4];
      inflate(data, byteArray);
      interpretBytesAsInts(byteArray, idata,
                                             unitsInThisTile);

                    }
    } else if (sampleSize == 32 &&
                           dataType == DataBuffer.TYPE_FLOAT) { // redundant
        if (compression == COMP_NONE) {

      readFloats(byteCount/4, fdata);

        } else if (compression == COMP_LZW) {

      stream.readFully(data, 0, byteCount);

      // Since unitsInThisTile is the number of floats,
      // but we do our decompression in terms of bytes, we
      // need to multiply unitsInThisTile by 4 in order to
      // figure out how many bytes we'll get after
      // decompression.
      byte byteArray[] = new byte[unitsInThisTile * 4];
      lzwDecoder.decode(data, byteArray, newRect.height);
      interpretBytesAsFloats(byteArray, fdata,
                                               unitsInThisTile);

        } else if (compression == COMP_PACKBITS) {

      stream.readFully(data, 0, byteCount);

      // Since unitsInThisTile is the number of floats,
      // but we do our decompression in terms of bytes, we
      // need to multiply unitsInThisTile by 4 in order to
      // figure out how many bytes we'll get after
      // decompression.
      int bytesInThisTile = unitsInThisTile * 4;

      byte byteArray[] = new byte[bytesInThisTile];
      decodePackbits(data, bytesInThisTile, byteArray);
      interpretBytesAsFloats(byteArray, fdata,
                                               unitsInThisTile);
        } else if (compression == COMP_DEFLATE) {

      stream.readFully(data, 0, byteCount);
      byte byteArray[] = new byte[unitsInThisTile * 4];
                        inflate(data, byteArray);
      interpretBytesAsFloats(byteArray, fdata,
                                               unitsInThisTile);

                    }
    }

    stream.seek(save_offset);

      } catch (IOException ioe) {
                String message = JaiI18N.getString("TIFFImage13");
                ImagingListenerProxy.errorOccurred(message,
                                       new ImagingException(message, ioe),
                                       this, false);
//    throw new RuntimeException(JaiI18N.getString("TIFFImage13"));
      }

            // Modify the data for certain special cases.
            switch(imageType) {
            case TYPE_GRAY:
            case TYPE_GRAY_ALPHA:
                if(isWhiteZero) {
                    // Since we are using a ComponentColorModel with this
                    // image, we need to change the WhiteIsZero data to
                    // BlackIsZero data so it will display properly.
                    if (dataType == DataBuffer.TYPE_BYTE &&
                        !(colorModel instanceof IndexColorModel)) {

                        for (int l = 0; l < bdata.length; l += numBands) {
                            bdata[l] = (byte)(255 - bdata[l]);
                        }
                    } else if (dataType == DataBuffer.TYPE_USHORT) {

                        int ushortMax = Short.MAX_VALUE - Short.MIN_VALUE;
                        for (int l = 0; l < sdata.length; l += numBands) {
                            sdata[l] = (short)(ushortMax - sdata[l]);
                        }

                    } else if (dataType == DataBuffer.TYPE_SHORT) {

                        for (int l = 0; l < sdata.length; l += numBands) {
                            sdata[l] = (short)(~sdata[l]);
                        }
                    } else if (dataType == DataBuffer.TYPE_INT) {

                        long uintMax = Integer.MAX_VALUE - Integer.MIN_VALUE;
                        for (int l = 0; l < idata.length; l += numBands) {
                            idata[l] = (int)(uintMax - (long)idata[l]);
                        }
                    }
                }
                break;
            case TYPE_YCBCR_SUB:
                // Post-processing for YCbCr with subsampled chrominance:
                // simply replicate the chroma channels for displayability.
                int pixelsPerDataUnit = chromaSubH*chromaSubV;

                int numH = newRect.width/chromaSubH;
                int numV = newRect.height/chromaSubV;

                byte[] tempData = new byte[numH*numV*(pixelsPerDataUnit + 2)];
                System.arraycopy(bdata, 0, tempData, 0, tempData.length);

                int samplesPerDataUnit = pixelsPerDataUnit*3;
                int[] pixels = new int[samplesPerDataUnit];

                int bOffset = 0;
                int offsetCb = pixelsPerDataUnit;
                int offsetCr = offsetCb + 1;

                int y = newRect.y;
                for(int j = 0; j < numV; j++) {
                    int x = newRect.x;
                    for(int i = 0; i < numH; i++) {
                        int Cb = tempData[bOffset + offsetCb];
                        int Cr = tempData[bOffset + offsetCr];
                        int k = 0;
                        while(k < samplesPerDataUnit) {
                            pixels[k++] = tempData[bOffset++];
                            pixels[k++] = Cb;
                            pixels[k++] = Cr;
                        }
                        bOffset += 2;
                        tile.setPixels(x, y, chromaSubH, chromaSubV, pixels);
                        x += chromaSubH;
                    }
                    y += chromaSubV;
                }

View Full Code Here

Examples of java.awt.image.WritableRaster

                    catch (Exception e) {
                        // ignore
                    }
                }

                WritableRaster raster = bi.getRaster();
                DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
                ThemeReader.paintBackground(buffer.getData(),
                        part.getControlName(c), part.getValue(),
                        TMSchema.State.getValue(part, state),
                        0, 0, w, h, w);

                if (sm.getClass().getName().equals("sun.awt.image.CachingSurfaceManager")) {
                    try {
                        boolean oldAccEnabled = (Boolean) ReflectionUtils.callGet(sm, "isLocalAccelerationEnabled");
                        if (accEnabled != oldAccEnabled) {
                            ReflectionUtils.callSet(sm, "setLocalAccelerationEnabled", accEnabled);
                            ReflectionUtils.call(sm, "rasterChanged");
                        }
                    }
                    catch (Exception e) {
                        // ignore
                    }
                }
            }
            else // copied from JDK7 XPStyle. To make the code compilable under JDk6, we use RefectionUtils
                boolean accEnabled = false;
                Skin skin = (Skin) args[0];
                Part part = skin.part;
                State state = (State) args[1];
                if (state == null) {
                    state = skin.state;
                }
                if (c == null) {
                    c = skin.component;
                }
                BufferedImage bi = (BufferedImage) image;

                WritableRaster raster = bi.getRaster();
                DataBufferInt dbi = (DataBufferInt) raster.getDataBuffer();
                // Note that stealData() requires a markDirty() afterwards
                // since we modify the data in it.
                try {
                    ThemeReader.paintBackground(
                            (int[]) ReflectionUtils.callStatic(SunWritableRaster.class, "stealData", new Class[]{DataBufferInt.class, int.class}, new Object[]{dbi, 0}),
View Full Code Here

Examples of java.awt.image.WritableRaster

        int historyIdx;

        int aSum;

        ColorModel srcColorModel = src.getColorModel();
        WritableRaster srcRaster = src.getRaster();
        int[] dstBuffer = ((DataBufferInt) dst.getRaster().getDataBuffer()).getData();

        int lastPixelOffset = right * dstWidth;
        float hSumDivider = 1.0f / size;
        float vSumDivider = opacity / size;

        // horizontal pass : extract the alpha mask from the source picture and
        // blur it into the destination picture
        for (int srcY = 0, dstOffset = left * dstWidth; srcY < srcHeight; srcY++) {

            // first pixels are empty
            for (historyIdx = 0; historyIdx < shadowSize; ) {
                aHistory[historyIdx++] = 0;
            }

            aSum = 0;
            historyIdx = 0;

            // compute the blur average with pixels from the source image
            for (int srcX = 0; srcX < srcWidth; srcX++) {

                int a = (int) (aSum * hSumDivider); // calculate alpha value
                dstBuffer[dstOffset++] = a << 24;   // store the alpha value only
                                                    // the shadow color will be added in the next pass

                aSum -= aHistory[historyIdx]; // substract the oldest pixel from the sum

                // extract the new pixel ...
                a = srcColorModel.getAlpha(srcRaster.getDataElements(srcX, srcY, null));
                aHistory[historyIdx] = a;   // ... and store its value into history
                aSum += a;                  // ... and add its value to the sum

                if (++historyIdx >= shadowSize) {
                    historyIdx -= shadowSize;
View Full Code Here

Examples of java.awt.image.WritableRaster

            }
            PaletteData palette = new PaletteData(rgbs);
            ImageData data = new ImageData(
                image.getWidth(), image.getHeight(), cmodel.getPixelSize(), palette);
            data.transparentPixel = cmodel.getTransparentPixel();
            WritableRaster raster = image.getRaster();
            int[] pixelArray = new int[1];
            for (int y = 0; y < data.height; y++) {
                for (int x = 0; x < data.width; x++) {
                    raster.getPixel(x, y, pixelArray);
                    data.setPixel(x, y, pixelArray[0]);
                }
            }
            return data;
        } else if (image.getColorModel() instanceof ComponentColorModel) {
            ComponentColorModel cmodel = (ComponentColorModel)image.getColorModel();
            PaletteData palette = new PaletteData(0x0000FF, 0x00FF00, 0xFF0000); // BGR
            ImageData data = new ImageData(image.getWidth(), image.getHeight(), 24, palette);
            if (cmodel.hasAlpha()) data.alphaData = new byte[image.getWidth() * image.getHeight()];
            WritableRaster raster = image.getRaster();
            int[] pixelArray = new int[4];
            for (int y = 0; y < data.height; y++) {
                for (int x = 0; x < data.width; x++) {
                    raster.getPixel(x, y, pixelArray);
                    data.setPixel(x, y,
                        (pixelArray[2] << 16) | (pixelArray[1] << 8) | (pixelArray[0]));
                    if (data.alphaData != null)
                        data.alphaData[y*data.width + x] = (byte)pixelArray[3];
                }
View Full Code Here

Examples of java.awt.image.WritableRaster

    public Raster computeTile(int tileX, int tileY) {
        /* The origin of the tile. */
        Point org = new Point(tileXToX(tileX), tileYToY(tileY));

        /* Create a new WritableRaster to represent this tile. */
        WritableRaster dest = createWritableRaster(sampleModel, org);

        /* Find the intersection between this tile and the writable bounds. */
        Rectangle rect0 = new Rectangle(org.x, org.y, tileWidth, tileHeight);
        Rectangle destRect = rect0.intersection(computableBounds);
        Rectangle destRect1 = rect0.intersection(getBounds());
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.