Example usage for java.awt.image DataBufferByte getData

List of usage examples for java.awt.image DataBufferByte getData

Introduction

In this page you can find the example usage for java.awt.image DataBufferByte getData.

Prototype

public byte[] getData() 

Source Link

Document

Returns the default (first) byte data array.

Usage

From source file:com.neophob.sematrix.core.generator.Textwriter.java

/**
 * create image./*w  w  w  .j  a  v a 2 s.co m*/
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    //head and tailing space
    maxXPos = (int) (0.5f + rect.getWidth()) + 2 * internalBufferXSize;
    int ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_BYTE_GRAY);
    g2 = img.createGraphics();

    g2.setColor(new Color(128));
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);

    g2.drawString(text, internalBufferXSize, ypos);
    DataBufferByte dbi = (DataBufferByte) img.getRaster().getDataBuffer();
    byte[] textBuffer = dbi.getData();
    g2.dispose();

    xofs = 0;

    textAsImage = new int[maxXPos * internalBufferYSize];
    for (int i = 0; i < textAsImage.length; i++) {
        if (textBuffer[i] > 10) {
            textAsImage[i] = 127;
        } else {
            textAsImage[i] = 0;
        }
    }

    //clear internalbuffer
    Arrays.fill(this.internalBuffer, 0);
}

From source file:it.geosolutions.imageio.plugins.nitronitf.NITFImageWriter.java

/**
 * Do the real write operation (writing images, texts, ...)
 * //  w  ww  . j av  a2s. co  m
 * @param record
 * @param images
 * @param shp
 * @param fis
 * @param text
 * @return
 * @throws NITFException
 * @throws IOException
 */
private boolean writeNITF(final Record record, final List<ImageWrapper> images, final ShapeFileWrapper shp,
        final FileImageInputStreamExt fis, final List<TextWrapper> texts) throws NITFException, IOException {
    final int numImages = images.size();
    ImageWrapper image = images.get(0);
    RenderedImage ri = image.getImage();
    WriteCompression compression = image.getCompression();
    int nBands = ri.getSampleModel().getNumBands();
    boolean written = false;
    Writer writer = new Writer();
    IOHandle handle = new IOHandle(outputFile.getCanonicalPath(), IOHandle.NITF_ACCESS_WRITEONLY,
            IOHandle.NITF_CREATE);

    byte[] shapeFileData = null;
    final boolean isJP2 = !(compression == WriteCompression.UNCOMPRESSED);
    if (shp != null) {
        shapeFileData = getShapeData(record, shp);
    }

    boolean prepared = false;
    if (isJP2) {
        // //
        //
        // get the JP2 Codestream previously written with Kakadu and transfer its content within
        // the NITF imageSegment
        //
        // //
        WriteHandler codeStream = null;
        IOInterface io;
        final int size = (int) fis.length();
        io = new IOFileInputStream(fis);

        writer.prepare(record, handle);

        if (shapeFileData != null) {
            writeData(shapeFileData, writer);
        }

        codeStream = new StreamIOWriteHandler(io, 0, size);
        writer.setImageWriteHandler(0, codeStream);
        prepared = true;

    }
    if (!isJP2 || numImages > 1) {

        if (!prepared) {
            writer.prepare(record, handle);
        }

        if (numImages == 1) {

            // setup a Writer
            if (shapeFileData != null) {
                writeData(shapeFileData, writer);
            }

            ImageSource imageSource = new ImageSource();
            nitf.ImageWriter imageWriter = writer.getNewImageWriter(0);
            boolean[] successes = new boolean[nBands];
            final boolean isMono = images.get(0).getImage().getSampleModel().getNumBands() == 1;
            if (isMono) {
                DataBufferByte dbb = (DataBufferByte) ri.getData().getDataBuffer();
                BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
                successes[0] = imageSource.addBand(bs);
            } else {
                for (int i = 0; i < nBands; i++) {
                    RenderedImage band = BandSelectDescriptor.create(ri, new int[] { i }, null);
                    DataBufferByte dbb = (DataBufferByte) band.getData().getDataBuffer();
                    BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
                    successes[i] = imageSource.addBand(bs);
                }
            }

            imageWriter.attachSource(imageSource);
        } else {
            ImageWrapper img = images.get(1);
            ri = img.getImage();
            nBands = ri.getSampleModel().getNumBands();
            ImageSource imageSource = new ImageSource();
            nitf.ImageWriter imageWriter2 = writer.getNewImageWriter(1);
            boolean[] successes = new boolean[nBands];
            DataBufferByte dbb = (DataBufferByte) ri.getData().getDataBuffer();
            BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
            successes[0] = imageSource.addBand(bs);
            imageWriter2.attachSource(imageSource);
        }

    }

    // Adding text
    if (texts != null && !texts.isEmpty()) {
        int i = 0;
        for (TextWrapper text : texts) {
            byte[] textContent = text.getTextContent();
            if (textContent != null) {
                SegmentWriter textWriter = writer.getNewTextWriter(i++);
                SegmentSource source = SegmentSource.makeSegmentMemorySource(textContent, textContent.length, 0,
                        0);
                textWriter.attachSource(source);
            }
        }
    }

    written = writer.write();
    if (handle != null) {
        handle.close();
    }

    return written;
}

