Java Code Examples for android.graphics.Bitmap#copyPixelsToBuffer()

The following examples show how to use android.graphics.Bitmap#copyPixelsToBuffer() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: ScratchView   File: BitmapUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Finds the percentage of pixels that do are empty.
 *
 * @param bitmap input bitmap
 * @return a value between 0.0 to 1.0 . Note the method will return 0.0 if either of bitmaps are null nor of same size.
 *
 */
public static float getTransparentPixelPercent(Bitmap bitmap) {

    if (bitmap == null) {
        return 0f;
    }

    ByteBuffer buffer = ByteBuffer.allocate(bitmap.getHeight() * bitmap.getRowBytes());
    bitmap.copyPixelsToBuffer(buffer);

    byte[] array = buffer.array();

    int len = array.length;
    int count = 0;

    for(int i=0;i<len;i++) {
        if(array[i] == 0) {
            count++;
        }
    }

    return ((float)(count))/len;
}
 
Example 2
Source Project: xDrip   File: BitmapTools.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Wrapper loadPNGBytesToRGB565(final byte[] pngBytes) {
    if (pngBytes == null || pngBytes.length == 0) return null;
    try {
        val options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        final Bitmap bitmap = BitmapFactory.decodeByteArray(pngBytes, 0, pngBytes.length, options);

        val buffer = ByteBuffer.allocate(bitmap.getByteCount());
        val width = bitmap.getWidth();
        val height = bitmap.getHeight();
        bitmap.copyPixelsToBuffer(buffer);
        bitmap.recycle();
        return new Wrapper(TJ_BitmapType.RGB565, width, height, byteSwapRGB565(buffer.array()));
    } catch (Exception e) {
        UserError.Log.e(TAG, "loadPNGBytesToRGB565: exception " + e);
        return null;
    }
}
 
Example 3
public static Wrapper loadPNGBytesToRGB565(final byte[] pngBytes) {
    if (pngBytes == null || pngBytes.length == 0) return null;
    try {
        val options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        final Bitmap bitmap = BitmapFactory.decodeByteArray(pngBytes, 0, pngBytes.length, options);

        val buffer = ByteBuffer.allocate(bitmap.getByteCount());
        val width = bitmap.getWidth();
        val height = bitmap.getHeight();
        bitmap.copyPixelsToBuffer(buffer);
        bitmap.recycle();
        return new Wrapper(TJ_BitmapType.RGB565, width, height, byteSwapRGB565(buffer.array()));
    } catch (Exception e) {
        UserError.Log.e(TAG, "loadPNGBytesToRGB565: exception " + e);
        return null;
    }
}
 
Example 4
Source Project: videocreator   File: BitmapUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 从图片中获取字节数组
 */
public static byte[] getBytes(Bitmap bitmap) {
    byte[] buffer = new byte[bitmap.getRowBytes() * bitmap.getHeight()];
    Buffer byteBuffer = ByteBuffer.wrap(buffer);
    bitmap.copyPixelsToBuffer(byteBuffer);
    return buffer;
}
 
Example 5
Source Project: FaceDemo   File: DetecteSeeta.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取图像的字节数据
 * @param image
 * @return
 */
public byte[] getPixelsRGBA(Bitmap image) {
    // calculate how many bytes our image consists of
    int bytes = image.getByteCount();

    ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a new buffer
    image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer

    byte[] temp = buffer.array(); // Get the underlying array containing the

    return temp;
}
 
Example 6
private static void compareImages(Bitmap bmp1, Bitmap bmp2) {
    assertTrue(bmp1.getHeight() == bmp2.getHeight());
    assertTrue(bmp1.getWidth() == bmp1.getWidth());
    ByteBuffer buffer1 = ByteBuffer.allocate(bmp1.getHeight() * bmp1.getRowBytes());
    bmp1.copyPixelsToBuffer(buffer1);

    ByteBuffer buffer2 = ByteBuffer.allocate(bmp2.getHeight() * bmp2.getRowBytes());
    bmp2.copyPixelsToBuffer(buffer2);

    assertTrue(Arrays.equals(buffer1.array(), buffer2.array()));
}
 
Example 7
public void setImageInfo()
{
    attributes.put(MilStdAttributes.SymbologyStandard, "0");
    ImageInfo imageInfo = renderer.RenderIcon(symbolCode, modifiers, attributes);
    Bitmap bitmap = imageInfo.getImage();
    ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
    bitmap.copyPixelsToBuffer(buffer);
    imageBytes = buffer.array();
}
 
