Example usage for java.nio ByteBuffer capacity

List of usage examples for java.nio ByteBuffer capacity

Introduction

In this page you can find the example usage for java.nio ByteBuffer capacity.

Prototype

public final int capacity() 

Source Link

Document

Returns the capacity of this buffer.

Usage

From source file:com.oneguy.recognize.Util.java

public static ByteBuffer putData(ByteBuffer buffer, byte[] data) {
    if (buffer == null || data == null || data.length == 0) {
        return buffer;
    }/*from   w w  w.j a  v a2 s .  c  om*/
    while (buffer.capacity() < buffer.position() + data.length - 1) {
        buffer = doubleSize(buffer);
    }
    buffer.put(data);
    return buffer;
}

From source file:org.onlab.util.ImmutableByteSequence.java

/**
 * Creates a new immutable byte sequence copying bytes from the given
 * ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
 * bytes will be copied in reverse order.
 *
 * @param original a byte buffer/*from  w  ww.j  av a  2  s  .  co m*/
 * @return a new byte buffer object
 */
public static ImmutableByteSequence copyFrom(ByteBuffer original) {
    checkArgument(original != null && original.capacity() > 0, "Cannot copy from an empty or null byte buffer");

    byte[] bytes = new byte[original.capacity()];

    // copy bytes from original buffer
    original.rewind();
    original.get(bytes);

    if (original.order() == ByteOrder.LITTLE_ENDIAN) {
        // FIXME: this can be improved, e.g. read bytes in reverse order from original
        reverse(bytes);
    }

    return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
}

From source file:org.kuali.student.common.io.IOUtils.java

private static String decode(CharsetDecoder decoder, byte[] in) {

    ByteBuffer inBuf = ByteBuffer.wrap(in);

    CharBuffer outBuf = CharBuffer.allocate(inBuf.capacity() * Math.round(decoder.maxCharsPerByte() + 0.5f));

    decoder.decode(inBuf, outBuf, true);

    decoder.flush(outBuf);/*from  w w w. ja va 2  s.co m*/

    decoder.reset();

    return outBuf.flip().toString();

}

From source file:com.android.camera2.its.ItsUtils.java

public static byte[] getDataFromImage(Image image) throws ItsException {
    int format = image.getFormat();
    int width = image.getWidth();
    int height = image.getHeight();
    byte[] data = null;

    // Read image data
    Plane[] planes = image.getPlanes();//from   w  w  w.ja  v  a2 s .  c o m

    // Check image validity
    if (!checkAndroidImageFormat(image)) {
        throw new ItsException("Invalid image format passed to getDataFromImage: " + image.getFormat());
    }

    if (format == ImageFormat.JPEG) {
        // JPEG doesn't have pixelstride and rowstride, treat it as 1D buffer.
        ByteBuffer buffer = planes[0].getBuffer();
        data = new byte[buffer.capacity()];
        buffer.get(data);
        return data;
    } else if (format == ImageFormat.YUV_420_888 || format == ImageFormat.RAW_SENSOR
            || format == ImageFormat.RAW10) {
        int offset = 0;
        data = new byte[width * height * ImageFormat.getBitsPerPixel(format) / 8];
        byte[] rowData = new byte[planes[0].getRowStride()];
        for (int i = 0; i < planes.length; i++) {
            ByteBuffer buffer = planes[i].getBuffer();
            int rowStride = planes[i].getRowStride();
            int pixelStride = planes[i].getPixelStride();
            int bytesPerPixel = ImageFormat.getBitsPerPixel(format) / 8;
            Logt.i(TAG, String.format("Reading image: fmt %d, plane %d, w %d, h %d, rowStride %d, pixStride %d",
                    format, i, width, height, rowStride, pixelStride));
            // For multi-planar yuv images, assuming yuv420 with 2x2 chroma subsampling.
            int w = (i == 0) ? width : width / 2;
            int h = (i == 0) ? height : height / 2;
            for (int row = 0; row < h; row++) {
                if (pixelStride == bytesPerPixel) {
                    // Special case: optimized read of the entire row
                    int length = w * bytesPerPixel;
                    buffer.get(data, offset, length);
                    // Advance buffer the remainder of the row stride
                    buffer.position(buffer.position() + rowStride - length);
                    offset += length;
                } else {
                    // Generic case: should work for any pixelStride but slower.
                    // Use intermediate buffer to avoid read byte-by-byte from
                    // DirectByteBuffer, which is very bad for performance.
                    // Also need avoid access out of bound by only reading the available
                    // bytes in the bytebuffer.
                    int readSize = rowStride;
                    if (buffer.remaining() < readSize) {
                        readSize = buffer.remaining();
                    }
                    buffer.get(rowData, 0, readSize);
                    if (pixelStride >= 1) {
                        for (int col = 0; col < w; col++) {
                            data[offset++] = rowData[col * pixelStride];
                        }
                    } else {
                        // PixelStride of 0 can mean pixel isn't a multiple of 8 bits, for
                        // example with RAW10. Just copy the buffer, dropping any padding at
                        // the end of the row.
                        int length = (w * ImageFormat.getBitsPerPixel(format)) / 8;
                        System.arraycopy(rowData, 0, data, offset, length);
                        offset += length;
                    }
                }
            }
        }
        Logt.i(TAG, String.format("Done reading image, format %d", format));
        return data;
    } else {
        throw new ItsException("Unsupported image format: " + format);
    }
}

