Java java.awt.image.DataBufferByte 代码实例

・29 分钟阅读

以下是展示如何使用java.awt.image.DataBufferByte的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * @param BufferedImage image -- expects BufferedImage.TYPE_3BYTE_BGR
 * @return
 */
public static Mat getMatFromBufferedImage(BufferedImage image)
{
        if (image.getType() != BufferedImage.TYPE_3BYTE_BGR)
                throw new RuntimeException("Exception: getMatFromBufferedImage expects BufferedImage.TYPE_3BYTE_BGR as input");
        DataBufferByte dbi = (DataBufferByte) image.getRaster().getDataBuffer();
        byte[] buff = dbi.getData();
        Mat mat = Mat.zeros(new Size(image.getWidth(), image.getHeight()), CvType.CV_8UC3);
        mat.put(0, 0, buff);
        return mat;
}
 

实例 2


/**
 * returns a byte array containing the binary data from the album cover
 * 
 * @return byte[] cover image
 */
public byte[] getCoverBytes() {
        if( getCover() == null ) return new byte[0];
        WritableRaster raster = getCover().getRaster();
        DataBufferByte buff = (DataBufferByte) raster.getDataBuffer();
        return buff.getData();
}
 

实例 3


private void ok(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ok
{//GEN-HEADEREND:event_ok
        grabDialogValues();
        Cell curCell = WindowFrame.needCurCell();
        if (curCell == null) return;
        // determine the primitive to use for the layout
        NodeProto primNode = Technology.getCurrent().findNodeProto(lastLayer);
        if (primNode == null)
        {
                System.out.println("Cannot find " + lastLayer + " primitive");
                return;
        }
        // get the raster
        int yOffset = 0;
        String [] strings = lastMessage.split("n");
        for(int i=0; i<strings.length; i++)
        {
                String str = strings[i];
                Raster ras = renderText(str, lastFont, lastSize, lastItalic, lastBold, lastUnderline);
                if (ras == null) return;
                DataBufferByte dbb = (DataBufferByte)ras.getDataBuffer();
                byte [] samples = dbb.getData();
                // create the layout text
                new CreateLayoutText(curCell, primNode, lastScale, lastSeparation, ras.getWidth(), ras.getHeight(),
                        yOffset, lastInvertDots, samples);
                yOffset += ras.getHeight();
        }
        closeDialog(null);
}
 

实例 4


/**
 *
 * @todo Write documentation
 * @param texture
 * @param position
 * @since 0.1
 */
public void draw(Texture2D texture, Vector2 position)
{
        GL2 gl = game.getWindow().getCanvas().getGL().getGL2();
        if (gl != null)
        {
                WritableRaster raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texture.getWidth(), texture.getHeight(), 4, null);
                ComponentColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[]
                {
                        8, 8, 8, 8
                }, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);
                Texture2D image = new Texture2D(colorModel, raster, false, null);
                Graphics2D graphics = image.createGraphics();
                graphics.drawImage(texture, null, null);
                DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
                byte[] rgba = dataBuffer.getData();
                ByteBuffer buffer = ByteBuffer.wrap(rgba);
                buffer.position(0);
                buffer.mark();
                gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP);
                gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP);
                gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
                gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
                gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL.GL_REPLACE);
                gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, texture.getWidth(), texture.getHeight(), 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, buffer);
                gl.glEnable(GL.GL_TEXTURE_2D);
                gl.glBindTexture(GL.GL_TEXTURE_2D, 13);
                gl.glBegin(GL2.GL_POLYGON);
                gl.glTexCoord2d(0, 0);
                gl.glVertex2d(position.x, position.y);
                gl.glTexCoord2d(1, 0);
                gl.glVertex2d(position.x + texture.getWidth(), position.y);
                gl.glTexCoord2d(1, 1);
                gl.glVertex2d(position.x + texture.getWidth(), position.y + texture.getHeight());
                gl.glTexCoord2d(0, 1);
                gl.glVertex2d(position.x, position.y + texture.getHeight());
                gl.glEnd();
                gl.glFlush();
        }
}
 

实例 5


