Java Code Examples for android.graphics.Bitmap.copyPixelsFromBuffer()

The following are Jave code examples for showing how to use copyPixelsFromBuffer() of the android.graphics.Bitmap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ScreenRecordCaptureMaster   File: CaptureScreenImage.java   View Source Code Vote up 8 votes
/**
 * 图像可用时截屏
 *
 * @param reader
 * @param path
 *@param callback @return
 */
private void imageAvailable(ImageReader reader, String path, IRecordShotCallback callback) {
    mImageReaderLock.lock();
    try{
        Image image = reader.acquireLatestImage();

        if(image == null) return;
        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * width;
        Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        image.close();
        //需要在这里释放图片否则会截取很多图片
        release();

        saveBitmap(path, bitmap, callback);
    }finally {
        mImageReaderLock.unlock();
    }
}
 
Example 2
Project: BWS-Android   File: ImageFormatConverter.java   View Source Code Vote up 6 votes
/**
 * Converts a GrayscaleImage to a Bitmap.
 */
@NonNull
public Bitmap grayscaleImageToBitmap(@NonNull GrayscaleImage img) {
    String stopwatchSessionId = log.startStopwatch(getStopwatchSessionId("grayscaleImageToBitmap"));

    int size = img.width * img.height;
    int[] buffer = new int[size];

    for (int index = 0; index < size; index++) {
        // "AND 0xff" for the signed byte issue
        int luminance = img.data[index] & 0xff;
        // normal encoding for bitmap
        buffer[index] = (0xff000000 | luminance << 16 | luminance << 8 | luminance);
    }

    Bitmap bitmap = Bitmap.createBitmap(img.width, img.height, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(IntBuffer.wrap(buffer));

    log.stopStopwatch(stopwatchSessionId);
    return bitmap;
}
 
Example 3
Project: homunculus   File: BitmapPoolFactory.java   View Source Code Vote up 6 votes
/**
 * Tries to recycle a pooled bitmap and reads raw pixels into the bitmap. Internally always reuses
 * a (potentially) big buffer to update the texture. The buffer grows to the largest size when needed and
 * is never shrunk, so be careful what you read, e.g. a fullhd frame will take more than 8 MiB. However to
 * lower the pressure to the stupid Android GC we sacrifice throughput by synchronizing globally, so NEVER
 * call this method from the UI thread.
 * <p>
 * The format is:
 * <pre>
 *     bool available   1 byte
 *     int width        4 byte
 *     int height       4 byte
 *     int type         1 byte, [2 = ARGB_8888]
 * </pre>
 *
 * @param in the source
 * @return the instance or null if not available
 * @throws IOException
 */
@Nullable
public static Bitmap readPixel(DataInput in) throws IOException {
    boolean available = in.readBoolean();
    if (!available) {
        return null;
    }
    int width = in.readInt();
    int height = in.readInt();
    int type = in.readUnsignedByte();
    if (type != Config.ARGB_8888.ordinal()) {
        throw new Panic("format not implemented " + type);
    }
    int bytes = width * height * 4;
    Bitmap bmp = getDefaultPool().borrowBitmap(width, height, Config.ARGB_8888);
    synchronized (BitmapPoolFactory.class) {
        if (sTmp.capacity() < bytes) {
            sTmp = ByteBuffer.allocate(bytes);
        }
        sTmp.clear();
        in.readFully(sTmp.array(), 0, bytes);
        sTmp.limit(bytes);
        bmp.copyPixelsFromBuffer(sTmp);
    }
    return bmp;
}
 
Example 4
Project: EZFilter   File: OffscreenImage.java   View Source Code Vote up 6 votes
public Bitmap capture(int width, int height) {
    mPipeline.onSurfaceChanged(null, width, height);
    mPipeline.startRender();
    mPipeline.onDrawFrame(null);

    int[] iat = new int[mWidth * mHeight];
    IntBuffer ib = IntBuffer.allocate(width * height);
    GLES20.glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, ib);

    int[] ia = ib.array();
    for (int i = 0; i < mHeight; i++) {
        System.arraycopy(ia, i * mWidth, iat, (mHeight - i - 1) * mWidth, mWidth);
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(IntBuffer.wrap(iat));

    mPipeline.onSurfaceDestroyed();

    // 释放EGL环境
    mInputSurface.release();
    mEgl.release();
    return bitmap;
}
 
Example 5
Project: screen-share-to-browser   File: RecordService.java   View Source Code Vote up 5 votes
private Function<ImageInfo, Bitmap> getBitmapFunction() {
    return new Function<ImageInfo, Bitmap>() {
        @Override
        public Bitmap apply(ImageInfo imageInfo) throws Exception {
            Bitmap bitmap = Bitmap.createBitmap(imageInfo.width + imageInfo.rowPadding / imageInfo.pixelStride, imageInfo.height,
                    Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(imageInfo.byteBuffer);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);

            return bitmap;
        }
    };
}
 
Example 6
Project: pc-android-controller-android   File: ScreenCaptureSocket.java   View Source Code Vote up 5 votes
@Override
protected Bitmap doInBackground(Image... params) {

    if (params == null || params.length < 1 || params[0] == null) {

        L.e(" params is null ...");
        return null;
    }

    Image image = params[0];

    int width = image.getWidth();
    int height = image.getHeight();
    final Image.Plane[] planes = image.getPlanes();
    final ByteBuffer buffer = planes[0].getBuffer();
    //每个像素的间距
    int pixelStride = planes[0].getPixelStride();
    //总的间距
    int rowStride = planes[0].getRowStride();
    image.close();
    int rowPadding = rowStride - pixelStride * width;
    Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer);
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
    image.close();

    compressAndWrite(bitmap);

    return null;
}
 