From source file:org.apache.fop.render.pcl.PCLGenerator.java

/**
 * Paint a bitmap at the current cursor position. The bitmap must be a monochrome
 * (1-bit) bitmap image./*from   w  w  w .  j a v a2  s . c om*/
 * @param img the bitmap image (must be 1-bit b/w)
 * @param resolution the resolution of the image (must be a PCL resolution)
 * @throws IOException In case of an I/O error
 */
public void paintMonochromeBitmap(RenderedImage img, int resolution) throws IOException {
    if (!isValidPCLResolution(resolution)) {
        throw new IllegalArgumentException("Invalid PCL resolution: " + resolution);
    }
    boolean monochrome = isMonochromeImage(img);
    if (!monochrome) {
        throw new IllegalArgumentException("img must be a monochrome image");
    }

    setRasterGraphicsResolution(resolution);
    writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A");
    Raster raster = img.getData();

    Encoder encoder = new Encoder(img);
    // Transfer graphics data
    int imgw = img.getWidth();
    IndexColorModel cm = (IndexColorModel) img.getColorModel();
    if (cm.getTransferType() == DataBuffer.TYPE_BYTE) {
        DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
        MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
                img.getWidth(), img.getHeight(), 1);
        if (img.getSampleModel().equals(packedSampleModel) && dataBuffer.getNumBanks() == 1) {
            //Optimized packed encoding
            byte[] buf = dataBuffer.getData();
            int scanlineStride = packedSampleModel.getScanlineStride();
            int idx = 0;
            int c0 = toGray(cm.getRGB(0));
            int c1 = toGray(cm.getRGB(1));
            boolean zeroIsWhite = c0 > c1;
            for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
                for (int x = 0, maxx = scanlineStride; x < maxx; x++) {
                    if (zeroIsWhite) {
                        encoder.add8Bits(buf[idx]);
                    } else {
                        encoder.add8Bits((byte) ~buf[idx]);
                    }
                    idx++;
                }
                encoder.endLine();
            }
        } else {
            //Optimized non-packed encoding
            for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
                byte[] line = (byte[]) raster.getDataElements(0, y, imgw, 1, null);
                for (int x = 0, maxx = imgw; x < maxx; x++) {
                    encoder.addBit(line[x] == 0);
                }
                encoder.endLine();
            }
        }
    } else {
        //Safe but slow fallback
        for (int y = 0, maxy = img.getHeight(); y < maxy; y++) {
            for (int x = 0, maxx = imgw; x < maxx; x++) {
                int sample = raster.getSample(x, y, 0);
                encoder.addBit(sample == 0);
            }
            encoder.endLine();
        }
    }

    // End raster graphics
    writeCommand("*rB");
}

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

/**
 * This will take the inlined image information and create a java.awt.Image from
 * it.//w  ww. j a  v a 2s  .co  m
 * 
 * @param colorSpaces The ColorSpace dictionary from the current resources, if any.
 *
 * @return The image that this object represents.
 *
 * @throws IOException If there is an error creating the image.
 */