public static PImage toPImage(byte [] jpeg_bytes) {
        if (jpeg_bytes == null) return null;
        ByteArrayInputStream bis = new ByteArrayInputStream(jpeg_bytes);
        BufferedImage bufferd_img = null;
        try {
                bufferd_img = ImageIO.read(bis);
                bis.close();
        } catch (IOException e) {
                System.err.println("PImageUtils.toPImage(): ImageIO.read() failed...");
                e.printStackTrace();
                return null;
        }
        int w = bufferd_img.getWidth();
        int h = bufferd_img.getHeight();
        Raster raster = bufferd_img.getRaster();
        DataBufferByte data_buffer = (DataBufferByte) (raster.getDataBuffer());
        byte[] buf = data_buffer.getData();
        PImage pimage = new PImage(w, h, PImage.ARGB);
        for (int y = 0; y < h; ++y) {
                for (int x = 0; x < w; ++x) {
                        int buf_idx = x * 3 + y * w * 3;
                        byte b = buf[buf_idx + 0];
                        byte g = buf[buf_idx + 1];
                        byte r = buf[buf_idx + 2];
                        int c = (b << 0) & 0x000000ff | (g << 8) & 0x0000ff00
                                        | (r << 16) & 0x00ff0000 | (0xff << 24) & 0xff000000;
                        int img_idx = x + y * w;
                        pimage.pixels[img_idx] = c;
                }
        }
        pimage.updatePixels();
        return pimage;
}
 

实例 6


public void readKey8(byte[] in, int offset, int length, BufferedImage img) {
    DataBufferByte buf = (DataBufferByte) img.getRaster().getDataBuffer();
    WritableRaster raster = img.getRaster();
    int scanlineStride = raster.getSampleModel().getWidth();
    Rectangle r = raster.getBounds();
    r.x -= raster.getSampleModelTranslateX();
    r.y -= raster.getSampleModelTranslateY();
    int h=img.getHeight();
    int w=img.getWidth();
    int i=offset;
    int j=r.x+r.y*scanlineStride+(h-1)*scanlineStride;
    byte[] out=buf.getData();
    for (int y=0;y<h;y++) {
        System.arraycopy(in,i,out,j,w);
        i+=w;
        j-=scanlineStride;
    }
}
 

实例 7


/**
 * implements the Runnable interface to gradually fade in the real image over time
 */
@Override
public void run() {
        try {
                WritableRaster sRaster = srcImage.getRaster();
                DataBufferByte sDBB = (DataBufferByte)sRaster.getDataBuffer();
                byte[] sData = sDBB.getData();
                WritableRaster tRaster = targetImage.getRaster();
                DataBufferByte tDBB = (DataBufferByte)tRaster.getDataBuffer();
                byte[] tData = tDBB.getData();
                int transition = 0;
                do {
                        Thread.sleep(TRANSITION_DELAY);
                        transition++;
                        BufferedImage intermediateImage = new BufferedImage(imageSize.width, imageSize.height, BufferedImage.TYPE_4BYTE_ABGR);
                        WritableRaster iRaster=  intermediateImage.getRaster();
                        DataBufferByte iDBB = (DataBufferByte)iRaster.getDataBuffer();
                        byte[] iData = iDBB.getData();
                        for (int i = 0; i < sData.length; ) {
                                iData[i++] = (byte)0xFF;
                                for (int c = 0; c < 3; c++) {
                                        int sC = sData[i] & 0x00FF;
                                        int tC = tData[i] & 0x00FF;
                                        int iC = sC + (((tC - sC) * transition) / NUMTRANSITIONS);
                                        iData[i] = (byte)iC;
                                        ++i;
                                }
                        }
                        imageGenerator.fireImageGenerated(intermediateImage);
                } while ((transition < NUMTRANSITIONS) && !Thread.interrupted());
        } catch (InterruptedException ie) {
        }
}
 

实例 8


/**
 * A faster convert that works directly with a specific raster
 */