Example 7
Project: silly-android   File: ColoringTest.java   View Source Code Vote up 5 votes
/**
 * Tests the {@link Coloring#colorBitmap(Bitmap, int)} method.
 * <p>
 * Due to {@link org.robolectric.shadows.ShadowBitmap}'s empty implementation, this won't really work, so we can only test the transparency.
 */
@Test
public final void testColorBitmap() {
    final Bitmap.Config config = Bitmap.Config.ARGB_8888;
    final int width = 10, height = 10;
    final int[] allReds = new int[width * height];
    for (int i = 0; i < width * height; i++) {
        allReds[i] = Color.RED;
    }

    final Bitmap redSquare = Bitmap.createBitmap(allReds, width, height, config);
    assertNotNull("Created Bitmap is null", redSquare);

    // initialize red Bitmap's internal structures, otherwise it won't draw properly
    redSquare.prepareToDraw();
    final byte[] redPixels = new byte[redSquare.getWidth() * redSquare.getHeight() * 8];
    final ByteBuffer redBuffer = ByteBuffer.wrap(redPixels);
    redBuffer.order(ByteOrder.nativeOrder());
    redSquare.copyPixelsToBuffer(redBuffer);
    redSquare.copyPixelsFromBuffer(redBuffer);
    redSquare.prepareToDraw();

    final String redPixel = hex(redSquare.getPixel(width / 2, height / 2));
    final String errorRed = String.format("Error while creating red bitmap, middle pixel is %s", redPixel);
    assertEquals(errorRed, hex(Color.TRANSPARENT), redPixel);

    final Bitmap greenSquare = Coloring.colorBitmap(redSquare, Color.GREEN);
    assertNotNull("Created colored Bitmap is null", greenSquare);
    final String greenPixel = hex(greenSquare.getPixel(width / 2, height / 2));
    final String errorGreen = String.format("Error while coloring bitmap, middle pixel is %s", greenPixel);
    assertEquals(errorGreen, hex(Color.TRANSPARENT), greenPixel);
}
 
Example 8
Project: Auto.js   File: ImageWrapper.java   View Source Code Vote up 5 votes
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static Bitmap toBitmap(Image image) {
    Image.Plane plane = image.getPlanes()[0];
    ByteBuffer buffer = plane.getBuffer();
    buffer.position(0);
    int pixelStride = plane.getPixelStride();
    int rowPadding = plane.getRowStride() - pixelStride * image.getWidth();
    Bitmap bitmap = Bitmap.createBitmap(image.getWidth() + rowPadding / pixelStride, image.getHeight(), Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer);
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, image.getWidth(), image.getHeight());
    return bitmap;
}
 