From source file:tachyon.io.Utils.java

/**
 * Converts a byte buffer to a base64-encoded String. Avoids copying the array if possible.
 *//*from ww  w.java 2s.  c o m*/
public static String byteBufferToBase64(ByteBuffer buf) {
    if (buf == null) {
        return null;
    }

    if (buf.hasArray() && buf.position() == 0 && buf.limit() == buf.capacity()) {
        return Base64.encodeBase64String(buf.array());
    } else {
        byte[] b = new byte[buf.remaining()];
        buf.get(b);
        return Base64.encodeBase64String(b);
    }
}

From source file:Main.java

/**
 * Returns new byte buffer whose content is a shared subsequence of this buffer's content
 * between the specified start (inclusive) and end (exclusive) positions. As opposed to
 * {@link ByteBuffer#slice()}, the returned buffer's byte order is the same as the source
 * buffer's byte order.//w  w  w.j  a v a  2s.  c o  m
 */
private static ByteBuffer sliceFromTo(final ByteBuffer source, final int start, final int end) {
    if (start < 0) {
        throw new IllegalArgumentException("start: " + start);
    }
    if (end < start) {
        throw new IllegalArgumentException("end < start: " + end + " < " + start);
    }
    final int capacity = source.capacity();
    if (end > source.capacity()) {
        throw new IllegalArgumentException("end > capacity: " + end + " > " + capacity);
    }
    final int originalLimit = source.limit();
    final int originalPosition = source.position();
    try {
        source.position(0);
        source.limit(end);
        source.position(start);
        final ByteBuffer result = source.slice();
        result.order(source.order());
        return result;
    } finally {
        source.position(0);
        source.limit(originalLimit);
        source.position(originalPosition);
    }
}

From source file:com.oneguy.recognize.Util.java

public static ByteBuffer doubleSize(ByteBuffer buffer) {
    if (buffer == null) {
        return null;
    }/*from   www  .j  a  v a 2  s  .  c  om*/
    byte[] content = new byte[buffer.position()];
    buffer.flip();
    buffer.get(content);
    ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
    newBuffer.put(content);
    return newBuffer;
}

From source file:com.fujitsu.dc.test.jersey.bar.BarInstallTestUtils.java

/**
 * bar?.//w w w. ja v  a 2 s  .  c o  m
 * @param barFile bar?
 * @return ??bar
 */