public static void bufferedToGray(SunWritableRaster src, ImageUInt8 dst) {
        if( src.getDataBuffer().getDataType() != DataBuffer.TYPE_BYTE )
                throw new RuntimeException("Unsupported type");
        DataBufferByte byteBuffer = (DataBufferByte)src.getDataBuffer();
        byte[] srcData = byteBuffer.getData();
        byte[] dstData = dst.data;
        int numBands = src.getNumBands();
        int srcStride = src.getWidth()*numBands;
        int srcOffset = 0;
        int srcStrideDiff = 0;
        int size = dst.getWidth() * dst.getHeight();
        if (numBands == 3) {
                from_3BU8_to_U8(dst, srcData, dstData, srcOffset, srcStrideDiff);
        } else if (numBands == 1) {
                from_1BU8_to_U8(dst, srcData, dstData, size, srcStride, srcOffset, srcStrideDiff);
        } else if (numBands == 4) {
                from_4BU8_to_U8(dst, srcData, dstData, srcOffset, srcStrideDiff);
        } else {
                throw new RuntimeException("Unexpected number of bands found. Bands = "+numBands);
        }
}
 

实例 9


protected static void divide_BYTE_COMP_Data(WritableRaster wr) {
    // System.out.println("Multiply Int: " + wr);
    ComponentSampleModel csm;
    csm = (ComponentSampleModel) wr.getSampleModel();
    final int width = wr.getWidth();
    final int scanStride = csm.getScanlineStride();
    final int pixStride = csm.getPixelStride();
    final int[] bandOff = csm.getBandOffsets();
    DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
    final int base = (db.getOffset() +
            csm.getOffset(wr.getMinX() - wr.getSampleModelTranslateX(),
            wr.getMinY() - wr.getSampleModelTranslateY()));
    int aOff = bandOff[bandOff.length - 1];
    int bands = bandOff.length - 1;
    // Access the pixel data array
    final byte[] pixels = db.getBankData()[0];
    for (int y = 0; y < wr.getHeight(); y++) {
        int sp = base + y * scanStride;
        final int end = sp + width * pixStride;
        while (sp < end) {
            int a = pixels[sp + aOff] & 0xFF;
            if (a == 0) {
                for (int b = 0; b < bands; b++) {
                    pixels[sp + bandOff[b]] = (byte) 0xFF;
                }
            } else if (a < 255) {         // this does NOT include a == 255 (0xff) !
                int aFP = (0x00FF0000 / a);
                for (int b = 0; b < bands; b++) {
                    int i = sp + bandOff[b];
                    pixels[i] = (byte) (((pixels[i] & 0xFF) * aFP) >>> 16);
                }
            }
            sp += pixStride;
        }
    }
}
 

实例 10


protected static void divide_BYTE_COMP_Data(WritableRaster wr) {
    // System.out.println("Multiply Int: " + wr);
    ComponentSampleModel csm;
    csm = (ComponentSampleModel) wr.getSampleModel();
    final int width = wr.getWidth();
    final int scanStride = csm.getScanlineStride();
    final int pixStride = csm.getPixelStride();
    final int[] bandOff = csm.getBandOffsets();
    DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
    final int base = (db.getOffset() + csm
                                          .getOffset(
                                                     wr.getMinX()
                                                             - wr
                                                                 .getSampleModelTranslateX(),
                                                     wr.getMinY()
                                                             - wr
                                                                 .getSampleModelTranslateY()));
    int a = 0;
    int aOff = bandOff[bandOff.length - 1];
    int bands = bandOff.length - 1;
    int b, i;
    // Access the pixel data array
    final byte pixels[] = db.getBankData()[0];
    for (int y = 0; y < wr.getHeight(); y++) {
        int sp = base + y * scanStride;
        final int end = sp + width * pixStride;
        while (sp < end) {
            a = pixels[sp + aOff] & 0xFF;
            if (a == 0) {
                for (b = 0; b < bands; b++)
                    pixels[sp + bandOff[b]] = (byte) 0xFF;
            } else if (a < 255) {
                int aFP = (0x00FF0000 / a);
                for (b = 0; b < bands; b++) {
                    i = sp + bandOff[b];
                    pixels[i] = (byte) (((pixels[i] & 0xFF) * aFP) >>> 16);
                }
            }
            sp += pixStride;
        }
    }
}
 

实例 11