Example 8
Source Project: ScratchView   File: BitmapUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Compares two bitmaps and gives the percentage of similarity
 *
 * @param bitmap1 input bitmap 1
 * @param bitmap2 input bitmap 2
 * @return a value between 0.0 to 1.0 . Note the method will return 0.0 if either of bitmaps are null nor of same size.
 *
 */
public static float compareEquivalance(Bitmap bitmap1, Bitmap bitmap2) {

    if (bitmap1 == null || bitmap2 == null || bitmap1.getWidth() != bitmap2.getWidth() || bitmap1.getHeight() != bitmap2.getHeight()) {
        return 0f;
    }


    ByteBuffer buffer1 = ByteBuffer.allocate(bitmap1.getHeight() * bitmap1.getRowBytes());
    bitmap1.copyPixelsToBuffer(buffer1);

    ByteBuffer buffer2 = ByteBuffer.allocate(bitmap2.getHeight() * bitmap2.getRowBytes());
    bitmap2.copyPixelsToBuffer(buffer2);

    byte[] array1 = buffer1.array();
    byte[] array2 = buffer2.array();

    int len = array1.length; // array1 and array2 will be of some length.
    int count = 0;

    for(int i=0;i<len;i++) {
        if(array1[i] == array2[i]) {
            count++;
        }
    }

    return ((float)(count))/len;
}
 
Example 9
public static ByteBufferBitmap get(final Bitmap bmp) {
    if (bmp.getConfig() != Bitmap.Config.ARGB_8888) {
        throw new IllegalArgumentException("Wrong bitmap config: " + bmp.getConfig());
    }
    final ByteBufferBitmap b = ByteBufferManager.getBitmap(bmp.getWidth(), bmp.getHeight());
    bmp.copyPixelsToBuffer(b.pixels);
    return b;
}
 
Example 10
Source Project: DeviceConnect-Android   File: DefaultProjector.java    License: MIT License 5 votes vote down vote up
private void reverse(final Bitmap b) {
    int width = b.getWidth();
    int height = b.getHeight();
    IntBuffer buf = IntBuffer.allocate(width * height);
    IntBuffer tmp = IntBuffer.allocate(width * height);
    b.copyPixelsToBuffer(buf);
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            tmp.put((height - i - 1) * width + j, buf.get(i * width + j));
        }
    }
    b.copyPixelsFromBuffer(tmp);
    buf.clear();
}
 
Example 11
Source Project: Example-of-Cocos2DX   File: Cocos2dxBitmap.java    License: MIT License 5 votes vote down vote up
private static byte[] getPixels(final Bitmap bitmap) {
	if (bitmap != null) {
		final byte[] pixels = new byte[bitmap.getWidth()
				* bitmap.getHeight() * 4];
		final ByteBuffer buf = ByteBuffer.wrap(pixels);
		buf.order(ByteOrder.nativeOrder());
		bitmap.copyPixelsToBuffer(buf);
		return pixels;
	}

	return null;
}
 
Example 12
Source Project: Example-of-Cocos2DX   File: Cocos2dxBitmap.java    License: MIT License 5 votes vote down vote up
private static byte[] getPixels(final Bitmap bitmap) {
	if (bitmap != null) {
		final byte[] pixels = new byte[bitmap.getWidth()
				* bitmap.getHeight() * 4];
		final ByteBuffer buf = ByteBuffer.wrap(pixels);
		buf.order(ByteOrder.nativeOrder());
		bitmap.copyPixelsToBuffer(buf);
		return pixels;
	}

	return null;
}
 
Example 13
Source Project: Earlybird   File: Cocos2dxBitmap.java    License: Apache License 2.0 5 votes vote down vote up
private static byte[] getPixels(final Bitmap bitmap) {
	if (bitmap != null) {
		final byte[] pixels = new byte[bitmap.getWidth()
				* bitmap.getHeight() * 4];
		final ByteBuffer buf = ByteBuffer.wrap(pixels);
		buf.order(ByteOrder.nativeOrder());
		bitmap.copyPixelsToBuffer(buf);
		return pixels;
	}

	return null;
}
 
