Example usage for java.awt.image DataBuffer TYPE_BYTE

List of usage examples for java.awt.image DataBuffer TYPE_BYTE

Introduction

In this page you can find the example usage for java.awt.image DataBuffer TYPE_BYTE.

Prototype

int TYPE_BYTE

To view the source code for java.awt.image DataBuffer TYPE_BYTE.

Click Source Link

Document

Tag for unsigned byte data.

Usage

From source file:com.embedler.moon.jtxt2img.mmap.MappedFileBuffer.java

private MappedFileBuffer(final int type, final int size, final int numBanks) {
    super(type, size, numBanks);

    Validate.isTrue(size >= 0, "Integer overflow for size: %d", size);
    Validate.isTrue(numBanks >= 0, "Number of banks must be positive", numBanks);

    int componentSize = DataBuffer.getDataTypeSize(type) / 8;

    try {//from   www  .j a va  2 s  .  co m
        tempFile = File.createTempFile(String.format("%s-", getClass().getSimpleName().toLowerCase()), ".tmp");
        try (RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
                FileChannel channel = raf.getChannel()) {

            long length = ((long) size) * componentSize * numBanks;
            raf.setLength(length);

            byteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, length);

            switch (type) {
            case DataBuffer.TYPE_BYTE:
                buffer = byteBuffer;
                break;
            case DataBuffer.TYPE_USHORT:
                buffer = byteBuffer.asShortBuffer();
                break;
            case DataBuffer.TYPE_INT:
                buffer = byteBuffer.asIntBuffer();
                break;
            default:
                throw new IllegalArgumentException("Unsupported data type: " + type);
            }
        } finally {
            if (!tempFile.delete()) {
                tempFile.deleteOnExit();
            }
        }
    } catch (Exception e) {
        throw new JTxt2ImgIoRuntimeException(e);
    }
}

From source file:com.googlecode.fightinglayoutbugs.helpers.ImageHelper.java

public static int[][] imageToPixels(BufferedImage image) {
    if (image == null) {
        return null;
    }/*from   w w w .  j a  v  a  2  s  .c om*/
    int w = image.getWidth();
    int h = image.getHeight();
    int[][] pixels = new int[w][h];
    Raster raster = image.getRaster();
    if (raster.getTransferType() == DataBuffer.TYPE_BYTE) {
        byte[] bytes = (byte[]) raster.getDataElements(0, 0, w, h, null);
        int bytesPerPixel = (bytes.length / (w * h));
        ColorModel colorModel = image.getColorModel();
        byte[] buf = new byte[bytesPerPixel];
        for (int x = 0; x < w; ++x) {
            for (int y = 0; y < h; ++y) {
                System.arraycopy(bytes, (x + y * w) * bytesPerPixel, buf, 0, bytesPerPixel);
                pixels[x][y] = colorModel.getRGB(buf) & 0xFFFFFF;
            }
        }
        return pixels;
    } else {
        throw new RuntimeException("transfer type " + raster.getTransferType() + " not implemented yet");
    }
}

From source file:org.mrgeo.cmd.mrsimageinfo.MrsImageInfo.java

private static void printTileType(final MrsPyramidMetadata metadata) {
    System.out.print("Type: ");
    switch (metadata.getTileType()) {
    case DataBuffer.TYPE_BYTE:
        System.out.println("byte");
        break;//from www  .ja  v a  2s .c o m
    case DataBuffer.TYPE_FLOAT:
        System.out.println("float");
        break;
    case DataBuffer.TYPE_DOUBLE:
        System.out.println("double");
        break;
    case DataBuffer.TYPE_INT:
        System.out.println("int");
        break;
    case DataBuffer.TYPE_SHORT:
        System.out.println("short");
        break;
    case DataBuffer.TYPE_USHORT:
        System.out.println("unsigned short");
        break;
    default:
        break;
    }
}

From source file:ch5ImageReader.java

/**
 * this method provides suggestions for possible image types that will be
 * used to decode the image specified by index imageIndex. By default, the
 * first image type returned by this method will be the image type of the
 * BufferedImage returned by the ImageReader's getDestination method. In
 * this case, we are suggesting using an 8 bit grayscale image with no alpha
 * component.//  www .  j  a v a2s . c  o m
 */
public Iterator getImageTypes(int imageIndex) {
    java.util.List l = new java.util.ArrayList();
    ;
    int bits = 8;

    /*
     * can convert ch5 format into 8 bit grayscale image with no alpha
     */
    l.add(ImageTypeSpecifier.createGrayscale(bits, DataBuffer.TYPE_BYTE, false));
    return l.iterator();
}

From source file:org.mrgeo.image.ImageStats.java

/**
 * Computes pixel value statistics: min, max, sum, count, & mean for a Raster and returns an array
 * of ImageStats objects, one for each band in the image.
 * /*from   w  ww .  j ava 2  s .  co m*/
 * @param raster
 *          the raster to compute stats for
 * @param nodata
 *          the value to ignore
 * @return an array of ImageStats objects
 */