public BufferedImage createImage(Map colorSpaces) throws IOException {
    /*
     * This was the previous implementation, not sure which is better right now.
     *         byte[] transparentColors = new byte[]{(byte)0xFF,(byte)0xFF};
    byte[] colors=new byte[]{0, (byte)0xFF};
    IndexColorModel colorModel = new IndexColorModel( 1, 2, colors, colors, colors, transparentColors );
    BufferedImage image = new BufferedImage(
    params.getWidth(),
    params.getHeight(),
    BufferedImage.TYPE_BYTE_BINARY,
    colorModel );
    DataBufferByte buffer = new DataBufferByte( getImageData(), 1 );
    WritableRaster raster =
    Raster.createPackedRaster(
        buffer,
        params.getWidth(),
        params.getHeight(),
        params.getBitsPerComponent(),
        new Point(0,0) );
    image.setData( raster );
    return image;
     */

    //verify again pci32.pdf before changing below
    PDColorSpace pcs = params.getColorSpace(colorSpaces);
    ColorModel colorModel;
    if (pcs != null) {
        colorModel = pcs.createColorModel(params.getBitsPerComponent());
    } else {
        byte[] transparentColors = new byte[] { (byte) 0xFF, (byte) 0xFF };
        byte[] colors = new byte[] { 0, (byte) 0xFF };
        colorModel = new IndexColorModel(1, 2, colors, colors, colors, transparentColors);
    }

    boolean invert = false;
    // maybe a decode array is defined
    COSBase dictObj = params.getDictionary().getDictionaryObject(COSName.DECODE, COSName.D);
    if (dictObj != null && dictObj instanceof COSArray) {
        COSArray decode = (COSArray) dictObj;
        if (decode.getInt(0) == 1) {
            if (params.getBitsPerComponent() == 1) {
                // [1.0, 0.0] -> invert the "color" values
                invert = true;
            } else {
                //TODO implement decode array for BPC > 1
                LOG.warn("decode array is not implemented for BPC > 1");
            }
        }
    }

    List filters = params.getFilters();
    byte[] finalData;
    if (filters == null || filters.isEmpty()) {
        finalData = getImageData();
    } else {
        ByteArrayInputStream in = new ByteArrayInputStream(getImageData());
        ByteArrayOutputStream out = new ByteArrayOutputStream(getImageData().length);
        FilterManager filterManager = new FilterManager();
        for (int i = 0; i < filters.size(); i++) {
            out.reset();
            Filter filter = filterManager.getFilter((String) filters.get(i));
            filter.decode(in, out, params.getDictionary(), i);
            in = new ByteArrayInputStream(out.toByteArray());
        }
        finalData = out.toByteArray();
    }

    WritableRaster raster = colorModel.createCompatibleWritableRaster(params.getWidth(), params.getHeight());
    /*    Raster.createPackedRaster(
        buffer,
        params.getWidth(),
        params.getHeight(),
        params.getBitsPerComponent(),
        new Point(0,0) );
        */
    DataBuffer rasterBuffer = raster.getDataBuffer();
    if (rasterBuffer instanceof DataBufferByte) {
        DataBufferByte byteBuffer = (DataBufferByte) rasterBuffer;
        byte[] data = byteBuffer.getData();
        System.arraycopy(finalData, 0, data, 0, data.length);
        if (invert) {
            invertBitmap(data);
        }
    } else if (rasterBuffer instanceof DataBufferInt) {
        DataBufferInt byteBuffer = (DataBufferInt) rasterBuffer;
        int[] data = byteBuffer.getData();
        for (int i = 0; i < finalData.length; i++) {
            data[i] = (finalData[i] + 256) % 256;
            if (invert) {
                data[i] = (~data[i] & 0xFF);
            }
        }
    }
    BufferedImage image = new BufferedImage(colorModel, raster, false, null);
    image.setData(raster);
    return image;
}

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

/**
 * Returns a {@link java.awt.image.BufferedImage} of the COSStream
 * set in the constructor or null if the COSStream could not be encoded.
 *
 * @return {@inheritDoc}/*from   w ww . j  av a  2s . c  o  m*/
 *
 * @throws IOException {@inheritDoc}
 */