Example 14
public void test_getMapTile_found() throws RemoteException, BitmapTileSourceBase.LowMemoryException, java.io.IOException {
	final long tile = MapTileIndex.getTileIndex(2, 3, 3);
	if (Build.VERSION.SDK_INT >=23)
		return;

	// create a bitmap, draw something on it, write it to a file and put it in the cache
	String path = getContext().getFilesDir().getAbsolutePath() + File.separator + "osmdroid" + File.separator;

	File temp= new File(path);
	if (!temp.exists())
		temp.mkdirs();
	Configuration.getInstance().setOsmdroidTileCache(temp);;
	path = path + "OpenStreetMapTileProviderTest.png";
	File f = new File(path);
	if (f.exists())
		f.delete();
	final Bitmap bitmap1 = Bitmap.createBitmap(
			TileSourceFactory.MAPNIK.getTileSizePixels(),
			TileSourceFactory.MAPNIK.getTileSizePixels(),
			Config.ARGB_8888);
	bitmap1.eraseColor(Color.YELLOW);
	final Canvas canvas = new Canvas(bitmap1);

	canvas.drawText("test", 10, 20, new Paint());
	try {
		f.createNewFile();
		final FileOutputStream fos = new FileOutputStream(path);
		bitmap1.compress(CompressFormat.PNG, 100, fos);
		fos.close();
	}catch (Exception ex){
		ex.printStackTrace();
		Assert.fail("unable to write temp tile " + ex);
	}
	final MapTileRequestState state = new MapTileRequestState(tile,
			new ArrayList<MapTileModuleProviderBase>(), mProvider);
	mProvider.mapTileRequestCompleted(state, TileSourceFactory.MAPNIK.getDrawable(path));

	// do the test
	final Drawable drawable = mProvider.getMapTile(tile);
	if (f.exists())
		f.delete();
	assertNotNull("Expect tile to be not null from path " + path, drawable);
	assertTrue("Expect instance of BitmapDrawable", drawable instanceof BitmapDrawable);
	final Bitmap bitmap2 = ((BitmapDrawable) drawable).getBitmap();
	assertNotNull("Expect tile to be not null", bitmap2);

	// compare a few things to see if it's the same bitmap
	// commented out due to a number of intermitent failures on API8
	if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
		assertEquals("Compare config", bitmap1.getConfig(), bitmap2.getConfig());
	}
	assertEquals("Compare width", bitmap1.getWidth(), bitmap2.getWidth());
	assertEquals("Compare height", bitmap1.getHeight(), bitmap2.getHeight());

	if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
		// compare the total thing
		final ByteBuffer bb1 = ByteBuffer.allocate(bitmap1.getWidth() * bitmap1.getHeight() * 4);
		bitmap1.copyPixelsToBuffer(bb1);
		final ByteBuffer bb2 = ByteBuffer.allocate(bitmap2.getWidth() * bitmap2.getHeight() * 4);
		bitmap2.copyPixelsToBuffer(bb2);
		assertEquals("Compare pixels", bb1, bb2);
	}
}
 
Example 15
/**
 * Applies a more expensive and accurate outline to whatever is currently drawn in a specified
 * bitmap.
 */
public void applyExpensiveOutlineWithBlur(Bitmap srcDst, Canvas srcDstCanvas) {

    // We start by removing most of the alpha channel so as to ignore shadows, and
    // other types of partial transparency when defining the shape of the object
    byte[] pixels = new byte[srcDst.getWidth() * srcDst.getHeight()];
    ByteBuffer buffer = ByteBuffer.wrap(pixels);
    buffer.rewind();
    srcDst.copyPixelsToBuffer(buffer);

    for (int i = 0; i < pixels.length; i++) {
        if ((pixels[i] & 0xFF) < 188) {
            pixels[i] = 0;
        }
    }

    buffer.rewind();
    srcDst.copyPixelsFromBuffer(buffer);

    // calculate the outer blur first
    mBlurPaint.setMaskFilter(mMediumOuterBlurMaskFilter);
    int[] outerBlurOffset = new int[2];
    Bitmap thickOuterBlur = srcDst.extractAlpha(mBlurPaint, outerBlurOffset);

    mBlurPaint.setMaskFilter(mThinOuterBlurMaskFilter);
    int[] brightOutlineOffset = new int[2];
    Bitmap brightOutline = srcDst.extractAlpha(mBlurPaint, brightOutlineOffset);

    // calculate the inner blur
    srcDstCanvas.setBitmap(srcDst);
    srcDstCanvas.drawColor(0xFF000000, PorterDuff.Mode.SRC_OUT);
    mBlurPaint.setMaskFilter(mMediumInnerBlurMaskFilter);
    int[] thickInnerBlurOffset = new int[2];
    Bitmap thickInnerBlur = srcDst.extractAlpha(mBlurPaint, thickInnerBlurOffset);

    // mask out the inner blur
    srcDstCanvas.setBitmap(thickInnerBlur);
    srcDstCanvas.drawBitmap(srcDst, -thickInnerBlurOffset[0],
            -thickInnerBlurOffset[1], mErasePaint);
    srcDstCanvas.drawRect(0, 0, -thickInnerBlurOffset[0], thickInnerBlur.getHeight(),
            mErasePaint);
    srcDstCanvas.drawRect(0, 0, thickInnerBlur.getWidth(), -thickInnerBlurOffset[1],
            mErasePaint);

    // draw the inner and outer blur
    srcDstCanvas.setBitmap(srcDst);
    srcDstCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
    srcDstCanvas.drawBitmap(thickInnerBlur, thickInnerBlurOffset[0], thickInnerBlurOffset[1],
            mDrawPaint);
    srcDstCanvas.drawBitmap(thickOuterBlur, outerBlurOffset[0], outerBlurOffset[1],
            mDrawPaint);

    // draw the bright outline
    srcDstCanvas.drawBitmap(brightOutline, brightOutlineOffset[0], brightOutlineOffset[1],
            mDrawPaint);

    // cleanup
    srcDstCanvas.setBitmap(null);
    brightOutline.recycle();
    thickOuterBlur.recycle();
    thickInnerBlur.recycle();
}
 