protected static void divide_BYTE_COMP_Data(WritableRaster wr) {
    // System.out.println("Multiply Int: " + wr);
    ComponentSampleModel csm;
    csm = (ComponentSampleModel) wr.getSampleModel();
    final int width = wr.getWidth();
    final int scanStride = csm.getScanlineStride();
    final int pixStride = csm.getPixelStride();
    final int[] bandOff = csm.getBandOffsets();
    DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
    final int base = (db.getOffset() +
            csm.getOffset(wr.getMinX() - wr.getSampleModelTranslateX(),
            wr.getMinY() - wr.getSampleModelTranslateY()));
    int aOff = bandOff[bandOff.length - 1];
    int bands = bandOff.length - 1;
    // Access the pixel data array
    final byte[] pixels = db.getBankData()[0];
    for (int y = 0; y < wr.getHeight(); y++) {
        int sp = base + y * scanStride;
        final int end = sp + width * pixStride;
        while (sp < end) {
            int a = pixels[sp + aOff] & 0xFF;
            if (a == 0) {
                for (int b = 0; b < bands; b++) {
                    pixels[sp + bandOff[b]] = (byte) 0xFF;
                }
            } else if (a < 255) {         // this does NOT include a == 255 (0xff) !
                int aFP = (0x00FF0000 / a);
                for (int b = 0; b < bands; b++) {
                    int i = sp + bandOff[b];
                    pixels[i] = (byte) (((pixels[i] & 0xFF) * aFP) >>> 16);
                }
            }
            sp += pixStride;
        }
    }
}
 

实例 12


/**
 * compare two images
 * 
 * @param imageStream1
 *            stream of the reference image
 * @param imageStream2
 *            stream of the image to be compared
 * @throws IOException
 *             if IO errors occurred
 */
private void compareImages(final InputStream imageStream1,
                final InputStream imageStream2) {
        try {
                final BufferedImage image1 = ImageIO.read(imageStream1);
                final BufferedImage image2 = ImageIO.read(imageStream2);
                assertEquals(image1.getWidth(), image2.getWidth());
                assertEquals(image1.getHeight(), image2.getHeight());
                final DataBufferByte buffer1 = (DataBufferByte) image1.getRaster()
                                .getDataBuffer();
                final DataBufferByte buffer2 = (DataBufferByte) image2.getRaster()
                                .getDataBuffer();
                assertEquals(buffer1.getNumBanks(), buffer2.getNumBanks());
                for (int bank = 0; bank < buffer1.getNumBanks(); bank++) {
                        assertTrue(Arrays.equals(buffer1.getData(bank),
                                        buffer2.getData(bank)));
                }
        } catch (final IOException e) {
                fail("IO exception occurred!");
        }
}
 

实例 13


/**
 * create image.
 *
 * @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);
}
 

实例 14


/**
 * Tests the transformation using a random raster with only one band.
 *
 * @param  band The sample dimension for the only band.
 * @return The transformed image.
 */