Example 9
Project: Ftc2018RelicRecovery   File: FtcVuforia.java   View Source Code Vote up 5 votes
/**
 * This method gets a frame from the frame queue and returns the image that matches the format specified by the
 * configVideoSource method.
 *
 * @param frame specifies the frame object to hold image.
 * @return true if success, false otherwise.
 */
@Override
public boolean getFrame(Mat frame)
{
    boolean success = false;

    try
    {
        VuforiaLocalizer.CloseableFrame closeableFrame = localizer.getFrameQueue().take();

        for (int i = 0; i < closeableFrame.getNumImages(); i++)
        {
            Image image = closeableFrame.getImage(i);
            if (image.getWidth() == imageWidth && image.getHeight() == imageHeight &&
                    image.getFormat() == PIXEL_FORMAT.RGB565)
            {
                Bitmap bm = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.RGB_565);
                bm.copyPixelsFromBuffer(image.getPixels());
                Utils.bitmapToMat(bm, frame);
                break;
            }
        }

        closeableFrame.close();
        success = true;
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }

    return success;
}
 
Example 10
Project: EditPhoto   File: ImageEglSurface.java   View Source Code Vote up 5 votes
public Bitmap getBitmap() {
    ByteBuffer buf = ByteBuffer.allocateDirect(mWidth * mHeight * 4);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    GLES20.glReadPixels(0, 0, mWidth, mHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf);
    Bitmap bmp = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
    bmp.copyPixelsFromBuffer(buf);
    return bmp;
}
 
Example 11
Project: PlusGram   File: PhotoFilterView.java   View Source Code Vote up 5 votes
private Bitmap getRenderBufferBitmap() {
    ByteBuffer buffer = ByteBuffer.allocateDirect(renderBufferWidth * renderBufferHeight * 4);
    GLES20.glReadPixels(0, 0, renderBufferWidth, renderBufferHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);
    Bitmap bitmap = Bitmap.createBitmap(renderBufferWidth, renderBufferHeight, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer);
    return bitmap;
}
 
Example 12
Project: mao-android   File: EglSurfaceBase.java   View Source Code Vote up 5 votes
public Bitmap getFrameBitmap() {
    if (!mEglCore.isCurrent(mEGLSurface)) {
        throw new RuntimeException("Expected EGL context/surface is not current");
    }

    // glReadPixels fills in a "direct" ByteBuffer with what is essentially big-endian RGBA
    // data (i.e. a byte of red, followed by a byte of green...).  While the Bitmap
    // constructor that takes an int[] wants little-endian ARGB (blue/red swapped), the
    // Bitmap "copy pixels" method wants the same format GL provides.
    //
    // Ideally we'd have some way to re-use the ByteBuffer, especially if we're calling
    // here often.
    //
    // Making this even more interesting is the upside-down nature of GL, which means
    // our output will look upside down relative to what appears on screen if the
    // typical GL conventions are used.

    int width = getWidth();
    int height = getHeight();
    ByteBuffer buf = ByteBuffer.allocateDirect(width * height * 4);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    GLES20.glReadPixels(0, 0, width, height,
            GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf);
    //GlUtil.checkGlError("glReadPixels");
    buf.rewind();

    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bmp.copyPixelsFromBuffer(buf);

    Matrix matrix = new Matrix();
    matrix.preScale(1f, -1f);
    Bitmap bmp2 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, false);

    bmp.recycle();
    bmp = null;
    return bmp2;
}
 