public BufferedImage getRGBImage() throws IOException {
    if (image != null) {
        return image;
    }

    try {
        int width = getWidth();
        int height = getHeight();
        int bpc = getBitsPerComponent();

        byte[] array = getPDStream().getByteArray();
        if (array.length == 0) {
            LOG.error("Something went wrong ... the pixelmap doesn't contain any data.");
            return null;
        }
        // Get the ColorModel right
        PDColorSpace colorspace = getColorSpace();
        if (colorspace == null) {
            LOG.error("getColorSpace() returned NULL.  Predictor = " + getPredictor());
            return null;
        }

        ColorModel cm = null;
        if (colorspace instanceof PDIndexed) {
            PDIndexed csIndexed = (PDIndexed) colorspace;
            // the base color space uses 8 bit per component, as the indexed color values
            // of an indexed color space are always in a range from 0 to 255
            ColorModel baseColorModel = csIndexed.getBaseColorSpace().createColorModel(8);
            // number of possible color values in the target color space
            int numberOfColorValues = 1 << bpc;
            // number of indexed color values
            int highValue = csIndexed.getHighValue();
            // choose the correct size, sometimes there are more indexed values than needed
            // and sometimes there are fewer indexed value than possible
            int size = Math.min(numberOfColorValues - 1, highValue);
            byte[] index = csIndexed.getLookupData();
            boolean hasAlpha = baseColorModel.hasAlpha();
            COSBase maskArray = getMask();
            if (baseColorModel.getTransferType() != DataBuffer.TYPE_BYTE) {
                throw new IOException("Not implemented");
            }
            // the IndexColorModel uses RGB-based color values
            // which leads to 3 color components and a optional alpha channel
            int numberOfComponents = 3 + (hasAlpha ? 1 : 0);
            int buffersize = (size + 1) * numberOfComponents;
            byte[] colorValues = new byte[buffersize];
            byte[] inData = new byte[baseColorModel.getNumComponents()];
            int bufferIndex = 0;
            for (int i = 0; i <= size; i++) {
                System.arraycopy(index, i * inData.length, inData, 0, inData.length);
                // convert the indexed color values to RGB 
                colorValues[bufferIndex] = (byte) baseColorModel.getRed(inData);
                colorValues[bufferIndex + 1] = (byte) baseColorModel.getGreen(inData);
                colorValues[bufferIndex + 2] = (byte) baseColorModel.getBlue(inData);
                if (hasAlpha) {
                    colorValues[bufferIndex + 3] = (byte) baseColorModel.getAlpha(inData);
                }
                bufferIndex += numberOfComponents;
            }
            if (maskArray != null && maskArray instanceof COSArray) {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha,
                        ((COSArray) maskArray).getInt(0));
            } else {
                cm = new IndexColorModel(bpc, size + 1, colorValues, 0, hasAlpha);
            }
        } else if (colorspace instanceof PDSeparation) {
            PDSeparation csSeparation = (PDSeparation) colorspace;
            int numberOfComponents = csSeparation.getAlternateColorSpace().getNumberOfComponents();
            PDFunction tintTransformFunc = csSeparation.getTintTransform();
            COSArray decode = getDecode();
            // we have to invert the tint-values,
            // if the Decode array exists and consists of (1,0)
            boolean invert = decode != null && decode.getInt(0) == 1;
            // TODO add interpolation for other decode values then 1,0
            int maxValue = (int) Math.pow(2, bpc) - 1;
            // destination array
            byte[] mappedData = new byte[width * height * numberOfComponents];
            int rowLength = width * numberOfComponents;
            float[] input = new float[1];
            for (int i = 0; i < height; i++) {
                int rowOffset = i * rowLength;
                for (int j = 0; j < width; j++) {
                    // scale tint values to a range of 0...1
                    int value = (array[i * width + j] + 256) % 256;
                    if (invert) {
                        input[0] = 1 - (value / maxValue);
                    } else {
                        input[0] = value / maxValue;
                    }
                    float[] mappedColor = tintTransformFunc.eval(input);
                    int columnOffset = j * numberOfComponents;
                    for (int k = 0; k < numberOfComponents; k++) {
                        // redo scaling for every single color value 
                        float mappedValue = mappedColor[k];
                        mappedData[rowOffset + columnOffset + k] = (byte) (mappedValue * maxValue);
                    }
                }
            }
            array = mappedData;
            cm = colorspace.createColorModel(bpc);
        } else if (bpc == 1) {
            byte[] map = null;
            if (colorspace instanceof PDDeviceGray) {
                COSArray decode = getDecode();
                // we have to invert the b/w-values,
                // if the Decode array exists and consists of (1,0)
                if (decode != null && decode.getInt(0) == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    map = new byte[] { (byte) 0xff };
                } else {
                    map = new byte[] { (byte) 0x00, (byte) 0xff };
                }
            } else {
                map = new byte[] { (byte) 0x00, (byte) 0xff };
            }
            cm = new IndexColorModel(bpc, map.length, map, map, map, Transparency.OPAQUE);
        } else {
            if (colorspace instanceof PDICCBased) {
                if (((PDICCBased) colorspace).getNumberOfComponents() == 1) {
                    byte[] map = new byte[] { (byte) 0xff };
                    cm = new IndexColorModel(bpc, 1, map, map, map, Transparency.OPAQUE);
                } else {
                    cm = colorspace.createColorModel(bpc);
                }
            } else {
                cm = colorspace.createColorModel(bpc);
            }
        }

        LOG.debug("ColorModel: " + cm.toString());
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        byte[] bufferData = buffer.getData();

        System.arraycopy(array, 0, bufferData, 0,
                (array.length < bufferData.length ? array.length : bufferData.length));
        image = new BufferedImage(cm, raster, false, null);

        // If there is a 'soft mask' image then we use that as a transparency mask.
        PDXObjectImage smask = getSMaskImage();
        if (smask != null) {
            BufferedImage smaskBI = smask.getRGBImage();

            COSArray decodeArray = smask.getDecode();

            CompositeImage compositeImage = new CompositeImage(image, smaskBI);
            BufferedImage rgbImage = compositeImage.createMaskedImage(decodeArray);

            return rgbImage;
        } else if (getImageMask()) {
            BufferedImage stencilMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = (Graphics2D) stencilMask.getGraphics();
            if (getStencilColor() != null) {
                graphics.setColor(getStencilColor().getJavaColor());
            } else {
                // this might happen when using ExractImages, see PDFBOX-1145
                LOG.debug("no stencil color for PixelMap found, using Color.BLACK instead.");
                graphics.setColor(Color.BLACK);
            }

            graphics.fillRect(0, 0, width, height);
            // assume default values ([0,1]) for the DecodeArray
            // TODO DecodeArray == [1,0]
            graphics.setComposite(AlphaComposite.DstIn);
            graphics.drawImage(image, null, 0, 0);
            return stencilMask;
        } else {
            // if there is no mask, use the unaltered image.
            return image;
        }
    } catch (Exception exception) {
        LOG.error(exception, exception);
        //A NULL return is caught in pagedrawer.Invoke.process() so don't re-throw.
        //Returning the NULL falls through to Phillip Koch's TODO section.
        return null;
    }
}