private RenderedImage testOneBand(final GridSampleDimension band) throws TransformException {
    final int SIZE = 64;
    /*
     * Constructs a 64x64 image with random values.
     * Samples values are integer in the range 0..160 inclusive.
     */
    final BufferedImage  source = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_BYTE_INDEXED);
    final DataBufferByte buffer = (DataBufferByte) source.getRaster().getDataBuffer();
    final byte[] array = buffer.getData(0);
    for (int i=0; i<array.length; i++) {
        array[i] = (byte) random.nextInt(161);
    }
    final MathTransform identity = IdentityTransform.create(2);
    final GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);
    GridCoverage2D coverage;
    coverage = factory.create("Test", source, DefaultGeographicCRS.WGS84,
                identity, new GridSampleDimension[] {band}, null, null);
    /*
     * Apply the operation. The SampleTranscoder class is suppose to transform our
     * integers into real-world values. Check if the result use floating-points.
     */
    final RenderedImage target = coverage.view(ViewType.GEOPHYSICS).getRenderedImage();
    assertSame(target, PlanarImage.wrapRenderedImage(target));
    assertEquals(DataBuffer.TYPE_BYTE, source.getSampleModel().getDataType());
    if (coverage.getRenderedImage() != target) {
        assertEquals(DataBuffer.TYPE_FLOAT, target.getSampleModel().getDataType());
    }
    /*
     * Now, gets the data as an array and compare it with the expected values.
     */
    double[] sourceData = source.getData().getSamples(0, 0, SIZE, SIZE, 0, (double[]) null);
    double[] targetData = target.getData().getSamples(0, 0, SIZE, SIZE, 0, (double[]) null);
    band.getSampleToGeophysics().transform(sourceData, 0, sourceData, 0, sourceData.length);
    CategoryListTest.compare(sourceData, targetData, EPS);
    /*
     * Construct a new image with the resulting data, and apply an inverse transformation.
     * Compare the resulting values with the original data.
     */
    RenderedImage back = PlanarImage.wrapRenderedImage(target).getAsBufferedImage();
    coverage = factory.create("Test", back, DefaultGeographicCRS.WGS84,
                identity, new GridSampleDimension[]{band.geophysics(true)}, null, null);
    back = coverage.view(ViewType.PACKED).getRenderedImage();
    assertEquals(DataBuffer.TYPE_BYTE, back.getSampleModel().getDataType());
    sourceData = source.getData().getSamples(0, 0, SIZE, SIZE, 0, (double[]) null);
    targetData =   back.getData().getSamples(0, 0, SIZE, SIZE, 0, (double[]) null);
    CategoryListTest.compare(sourceData, targetData, 1.0 + EPS);
    /*
     * Returns the "geophysics view" of the image.
     */
    return target;
}
 

实例 15


protected byte[] imageToPlatformBytes(Image image, long format)
  throws IOException {
    String mimeType = null;
    if (format == CF_PNG) {
        mimeType = "image/png";
    } else if (format == CF_JFIF) {
        mimeType = "image/jpeg";
    }
    if (mimeType != null) {
        return imageToStandardBytes(image, mimeType);
    }
    int width = 0;
    int height = 0;
    if (image instanceof ToolkitImage) {
        ImageRepresentation ir = ((ToolkitImage)image).getImageRep();
        ir.reconstruct(ImageObserver.ALLBITS);
        width = ir.getWidth();
        height = ir.getHeight();
    } else {
        width = image.getWidth(null);
        height = image.getHeight(null);
    }
    // Fix for 4919639.
    // Some Windows native applications (e.g. clipbrd.exe) do not handle
    // 32-bpp DIBs correctly.
    // As a workaround we switched to 24-bpp DIBs.
    // MSDN prescribes that the bitmap array for a 24-bpp should consist of
    // 3-byte triplets representing blue, green and red components of a
    // pixel respectively. Additionally each scan line must be padded with
    // zeroes to end on a LONG data-type boundary. LONG is always 32-bit.
    // We render the given Image to a BufferedImage of type TYPE_3BYTE_BGR
    // with non-default scanline stride and pass the resulting data buffer
    // to the native code to fill the BITMAPINFO structure.
    int mod = (width * 3) % 4;
    int pad = mod > 0 ? 4 - mod : 0;
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    int[] nBits = {8, 8, 8};
    int[] bOffs = {2, 1, 0};
    ColorModel colorModel =
        new ComponentColorModel(cs, nBits, false, false,
                                Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    WritableRaster raster =
        Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height,
                                       width * 3 + pad, 3, bOffs, null);
    BufferedImage bimage = new BufferedImage(colorModel, raster, false, null);
    // Some Windows native applications (e.g. clipbrd.exe) do not understand
    // top-down DIBs.
    // So we flip the image vertically and create a bottom-up DIB.
    AffineTransform imageFlipTransform =
        new AffineTransform(1, 0, 0, -1, 0, height);
    Graphics2D g2d = bimage.createGraphics();
    try {
        g2d.drawImage(image, imageFlipTransform, null);
    } finally {
        g2d.dispose();
    }
    DataBufferByte buffer = (DataBufferByte)raster.getDataBuffer();
    byte[] imageData = buffer.getData();
    return imageDataToPlatformImageBytes(imageData, width, height, format);
}
 
讨论
淘淘あ西西 profile image