Example 13
Project: AndroidRTC   File: EglRenderer.java   View Source Code Vote up 4 votes
private void notifyCallbacks(VideoRenderer.I420Frame frame, float[] texMatrix) {
  // Make temporary copy of callback list to avoid ConcurrentModificationException, in case
  // callbacks call addFramelistener or removeFrameListener.
  final ArrayList<FrameListenerAndParams> tmpList;
  if (frameListeners.isEmpty())
    return;
  tmpList = new ArrayList<>(frameListeners);
  frameListeners.clear();

  final float[] bitmapMatrix = RendererCommon.multiplyMatrices(
      RendererCommon.multiplyMatrices(texMatrix,
          mirror ? RendererCommon.horizontalFlipMatrix() : RendererCommon.identityMatrix()),
      RendererCommon.verticalFlipMatrix());

  for (FrameListenerAndParams listenerAndParams : tmpList) {
    final int scaledWidth = (int) (listenerAndParams.scale * frame.rotatedWidth());
    final int scaledHeight = (int) (listenerAndParams.scale * frame.rotatedHeight());

    if (scaledWidth == 0 || scaledHeight == 0) {
      listenerAndParams.listener.onFrame(null);
      continue;
    }

    if (bitmapTextureFramebuffer == null) {
      bitmapTextureFramebuffer = new GlTextureFrameBuffer(GLES20.GL_RGBA);
    }
    bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
    GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
        GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);

    if (frame.yuvFrame) {
      listenerAndParams.drawer.drawYuv(yuvTextures, bitmapMatrix, frame.rotatedWidth(),
          frame.rotatedHeight(), 0 /* viewportX */, 0 /* viewportY */, scaledWidth, scaledHeight);
    } else {
      listenerAndParams.drawer.drawOes(frame.textureId, bitmapMatrix, frame.rotatedWidth(),
          frame.rotatedHeight(), 0 /* viewportX */, 0 /* viewportY */, scaledWidth, scaledHeight);
    }

    final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
    GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
    GLES20.glReadPixels(
        0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
    GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");

    final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(bitmapBuffer);
    listenerAndParams.listener.onFrame(bitmap);
  }
}
 
Example 14
Project: VideoCRE   File: EglRenderer.java   View Source Code Vote up 4 votes
private void notifyCallbacks(
    VideoRenderer.I420Frame frame, int[] yuvTextures, float[] texMatrix, boolean wasRendered) {
  if (frameListeners.isEmpty())
    return;

  final float[] bitmapMatrix = RendererCommon.multiplyMatrices(
      RendererCommon.multiplyMatrices(texMatrix,
          mirror ? RendererCommon.horizontalFlipMatrix() : RendererCommon.identityMatrix()),
      RendererCommon.verticalFlipMatrix());

  Iterator<FrameListenerAndParams> it = frameListeners.iterator();
  while (it.hasNext()) {
    FrameListenerAndParams listenerAndParams = it.next();
    if (!wasRendered && listenerAndParams.applyFpsReduction) {
      continue;
    }
    it.remove();

    final int scaledWidth = (int) (listenerAndParams.scale * frame.rotatedWidth());
    final int scaledHeight = (int) (listenerAndParams.scale * frame.rotatedHeight());

    if (scaledWidth == 0 || scaledHeight == 0) {
      listenerAndParams.listener.onFrame(null);
      continue;
    }

    if (bitmapTextureFramebuffer == null) {
      bitmapTextureFramebuffer = new GlTextureFrameBuffer(GLES20.GL_RGBA);
    }
    bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
    GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
        GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);

    GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
    if (frame.yuvFrame) {
      listenerAndParams.drawer.drawYuv(yuvTextures, bitmapMatrix, frame.rotatedWidth(),
          frame.rotatedHeight(), 0 /* viewportX */, 0 /* viewportY */, scaledWidth, scaledHeight);
    } else {
      listenerAndParams.drawer.drawOes(frame.textureId, bitmapMatrix, frame.rotatedWidth(),
          frame.rotatedHeight(), 0 /* viewportX */, 0 /* viewportY */, scaledWidth, scaledHeight);
    }

    final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
    GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
    GLES20.glReadPixels(
        0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
    GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");

    final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(bitmapBuffer);
    listenerAndParams.listener.onFrame(bitmap);
  }
}
 