static public void computeAndUpdateStats(final ImageStats[] tileStats, final Raster raster,
        final double[] nodata) throws RasterWritableException {
    final int type = raster.getTransferType();
    Number sample;
    for (int y = 0; y < raster.getHeight(); y++) {
        for (int x = 0; x < raster.getWidth(); x++) {
            for (int b = 0; b < raster.getNumBands(); b++) {
                switch (type) {
                case DataBuffer.TYPE_BYTE:
                case DataBuffer.TYPE_INT:
                case DataBuffer.TYPE_SHORT:
                case DataBuffer.TYPE_USHORT:
                    sample = raster.getSample(x, y, b);
                    break;
                case DataBuffer.TYPE_FLOAT:
                    sample = raster.getSampleFloat(x, y, b);
                    break;
                case DataBuffer.TYPE_DOUBLE:
                    sample = raster.getSampleDouble(x, y, b);
                    break;
                default:
                    throw new RasterWritableException(
                            "Error computing tile statistics. Unsupported raster data type");
                }
                updateStats(tileStats[b], sample, nodata[b]);
            }
        }
    }

}

From source file:omr.jai.RGBToBilevel.java

RGBToBilevel(final String fileName, boolean isErrorDiffusion) {

    // Load the file.
    PlanarImage src = JAI.create("fileload", fileName);

    // Load the ParameterBlock for the dithering operation
    // and set the operation name.
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(src);//from  www  . ja va2  s  . co m
    String opName = null;
    if (isErrorDiffusion) {
        opName = "errordiffusion";
        LookupTableJAI lut = new LookupTableJAI(new byte[][] { { (byte) 0x00, (byte) 0xff },
                { (byte) 0x00, (byte) 0xff }, { (byte) 0x00, (byte) 0xff } });
        pb.add(lut);
        pb.add(KernelJAI.ERROR_FILTER_FLOYD_STEINBERG);
    } else {
        opName = "ordereddither";
        ColorCube cube = ColorCube.createColorCube(DataBuffer.TYPE_BYTE, 0, new int[] { 2, 2, 2 });
        pb.add(cube);
        pb.add(KernelJAI.DITHER_MASK_443);
    }

    // Create a layout containing an IndexColorModel which maps
    // zero to zero and unity to 255; force SampleModel to be bilevel.
    ImageLayout layout = new ImageLayout();
    byte[] map = new byte[] { (byte) 0x00, (byte) 0xff };
    ColorModel cm = new IndexColorModel(1, 2, map, map, map);
    layout.setColorModel(cm);
    SampleModel sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, src.getWidth(), src.getHeight(), 1);
    layout.setSampleModel(sm);

    // Create a hint containing the layout.
    RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);

    // Dither the image.
    final PlanarImage dst = JAI.create(opName, pb, hints);

    // Exit on window closing.
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            JAI.create("filestore", dst, fileName + ".out", "PNG", null);
            System.exit(0);
        }
    });

    // Display the result.
    //// ATTENTION A REMPLACER : add(new ScrollingImagePanel(dst, dst.getWidth(), dst.getHeight()));
    pack();
    setVisible(true);
}

From source file:org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap.java