public static byte[] readBarFile(File barFile) {
    InputStream is = ClassLoader.getSystemResourceAsStream(barFile.getPath());
    ByteBuffer buff = ByteBuffer.allocate(READ_BUFFER_SIZE);
    log.debug(String.valueOf(buff.capacity()));
    try {
        byte[] bbuf = new byte[SIZE_KB];
        int size;
        while ((size = is.read(bbuf)) != -1) {
            buff.put(bbuf, 0, size);
        }
    } catch (IOException e) {
        throw new RuntimeException("failed to load bar file:" + barFile.getPath(), e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException("failed to close bar file:" + barFile.getPath(), e);
        }
    }
    int size = buff.position();
    buff.flip();
    byte[] retv = new byte[size];
    buff.get(retv, 0, size);
    return retv;
}

From source file:io.mycat.util.ByteBufferUtil.java

/** trims size of bytebuffer to exactly number of bytes in it, to do not hold too much memory */
public static ByteBuffer minimalBufferFor(ByteBuffer buf) {
    return buf.capacity() > buf.remaining() || !buf.hasArray() ? ByteBuffer.wrap(getArray(buf)) : buf;
}

From source file:Main.java

public static byte[] makeFontBitmap(String font, String code, int size, float[] arrayOfPos) {
    Log.v(TAG, String.format("makeFontBitmap called(Java): font=%s code=%s", font, code));
    Canvas c = new Canvas();
    Paint p = new Paint();
    //        Log.v(TAG, "get density");
    float density = context.getResources().getDisplayMetrics().density;
    Log.v(TAG, String.format("makeFontBitmap density: %f", density));
    p.setTextSize((float) size * density);
    p.setAntiAlias(true);//from   ww  w  .j a v a  2  s  .c o m

    Rect textBounds = new Rect();
    p.getTextBounds(code, 0, code.length(), textBounds);
    Log.v(TAG, String.format("makeFontBitmap textBounds: %d,%d,%d,%d", textBounds.left, textBounds.top,
            textBounds.right, textBounds.bottom));

    Rect textBoundsAxA = new Rect();
    String axa = String.format("A%sA", code);
    p.getTextBounds(axa, 0, axa.length(), textBoundsAxA);
    Rect textBoundsAA = new Rect();
    String aa = "AA";
    p.getTextBounds(aa, 0, aa.length(), textBoundsAA);

    // cache.distDelta = Vec2(0, 0);
    arrayOfPos[0] = textBounds.left;
    arrayOfPos[1] = textBounds.top;

    // cache.srcWidth = Vec2(16, 16);
    arrayOfPos[2] = textBounds.width();
    arrayOfPos[3] = textBounds.height();

    // cache.step = 16;
    //      arrayOfPos[4] = textBounds.width() + 1;
    arrayOfPos[4] = textBoundsAxA.width() - textBoundsAA.width();

    if (textBounds.width() == 0 || textBounds.height() == 0) {
        Log.v(TAG, "makeFontBitmap: empty");
        return null;
    }

    Bitmap b = Bitmap.createBitmap(textBounds.width(), textBounds.height(), Bitmap.Config.ARGB_8888);
    c.setBitmap(b);

    Rect r = new Rect(0, 0, textBounds.width(), textBounds.height());
    //      p.setColor(Color.RED);
    p.setARGB(0, 0, 0, 0);
    c.drawRect(r, p);
    p.setARGB(255, 255, 255, 255);

    //        Log.v(TAG, "makeFontBitmap: drawText");
    c.drawText(code, -textBounds.left, -textBounds.top, p);
    Log.v(TAG, String.format("makeFontBitmap: w=%.2f h=%.2f", arrayOfPos[2], arrayOfPos[3]));

    ByteBuffer buf = ByteBuffer.allocate(textBounds.width() * textBounds.height() * 4);
    //      ByteBuffer buf = ByteBuffer.allocate(b.getRowBytes());
    Log.v(TAG, String.format("makeFontBitmap: b.getRowBytes() %d", b.getRowBytes()));
    buf.position(0);
    b.copyPixelsToBuffer(buf);
    Log.v(TAG, String.format("makeFontBitmap results: capacity=%d", buf.capacity()));

    //      byte bytes[] = buf.array();
    //      for (int i = 0; i < size * size * 2; i++)
    //         bytes[i] = (byte)(Math.random() * 255);
    return buf.array();
}