Example 16
Source Project: video-quickstart-android   File: ViewCapturer.java    License: MIT License 4 votes vote down vote up
@Override
public void run() {
    boolean dropFrame = view.getWidth() == 0 || view.getHeight() == 0;

    // Only capture the view if the dimensions have been established
    if (!dropFrame) {
        // Draw view into bitmap backed canvas
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(view.getWidth(),
                View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(view.getHeight(),
                View.MeasureSpec.EXACTLY);
        view.measure(measuredWidth, measuredHeight);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

        Bitmap viewBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);
        view.draw(viewCanvas);

        // Extract the frame from the bitmap
        int bytes = viewBitmap.getByteCount();
        ByteBuffer buffer = ByteBuffer.allocate(bytes);
        viewBitmap.copyPixelsToBuffer(buffer);
        byte[] array = buffer.array();
        final long captureTimeNs =
                TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime());

        // Create video frame
        VideoDimensions dimensions = new VideoDimensions(view.getWidth(), view.getHeight());
        VideoFrame videoFrame = new VideoFrame(array,
                dimensions, VideoFrame.RotationAngle.ROTATION_0, captureTimeNs);

        // Notify the listener
        if (started.get()) {
            videoCapturerListener.onFrameCaptured(videoFrame);
        }
    }

    // Schedule the next capture
    if (started.get()) {
        handler.postDelayed(this, VIEW_CAPTURER_FRAMERATE_MS);
    }
}
 
Example 17
Source Project: marvel   File: PersonRecognizer.java    License: MIT License 4 votes vote down vote up
IplImage BitmapToIplImage(Bitmap bmp, int width, int height) {

		if ((width != -1) || (height != -1)) {
			Bitmap bmp2 = Bitmap.createScaledBitmap(bmp, width, height, false);
			bmp = bmp2;
		}

		IplImage image = IplImage.create(bmp.getWidth(), bmp.getHeight(),
				IPL_DEPTH_8U, 4);

		bmp.copyPixelsToBuffer(image.getByteBuffer());

		IplImage grayImg = IplImage.create(image.width(), image.height(),
				IPL_DEPTH_8U, 1);

		cvCvtColor(image, grayImg, opencv_imgproc.CV_BGR2GRAY);

		return grayImg;
	}
 
Example 18
public static byte[] bitmap2Bytes(Bitmap bitmap){
    ByteBuffer byteBuffer=ByteBuffer.allocate(bitmap.getByteCount());
    bitmap.copyPixelsToBuffer(byteBuffer);
    return byteBuffer.array();
}
 