private void createImageStream(PDDocument doc, BufferedImage bi) throws IOException {
    BufferedImage alphaImage = null;
    BufferedImage rgbImage = null;
    int width = bi.getWidth();
    int height = bi.getHeight();
    if (bi.getColorModel().hasAlpha()) {
        // extract the alpha information
        WritableRaster alphaRaster = bi.getAlphaRaster();
        ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false,
                Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
        alphaImage = new BufferedImage(cm, alphaRaster, false, null);
        // create a RGB image without alpha
        rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = rgbImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.drawImage(bi, 0, 0, null);/*from   ww  w .  jav  a 2  s .  c om*/
    } else {
        rgbImage = bi;
    }
    java.io.OutputStream os = null;
    try {
        int numberOfComponents = rgbImage.getColorModel().getNumComponents();
        if (numberOfComponents == 3) {
            setColorSpace(PDDeviceRGB.INSTANCE);
        } else {
            if (numberOfComponents == 1) {
                setColorSpace(new PDDeviceGray());
            } else {
                throw new IllegalStateException();
            }
        }
        byte[] outData = new byte[width * height * numberOfComponents];
        rgbImage.getData().getDataElements(0, 0, width, height, outData);
        // add FlateDecode compression
        getPDStream().addCompression();
        os = getCOSStream().createUnfilteredStream();
        os.write(outData);

        COSDictionary dic = getCOSStream();
        dic.setItem(COSName.FILTER, COSName.FLATE_DECODE);
        dic.setItem(COSName.SUBTYPE, COSName.IMAGE);
        dic.setItem(COSName.TYPE, COSName.XOBJECT);
        if (alphaImage != null) {
            PDPixelMap smask = new PDPixelMap(doc, alphaImage);
            dic.setItem(COSName.SMASK, smask);
        }
        setBitsPerComponent(8);
        setHeight(height);
        setWidth(width);
    } finally {
        os.close();
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.image.SampledImageReader.java

/**
 * Returns the content of the given image as an AWT buffered image with an RGB color space.
 * If a color key mask is provided then an ARGB image is returned instead.
 * This method never returns null.// w w w.  j a v a 2  s. c o  m
 * @param pdImage the image to read
 * @param colorKey an optional color key mask
 * @return content of this image as an RGB buffered image
 * @throws IOException if the image cannot be read
 */
public static BufferedImage getRGBImage(PDImage pdImage, COSArray colorKey) throws IOException {
    if (pdImage.isEmpty()) {
        throw new IOException("Image stream is empty");
    }

    // get parameters, they must be valid or have been repaired
    final PDColorSpace colorSpace = pdImage.getColorSpace();
    final int numComponents = colorSpace.getNumberOfComponents();
    final int width = pdImage.getWidth();
    final int height = pdImage.getHeight();
    final int bitsPerComponent = pdImage.getBitsPerComponent();
    final float[] decode = getDecodeArray(pdImage);

    //
    // An AWT raster must use 8/16/32 bits per component. Images with < 8bpc
    // will be unpacked into a byte-backed raster. Images with 16bpc will be reduced
    // in depth to 8bpc as they will be drawn to TYPE_INT_RGB images anyway. All code
    // in PDColorSpace#toRGBImage expects and 8-bit range, i.e. 0-255.
    //
    WritableRaster raster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE, width, height, numComponents,
            new Point(0, 0));

    // convert image, faster path for non-decoded, non-colormasked 8-bit images
    final float[] defaultDecode = pdImage.getColorSpace().getDefaultDecode(8);
    if (bitsPerComponent == 8 && Arrays.equals(decode, defaultDecode) && colorKey == null) {
        return from8bit(pdImage, raster);
    } else if (bitsPerComponent == 1 && colorKey == null) {
        return from1Bit(pdImage, raster);
    } else {
        return fromAny(pdImage, raster, colorKey);
    }
}

From source file:org.mrgeo.image.MrsImagePyramidMetadata.java

public static int toBytes(final int tiletype) {
    switch (tiletype) {
    case DataBuffer.TYPE_BYTE: {
        return 1;
    }//from ww  w .  j ava 2 s .  co  m
    case DataBuffer.TYPE_FLOAT: {
        return RasterUtils.FLOAT_BYTES;
    }
    case DataBuffer.TYPE_DOUBLE: {
        return RasterUtils.DOUBLE_BYTES;
    }
    case DataBuffer.TYPE_INT: {
        return RasterUtils.INT_BYTES;
    }
    case DataBuffer.TYPE_SHORT: {
        return RasterUtils.SHORT_BYTES;
    }
    case DataBuffer.TYPE_USHORT: {
        return RasterUtils.USHORT_BYTES;
    }
    }

    return 0;
}

From source file:com.bc.ceres.jai.opimage.ReinterpretOpImage.java

private void rescale(Raster sourceRaster, WritableRaster targetRaster, Rectangle targetRectangle) {
    final int sourceDataType = sourceRaster.getSampleModel().getDataType();
    final int targetDataType = targetRaster.getSampleModel().getDataType();
    final PixelAccessor sourceAcc = new PixelAccessor(getSourceImage(0));
    final PixelAccessor targetAcc = new PixelAccessor(this);
    final UnpackedImageData sourcePixels;
    final UnpackedImageData targetPixels;

    sourcePixels = sourceAcc.getPixels(sourceRaster, targetRectangle, sourceDataType, false);
    targetPixels = targetAcc.getPixels(targetRaster, targetRectangle, targetDataType, true);

    switch (sourceDataType) {
    case DataBuffer.TYPE_BYTE:
        if (interpretationType == ReinterpretDescriptor.INTERPRET_BYTE_SIGNED) {
            rescaleSByte(sourcePixels, targetPixels, targetRectangle);
        } else {//w  w  w  . j av  a  2s . com
            rescaleByte(sourcePixels, targetPixels, targetRectangle);
        }
        break;
    case DataBuffer.TYPE_USHORT:
        rescaleUShort(sourcePixels, targetPixels, targetRectangle);
        break;
    case DataBuffer.TYPE_SHORT:
        rescaleShort(sourcePixels, targetPixels, targetRectangle);
        break;
    case DataBuffer.TYPE_INT:
        if (interpretationType == ReinterpretDescriptor.INTERPRET_INT_UNSIGNED) {
            rescaleUInt(sourcePixels, targetPixels, targetRectangle);
        } else {
            rescaleInt(sourcePixels, targetPixels, targetRectangle);
        }
        break;
    case DataBuffer.TYPE_FLOAT:
        rescaleFloat(sourcePixels, targetPixels, targetRectangle);
        break;
    case DataBuffer.TYPE_DOUBLE:
        rescaleDouble(sourcePixels, targetPixels, targetRectangle);
        break;
    }

    targetAcc.setPixels(targetPixels);
}