Example 15
Project: LaunchEnr   File: HolographicOutlineHelper.java   View Source Code Vote up 4 votes
/**
 * 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
Project: FlickLauncher   File: HolographicOutlineHelper.java   View Source Code Vote up 4 votes
public void applyExpensiveOutlineWithBlur(Bitmap srcDst, Canvas srcDstCanvas,
        boolean clipAlpha) {
    if (ProviderConfig.IS_DOGFOOD_BUILD && srcDst.getConfig() != Bitmap.Config.ALPHA_8) {
        throw new RuntimeException("Outline blue is only supported on alpha bitmaps");
    }

    // 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
    if (clipAlpha) {
        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 17
Project: FTC2016   File: BeaconUtils.java   View Source Code Vote up 4 votes
public static int getBeaconConfig(Image img, VuforiaTrackableDefaultListener beacon, CameraCalibration camCal) {

        OpenGLMatrix pose = beacon.getRawPose();

        if (pose != null && img != null && img.getPixels() != null) {

            Matrix34F rawPose = new Matrix34F();
            float[] poseData = Arrays.copyOfRange(pose.transposed().getData(), 0, 12);

            rawPose.setData(poseData);

            float[][] corners = new float[4][2];

            corners[0] = Tool.projectPoint(camCal, rawPose, new Vec3F(-127, 276, 0)).getData(); //upper left of beacon
            corners[1] = Tool.projectPoint(camCal, rawPose, new Vec3F(127, 276, 0)).getData(); //upper right of beacon
            corners[2] = Tool.projectPoint(camCal, rawPose, new Vec3F(127, -92, 0)).getData(); //lower right of beacon
            corners[3] = Tool.projectPoint(camCal, rawPose, new Vec3F(-127, -92, 0)).getData(); //lower left of beacon

            //getting camera image...
            Bitmap bm = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.RGB_565);
            bm.copyPixelsFromBuffer(img.getPixels());

            //turning the corner pixel coordinates into a proper bounding box
            Mat crop = bitmapToMat(bm, CvType.CV_8UC3);
            float x = Math.min(Math.min(corners[1][0], corners[3][0]), Math.min(corners[0][0], corners[2][0]));
            float y = Math.min(Math.min(corners[1][1], corners[3][1]), Math.min(corners[0][1], corners[2][1]));
            float width = Math.max(Math.abs(corners[0][0] - corners[2][0]), Math.abs(corners[1][0] - corners[3][0]));
            float height = Math.max(Math.abs(corners[0][1] - corners[2][1]), Math.abs(corners[1][1] - corners[3][1]));


            //make sure our bounding box doesn't go outside of the image
            //OpenCV doesn't like that...
            x = Math.max(x, 0);
            y = Math.max(y, 0);
            width = (x + width > crop.cols())? crop.cols() - x : width;
            height = (y + height > crop.rows())? crop.rows() - y : height;

            //cropping bounding box out of camera image
            final Mat cropped = new Mat(crop, new Rect((int) x, (int) y, (int) width, (int) height));

            //filtering out non-beacon-blue colours in HSV colour space
            Imgproc.cvtColor(cropped, cropped, Imgproc.COLOR_RGB2HSV_FULL);

            //get filtered mask
            //if pixel is within acceptable blue-beacon-colour range, it's changed to white.
            //Otherwise, it's turned to black
            Mat mask = new Mat();

            Core.inRange(cropped, BEACON_BLUE_LOW, BEACON_BLUE_HIGH, mask);
            Moments mmnts = Imgproc.moments(mask, true);

            //calculating centroid of the resulting binary mask via image moments
            Log.i("CentroidX", "" + ((mmnts.get_m10() / mmnts.get_m00())));
            Log.i("CentroidY", "" + ((mmnts.get_m01() / mmnts.get_m00())));

            //checking if blue either takes up the majority of the image (which means the beacon is all blue)
            //or if there's barely any blue in the image (which means the beacon is all red or off)
//            if (mmnts.get_m00() / mask.total() > 0.8) {
//                return VortexUtils.BEACON_ALL_BLUE;
//            } else if (mmnts.get_m00() / mask.total() < 0.1) {
//                return VortexUtils.BEACON_NO_BLUE;
//            }//elseif

            //Note: for some reason, we end up with a image that is rotated 90 degrees
            //if centroid is in the bottom half of the image, the blue beacon is on the left
            //if the centroid is in the top half, the blue beacon is on the right
            if ((mmnts.get_m01() / mmnts.get_m00()) < cropped.rows() / 2) {
                return BEACON_RED_BLUE;
            } else {
                return BEACON_BLUE_RED;
            }
        }

        return NOT_VISIBLE;
    }
 
Example 18
Project: mpeg-encoder   File: GLToolsAndroidTest.java   View Source Code Vote up 4 votes
/**
 * Test for {@link GLTools#drawFrame(Buffer, int, int, int)}.
 * @throws Exception by some fails
 */