Example 19
@Override
public Object load(AssetInfo assetInfo) throws IOException {
    Bitmap bitmap = null;
    Image.Format format;
    InputStream in = null;
    int bpp;
    
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferQualityOverSpeed = false;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    options.inTempStorage = tempData;
    options.inScaled = false;
    options.inDither = false;
    options.inInputShareable = true;
    options.inPurgeable = true;
    options.inSampleSize = 1;
    
    try {
        in = assetInfo.openStream();
        bitmap = BitmapFactory.decodeStream(in, null, options);
        if (bitmap == null) {
            throw new IOException("Failed to load image: " + assetInfo.getKey().getName());
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }

    switch (bitmap.getConfig()) {
        case ALPHA_8:
            format = Image.Format.Alpha8;
            bpp = 1;
            break;
        case ARGB_8888:
            format = Image.Format.RGBA8;
            bpp = 4;
            break;
        case RGB_565:
            format = Image.Format.RGB565;
            bpp = 2;
            break;
        default:
            throw new UnsupportedOperationException("Unrecognized Android bitmap format: " + bitmap.getConfig());
    }

    TextureKey texKey = (TextureKey) assetInfo.getKey();
    
    int width  = bitmap.getWidth();
    int height = bitmap.getHeight();
    
    ByteBuffer data = BufferUtils.createByteBuffer(bitmap.getWidth() * bitmap.getHeight() * bpp);
    
    if (format == Image.Format.RGBA8) {
        int[] pixelData = new int[width * height];
        bitmap.getPixels(pixelData, 0,  width, 0, 0,          width,  height);

        if (texKey.isFlipY()) {
            int[] sln = new int[width];
            int y2;
            for (int y1 = 0; y1 < height / 2; y1++){
                y2 = height - y1 - 1;
                convertARGBtoABGR(pixelData, y1 * width, sln, 0,         width);
                convertARGBtoABGR(pixelData, y2 * width, pixelData, y1 * width, width);
                System.arraycopy (sln,       0,          pixelData, y2 * width, width);
            }
        } else {
            convertARGBtoABGR(pixelData, 0, pixelData, 0, pixelData.length);
        }
        
        data.asIntBuffer().put(pixelData);
    } else {
        if (texKey.isFlipY()) {
            // Flip the image, then delete the old one.
            Matrix flipMat = new Matrix();
            flipMat.preScale(1.0f, -1.0f);
            Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), flipMat, false);
            bitmap.recycle();
            bitmap = newBitmap;
            
            if (bitmap == null) {
                throw new IOException("Failed to flip image: " + texKey);
            }
        }
        
        bitmap.copyPixelsToBuffer(data);
    }
    
    data.flip();
    
    bitmap.recycle();
    
    Image image = new Image(format, width, height, data, ColorSpace.sRGB);
    return image;
}
 
Example 20
private static Bitmap from1Bit(PDImage pdImage) throws IOException
{
    final PDColorSpace colorSpace = pdImage.getColorSpace();
    final int width = pdImage.getWidth();
    final int height = pdImage.getHeight();
    Bitmap raster = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
    final float[] decode = getDecodeArray(pdImage);
    ByteBuffer buffer = ByteBuffer.allocate(raster.getRowBytes() * height);
    raster.copyPixelsToBuffer(buffer);
    byte[] output = buffer.array();

    // read bit stream
    InputStream iis = null;
    try
    {
        // create stream
        iis = pdImage.createInputStream();
        final boolean isIndexed =
            false; // TODO: PdfBox-Android colorSpace instanceof PDIndexed;

        int rowLen = width / 8;
        if (width % 8 > 0)
        {
            rowLen++;
        }

        // read stream
        byte value0;
        byte value1;
        if (isIndexed || decode[0] < decode[1])
        {
            value0 = 0;
            value1 = (byte) 255;
        }
        else
        {
            value0 = (byte) 255;
            value1 = 0;
        }
        byte[] buff = new byte[rowLen];
        int idx = 0;
        for (int y = 0; y < height; y++)
        {
            int x = 0;
            int readLen = iis.read(buff);
            for (int r = 0; r < rowLen && r < readLen; r++)
            {
                int value = buff[r];
                int mask = 128;
                for (int i = 0; i < 8; i++)
                {
                    int bit = value & mask;
                    mask >>= 1;
                    output[idx++] = bit == 0 ? value0 : value1;
                    x++;
                    if (x == width)
                    {
                        break;
                    }
                }
            }
            if (readLen != rowLen)
            {
                Log.w("PdfBox-Android", "premature EOF, image will be incomplete");
                break;
            }
        }


        buffer.rewind();
        raster.copyPixelsFromBuffer(buffer);
        // use the color space to convert the image to RGB
        return colorSpace.toRGBImage(raster);
    } finally
    {
        if (iis != null)
        {
            iis.close();
        }
    }
}