From source file:org.jboss.test.selenium.ScreenshotInterceptor.java

public String calculateHash(BufferedImage image) {
    WritableRaster raster = image.getRaster();
    DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
    messageDigest.update(buffer.getData());
    return new BigInteger(1, messageDigest.digest()).toString(16);
}

From source file:org.shaman.terrain.vegetation.ImpositorCreator.java

public static void convertScreenShot(ByteBuffer bgraBuf, BufferedImage out) {
    WritableRaster wr = out.getRaster();
    DataBufferByte db = (DataBufferByte) wr.getDataBuffer();

    byte[] cpuArray = db.getData();

    // copy native memory to java memory
    bgraBuf.clear();//from   w w  w.j  av  a 2  s . co m
    bgraBuf.get(cpuArray);
    bgraBuf.clear();

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

    // flip the components the way AWT likes them

    // calcuate half of height such that all rows of the array are written to
    // e.g. for odd heights, write 1 more scanline
    int heightdiv2ceil = height % 2 == 1 ? (height / 2) + 1 : height / 2;
    for (int y = 0; y < heightdiv2ceil; y++) {
        for (int x = 0; x < width; x++) {
            int inPtr = (y * width + x) * 4;
            int outPtr = ((height - y - 1) * width + x) * 4;

            byte b1 = cpuArray[inPtr + 0];
            byte g1 = cpuArray[inPtr + 1];
            byte r1 = cpuArray[inPtr + 2];
            byte a1 = cpuArray[inPtr + 3];

            byte b2 = cpuArray[outPtr + 0];
            byte g2 = cpuArray[outPtr + 1];
            byte r2 = cpuArray[outPtr + 2];
            byte a2 = cpuArray[outPtr + 3];

            cpuArray[outPtr + 0] = a1;
            cpuArray[outPtr + 1] = r1;//b1;
            cpuArray[outPtr + 2] = g1;
            cpuArray[outPtr + 3] = b1;//r1;

            cpuArray[inPtr + 0] = a2;
            cpuArray[inPtr + 1] = r2;//b2;
            cpuArray[inPtr + 2] = g2;
            cpuArray[inPtr + 3] = b2;//r2;
        }
    }
}