@Test
public final void testDrawFrame() throws Exception {
    final EGLDisplay eglDisplay = GLTools.newDisplay();
    final EGLConfig eglConfig = GLTools.newConfig(eglDisplay, true);
    final EGLContext eglContext = GLTools.newContext(eglDisplay, eglConfig);
    final EGLSurface eglSurface =
            GLTools.newSurface(eglDisplay, eglConfig, FRAME_SIZE, FRAME_SIZE);

    GLTools.makeCurrent(eglDisplay, eglSurface, eglContext);

    final int[] attrs = new int[5];
    GLTools.newShader(attrs);
    final int texture = GLTools.newTexture(TEXTURE_LEVEL);

    // 1-st pass
    Bitmap bitmap = Bitmap.createBitmap(FRAME_SIZE, FRAME_SIZE, Bitmap.Config.RGB_565);
    bitmap.setPixel(0, 0, Color.RED); bitmap.setPixel(1, 0, Color.GREEN);
    bitmap.setPixel(0, 1, Color.BLUE); bitmap.setPixel(1, 1, Color.YELLOW);
    ByteBuffer buffer = ByteBuffer.allocate(FRAME_SIZE * FRAME_SIZE * 2);
    bitmap.copyPixelsToBuffer(buffer); bitmap.recycle();

    GLTools.makeCurrent(eglDisplay, eglSurface, eglContext);
    GLTools.drawFrame(buffer, FRAME_SIZE, FRAME_SIZE, 0); buffer.clear();
    //GLTools.swapBuffers(eglDisplay, eglSurface);

    buffer = ByteBuffer.allocateDirect(FRAME_SIZE * FRAME_SIZE * 4);
    GLES20.glReadPixels(0, 0, FRAME_SIZE, FRAME_SIZE,
            GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);

    bitmap = Bitmap.createBitmap(FRAME_SIZE, FRAME_SIZE, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer); buffer.clear(); //bitmap.eraseColor(Color.BLACK);

    Assert.assertArrayEquals(new int[]{bitmap.getPixel(0, 0)}, new int[]{Color.BLUE});
    Assert.assertArrayEquals(new int[]{bitmap.getPixel(1, 0)}, new int[]{Color.YELLOW});
    Assert.assertArrayEquals(new int[]{bitmap.getPixel(0, 1)}, new int[]{Color.RED});
    Assert.assertArrayEquals(new int[]{bitmap.getPixel(1, 1)}, new int[]{Color.GREEN});
    bitmap.recycle();

    // 2-nd pass
    bitmap = Bitmap.createBitmap(FRAME_SIZE, FRAME_SIZE, Bitmap.Config.RGB_565);
    bitmap.setPixel(0, 0, Color.YELLOW); bitmap.setPixel(1, 0, Color.BLUE);
    bitmap.setPixel(0, 1, Color.GREEN); bitmap.setPixel(1, 1, Color.RED);
    buffer = ByteBuffer.allocate(FRAME_SIZE * FRAME_SIZE * 2);
    bitmap.copyPixelsToBuffer(buffer); bitmap.recycle();

    GLTools.makeCurrent(eglDisplay, eglSurface, eglContext);
    GLTools.drawFrame(buffer, FRAME_SIZE, FRAME_SIZE, 0); buffer.clear();
    //GLTools.swapBuffers(eglDisplay, eglSurface);

    buffer = ByteBuffer.allocateDirect(FRAME_SIZE * FRAME_SIZE * 4);
    GLES20.glReadPixels(0, 0, FRAME_SIZE, FRAME_SIZE,
            GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);

    bitmap = Bitmap.createBitmap(FRAME_SIZE, FRAME_SIZE, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer); buffer.clear(); //bitmap.eraseColor(Color.BLACK);

    Assert.assertArrayEquals(new int[]{bitmap.getPixel(0, 0)}, new int[]{Color.GREEN});
    Assert.assertArrayEquals(new int[]{bitmap.getPixel(1, 0)}, new int[]{Color.RED});
    Assert.assertArrayEquals(new int[]{bitmap.getPixel(0, 1)}, new int[]{Color.YELLOW});
    Assert.assertArrayEquals(new int[]{bitmap.getPixel(1, 1)}, new int[]{Color.BLUE});
    bitmap.recycle();

    GLTools.closeTexture(texture, TEXTURE_LEVEL);
    GLTools.closeShader(attrs);

    GLTools.closeSurface(eglDisplay, eglSurface);
    GLTools.closeContext(eglDisplay, eglContext);
    GLTools.closeDisplay(eglDisplay);
}
 
Example 19
Project: AppRTC-Android   File: EglRenderer.java   View Source Code Vote up 4 votes
private void notifyCallbacks(VideoFrame frame, boolean wasRendered) {
  if (frameListeners.isEmpty())
    return;

  drawMatrix.reset();
  drawMatrix.preTranslate(0.5f, 0.5f);
  if (mirror)
    drawMatrix.preScale(-1f, 1f);
  drawMatrix.preScale(1f, -1f); // We want the output to be upside down for Bitmap.
  drawMatrix.preTranslate(-0.5f, -0.5f);

  Iterator<FrameListenerAndParams> it = frameListeners.iterator();
  while (it.hasNext()) {
    FrameListenerAndParams listenerAndParams = it.next();
    if (!wasRendered && listenerAndParams.applyFpsReduction) {
      continue;
    }
    it.remove();

    final int scaledWidth = (int) (listenerAndParams.scale * frame.getRotatedWidth());
    final int scaledHeight = (int) (listenerAndParams.scale * frame.getRotatedHeight());

    if (scaledWidth == 0 || scaledHeight == 0) {
      listenerAndParams.listener.onFrame(null);
      continue;
    }

    if (bitmapTextureFramebuffer == null) {
      bitmapTextureFramebuffer = new GlTextureFrameBuffer(GLES20.GL_RGBA);
    }
    bitmapTextureFramebuffer.setSize(scaledWidth, scaledHeight);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, bitmapTextureFramebuffer.getFrameBufferId());
    GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
        GLES20.GL_TEXTURE_2D, bitmapTextureFramebuffer.getTextureId(), 0);

    GLES20.glClearColor(0 /* red */, 0 /* green */, 0 /* blue */, 0 /* alpha */);
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
    frameDrawer.drawFrame(frame, listenerAndParams.drawer, drawMatrix, 0 /* viewportX */,
        0 /* viewportY */, scaledWidth, scaledHeight);

    final ByteBuffer bitmapBuffer = ByteBuffer.allocateDirect(scaledWidth * scaledHeight * 4);
    GLES20.glViewport(0, 0, scaledWidth, scaledHeight);
    GLES20.glReadPixels(
        0, 0, scaledWidth, scaledHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, bitmapBuffer);

    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
    GlUtil.checkNoGLES2Error("EglRenderer.notifyCallbacks");

    final Bitmap bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(bitmapBuffer);
    listenerAndParams.listener.onFrame(bitmap);
  }
}
 
Example 20
Project: SimpleUILauncher   File: HolographicOutlineHelper.java   View Source Code Vote up 4 votes
public void applyExpensiveOutlineWithBlur(Bitmap srcDst, Canvas srcDstCanvas,
        boolean clipAlpha) {
    if (ProviderConfig.IS_DOGFOOD_BUILD && srcDst.getConfig() != Bitmap.Config.ALPHA_8) {
        throw new RuntimeException("Outline blue is only supported on alpha bitmaps");
    }

    // 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
    if (clipAlpha) {
        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();
}