android.media.Image

Here are the examples of the java api android.media.Image taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

218 Examples 7

19 Source : ImageSaver.java
with BSD 2-Clause "Simplified" License
from zugaldia

/**
 * Save a photo to disk
 */
public clreplaced ImageSaver implements Runnable {

    private Image image;

    private File root;

    private String filename;

    public ImageSaver(Image image, File root, String filename) {
        this.image = image;
        this.root = root;
        this.filename = filename;
    }

    @Override
    public void run() {
        if (image == null) {
            Timber.w("Empty image, skipping.");
            return;
        }
        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(getDestination(root, filename));
            output.write(bytes);
        } catch (IOException e) {
            Timber.e(e, "Failed to save photo.");
        } finally {
            Timber.d("Photo saved.");
            image.close();
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    Timber.e(e, "Failed to close file system resources.");
                }
            }
        }
    }

    /**
     * Checks if external storage is available for read and write.
     */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    /**
     * Get the directory for the user's public pictures directory.
     * This is /storage/emulated/0/Pictures/robocar
     */
    public static File getRoot(String robocarFolder) {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), robocarFolder);
        if (file.mkdirs()) {
            Timber.d("Root folder created: %s.", file.getAbsolutePath());
        } else {
            Timber.w("Could not create root folder (it probably existed already): %s.", file.getAbsolutePath());
        }
        return file;
    }

    private static File getDestination(File root, String filename) {
        File destination = new File(root, filename);
        Timber.d("Saving to: %s", destination.getAbsolutePath());
        return destination;
    }
}

19 Source : CameraHelp2.java
with MIT License
from Zhaoss

private byte[] getYUVI420(Image image) {
    int width = image.getWidth();
    int height = image.getHeight();
    byte[] yuvI420 = new byte[image.getWidth() * image.getHeight() * 3 / 2];
    byte[] yData = new byte[image.getPlanes()[0].getBuffer().remaining()];
    byte[] uData = new byte[image.getPlanes()[1].getBuffer().remaining()];
    byte[] vData = new byte[image.getPlanes()[2].getBuffer().remaining()];
    image.getPlanes()[0].getBuffer().get(yData);
    image.getPlanes()[1].getBuffer().get(uData);
    image.getPlanes()[2].getBuffer().get(vData);
    System.arraycopy(yData, 0, yuvI420, 0, yData.length);
    int index = yData.length;
    for (int r = 0; r < height / 2; ++r) {
        for (int c = 0; c < width; c += 2) {
            // 各一个byte存一个U值和V值
            yuvI420[index++] = uData[r * width + c];
        }
    }
    for (int r = 0; r < height / 2; ++r) {
        for (int c = 0; c < width; c += 2) {
            // 各一个byte存一个U值和V值
            yuvI420[index++] = vData[r * width + c];
        }
    }
    return yuvI420;
}

19 Source : ScreenShotTest.java
with MIT License
from yahoojapan

@TargetApi(Build.VERSION_CODES.KITKAT)
@Test
public void onImageAvailable_正常() throws Exception {
    ImageReader imageReader = mock(ImageReader.clreplaced);
    Image image = mock(Image.clreplaced);
    Image.Plane plane = mock(Image.Plane.clreplaced);
    ByteBuffer byteBuffer = mock(ByteBuffer.clreplaced);
    doReturn(image).when(imageReader).acquireLatestImage();
    doReturn(new Image.Plane[] { plane }).when(image).getPlanes();
    doReturn(byteBuffer).when(plane).getBuffer();
    setupAppFeedbackContext();
    ScreenShot screenShot = spy(new ScreenShot());
    setInternalState(screenShot, "isRunning", true);
    screenShot.onImageAvailable(imageReader);
    verify(image).getPlanes();
    verify(plane).getBuffer();
    verify(image).close();
}

19 Source : ScreenShotTest.java
with MIT License
from yahoojapan

@TargetApi(Build.VERSION_CODES.KITKAT)
@Test
public void onImageAvailable_実行中じゃない() throws Exception {
    ImageReader imageReader = mock(ImageReader.clreplaced);
    Image image = mock(Image.clreplaced);
    Image.Plane plane = mock(Image.Plane.clreplaced);
    ByteBuffer byteBuffer = mock(ByteBuffer.clreplaced);
    doReturn(image).when(imageReader).acquireLatestImage();
    doReturn(new Image.Plane[] { plane }).when(image).getPlanes();
    doReturn(byteBuffer).when(plane).getBuffer();
    setupAppFeedbackContext();
    ScreenShot screenShot = spy(new ScreenShot());
    setInternalState(screenShot, "isRunning", false);
    screenShot.onImageAvailable(imageReader);
    verify(image, never()).getPlanes();
    verify(plane, never()).getBuffer();
    verify(image).close();
}

19 Source : ARCoreCamera.java
with GNU General Public License v3.0
from Welthungerhilfe

private void onProcessDepthData(Image image) {
    if (image == null) {
        Log.w(TAG, "onImageAvailable: Skipping null image.");
        return;
    }
    if (mShowDepth) {
        mDepthCameraPreview.setImageBitmap(ARCoreUtils.getDepthPreview(image, false));
    }
    Pose pose;
    synchronized (mLock) {
        pose = mPose;
    }
    Bitmap bitmap = null;
    long bestDiff = Long.MAX_VALUE;
    synchronized (mCache) {
        if (!mCache.isEmpty()) {
            for (Long timestamp : mCache.keySet()) {
                // in microseconds
                long diff = Math.abs(image.getTimestamp() - timestamp) / 1000;
                if (bestDiff > diff) {
                    bestDiff = diff;
                    bitmap = mCache.get(timestamp);
                }
            }
        }
    }
    if (bitmap != null && bestDiff < 50000) {
        for (ARCoreUtils.Camera2DataListener listener : mListeners) {
            listener.onDepthDataReceived(image, pose, mFrameIndex);
        }
        for (ARCoreUtils.Camera2DataListener listener : mListeners) {
            listener.onColorDataReceived(bitmap, mFrameIndex);
        }
        synchronized (mCache) {
            mCache.clear();
            mFrameIndex++;
        }
    }
    image.close();
}

19 Source : ImageSaver.java
with MIT License
from sandrios

/**
 * Created by Arpit Gandhi on 7/6/16.
 */
public clreplaced ImageSaver implements Runnable {

    private final static String TAG = "ImageSaver";

    private final Image image;

    private final File file;

    private ImageSaverCallback imageSaverCallback;

    public ImageSaver(Image image, File file, ImageSaverCallback imageSaverCallback) {
        this.image = image;
        this.file = file;
        this.imageSaverCallback = imageSaverCallback;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void run() {
        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(file);
            output.write(bytes);
            imageSaverCallback.onSuccessFinish();
        } catch (IOException ignore) {
            Log.e(TAG, "Can't save the image file.");
            imageSaverCallback.onError();
        } finally {
            image.close();
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    Log.e(TAG, "Can't release image or close the output stream.");
                }
            }
        }
    }

    public interface ImageSaverCallback {

        void onSuccessFinish();

        void onError();
    }
}

19 Source : NoOpChain.java
with MIT License
from Piasy

@Override
public void onFrameData(Image image, Runnable postProcessedTask) {
}

19 Source : Camera2PreviewCallback.java
with MIT License
from Piasy

@Override
public void onImageAvailable(ImageReader reader) {
    try {
        final Image image = reader.acquireLatestImage();
        if (image != null) {
            mCameraFrameCallback.onFrameData(image, image::close);
        }
    } catch (OutOfMemoryError | IllegalStateException e) {
        CameraCompat.onError(CameraCompat.ERR_UNKNOWN);
    }
}

19 Source : ImageSaver.java
with GNU General Public License v3.0
from OSUPCVLab

/**
 * Saves a JPEG/YUV_420_888 {@link Image} into the specified {@link File}.
 * Preliminary tests shows that saving YUV_420_888 takes on average 70ms
 * while saving JPEG takes 2.5ms which is 27 times faster.
 * Also the compressToJpeg method has been found to subject to a bug, see
 * https://blog.csdn.net/q979713444/article/details/80446404
 */
public clreplaced ImageSaver implements Runnable {

    /**
     * The image
     */
    private final Image mImage;

    /**
     * The file we save the image into.
     */
    private final File mFile;

    public ImageSaver(Image image, File file) {
        mImage = image;
        mFile = file;
    }

    @Override
    public void run() {
        long startTime = System.nanoTime();
        if (mImage.getFormat() == ImageFormat.JPEG) {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            long endTime = System.nanoTime();
            long duration = (endTime - startTime);
            Timber.d("ImageSaver saving jpeg takes %d", duration);
        } else if (mImage.getFormat() == ImageFormat.YUV_420_888) {
            // Collection of bytes of the image
            byte[] rez;
            // Convert to NV21 format
            // https://github.com/bytedeco/javacv/issues/298#issuecomment-169100091
            ByteBuffer buffer0 = mImage.getPlanes()[0].getBuffer();
            ByteBuffer buffer2 = mImage.getPlanes()[2].getBuffer();
            int buffer0_size = buffer0.remaining();
            int buffer2_size = buffer2.remaining();
            rez = new byte[buffer0_size + buffer2_size];
            // Load the final data var with the actual bytes
            buffer0.get(rez, 0, buffer0_size);
            buffer2.get(rez, buffer0_size, buffer2_size);
            // Byte output stream, so we can save the file
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            // Create YUV image file
            YuvImage yuvImage = new YuvImage(rez, ImageFormat.NV21, mImage.getWidth(), mImage.getHeight(), null);
            yuvImage.compressToJpeg(new Rect(0, 0, mImage.getWidth(), mImage.getHeight()), 90, out);
            byte[] imageBytes = out.toByteArray();
            // Display for the end user
            Bitmap bmp = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            // Export the file to disk
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(mFile);
                bmp.compress(Bitmap.CompressFormat.JPEG, 90, output);
                output.flush();
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            long endTime = System.nanoTime();
            long duration = (endTime - startTime);
            Timber.d("ImageSaver saving YUV takes %d", duration);
        } else {
            mImage.close();
        }
    }
}

19 Source : CameraDeepArView.java
with MIT License
from mtellect

@Override
public void frameAvailable(Image image) {
}

19 Source : OnScreenshotAvailable.java
with MIT License
from microsoft

private Bitmap getBitmapFromImage(Image image) throws ImageFormatException {
    int width = image.getWidth();
    int height = image.getHeight();
    if (width != metrics.widthPixels || height != metrics.heightPixels) {
        Logger.logError(TAG, "Received image of dimensions " + width + "x" + height + ", mismatches device DisplayMetrics " + metrics.widthPixels + "x" + metrics.heightPixels);
    }
    Bitmap bitmap = bitmapProvider.createBitmap(width, height, IMAGE_BITMAP_FORMAT);
    copyPixelsFromImagePlane(bitmap, image.getPlanes()[0], width, height);
    return bitmap;
}

19 Source : ImageSaver.java
with MIT License
from memfis19

/**
 * Created by memfis on 7/6/16.
 */
public clreplaced ImageSaver implements Runnable {

    private final static String TAG = "ImageSaver";

    private final Image image;

    private final File file;

    private ImageSaverCallback imageSaverCallback;

    public interface ImageSaverCallback {

        void onSuccessFinish();

        void onError();
    }

    public ImageSaver(Image image, File file, ImageSaverCallback imageSaverCallback) {
        this.image = image;
        this.file = file;
        this.imageSaverCallback = imageSaverCallback;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void run() {
        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(file);
            output.write(bytes);
            imageSaverCallback.onSuccessFinish();
        } catch (IOException ignore) {
            Log.e(TAG, "Can't save the image file.");
            imageSaverCallback.onError();
        } finally {
            image.close();
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    Log.e(TAG, "Can't release image or close the output stream.");
                }
            }
        }
    }
}

19 Source : ImageUtils.java
with MIT License
from Ma-Dan

public static int[] convertYUVToARGB(final Image image, final int previewWidth, final int previewHeight) {
    final Image.Plane[] planes = image.getPlanes();
    byte[][] yuvBytes = fillBytes(planes);
    return ImageUtils.convertYUV420ToARGB8888(yuvBytes[0], yuvBytes[1], yuvBytes[2], previewWidth, previewHeight, planes[0].getRowStride(), planes[1].getRowStride(), planes[1].getPixelStride());
}

19 Source : ImageUtil.java
with GNU General Public License v3.0
from InnoFang

private static byte[] YUV_420_888toNV21(Image image) {
    byte[] nv21;
    ByteBuffer yBuffer = image.getPlanes()[0].getBuffer();
    ByteBuffer uBuffer = image.getPlanes()[1].getBuffer();
    ByteBuffer vBuffer = image.getPlanes()[2].getBuffer();
    int ySize = yBuffer.remaining();
    int uSize = uBuffer.remaining();
    int vSize = vBuffer.remaining();
    nv21 = new byte[ySize + uSize + vSize];
    // U and V are swapped
    yBuffer.get(nv21, 0, ySize);
    vBuffer.get(nv21, ySize, vSize);
    uBuffer.get(nv21, ySize + vSize, uSize);
    return nv21;
}

19 Source : ImageMetadataSynchronizer.java
with Apache License 2.0
from google-research

/**
 * Enforces the invariant by sweeping all internal queues when an Image arrives. image cannot be
 * null.
 */
private void handleImageLocked(int readerIndex, Image image) {
    pendingImageQueues.get(readerIndex).addLast(image);
    sweepQueuesLocked();
}

19 Source : MainActivity.java
with MIT License
from fritzlabs

@Override
protected void setupImageForPrediction(Image image) {
// STEP 2: Create the FritzVisionImage object from media.Image
// ------------------------------------------------------------------------
// TODO: Add code for creating FritzVisionImage from a media.Image object
// ------------------------------------------------------------------------
// END STEP 2
}

19 Source : ScreenCapturer.java
with Mozilla Public License 2.0
from feifadaima

/**
 * Created by Stardust on 2017/5/17.
 */
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public clreplaced ScreenCapturer {

    private static final String LOG_TAG = "ScreenCapturer";

    private ImageReader mImageReader;

    private MediaProjection mMediaProjection;

    private VirtualDisplay mVirtualDisplay;

    private volatile Looper mImageAcquireLooper;

    private final Object mImageWaitingLock = new Object();

    private volatile Image mImage;

    private volatile Image mLatestImage;

    private final int mScreenWidth;

    private final int mScreenHeight;

    private final int mScreenDensity;

    private Handler mHandler;

    private volatile boolean mImageAvailable = false;

    public ScreenCapturer(Context context, Intent data, int screenWidth, int screenHeight, int screenDensity, Handler handler) {
        mScreenWidth = screenWidth;
        mScreenHeight = screenHeight;
        mScreenDensity = screenDensity;
        mHandler = handler;
        MediaProjectionManager manager = (MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        initVirtualDisplay(manager, data, screenWidth, screenHeight, screenDensity);
        mHandler = handler;
        startAcquireImageLoop();
    }

    public ScreenCapturer(Context context, Intent data, int screenWidth, int screenHeight) {
        this(context, data, screenWidth, screenHeight, ScreenMetrics.getDeviceScreenDensity(), null);
    }

    public ScreenCapturer(Context context, Intent data) {
        this(context, data, ScreenMetrics.getDeviceScreenWidth(), ScreenMetrics.getDeviceScreenHeight());
    }

    private void initVirtualDisplay(MediaProjectionManager manager, Intent data, int screenWidth, int screenHeight, int screenDensity) {
        mImageReader = ImageReader.newInstance(screenWidth, screenHeight, PixelFormat.RGBA_8888, 1);
        mMediaProjection = manager.getMediaProjection(Activity.RESULT_OK, data);
        mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror", screenWidth, screenHeight, screenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
    }

    private void startAcquireImageLoop() {
        if (mHandler != null) {
            setImageListener(mHandler);
            return;
        }
        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();
                mImageAcquireLooper = Looper.myLooper();
                setImageListener(new Handler());
                Looper.loop();
            }
        }).start();
    }

    private void setImageListener(Handler handler) {
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {

            @Override
            public void onImageAvailable(ImageReader reader) {
                if (mImageAvailable) {
                    return;
                }
                mLatestImage = reader.acquireLatestImage();
                if (mLatestImage != null) {
                    mImageAvailable = true;
                    synchronized (mImageWaitingLock) {
                        mImageWaitingLock.notify();
                    }
                }
            }
        }, handler);
    }

    @Nullable
    public Image capture() {
        if (!mImageAvailable) {
            waitForImageAvailable();
            return mLatestImage;
        }
        if (mLatestImage != null) {
            tryClose(mLatestImage);
        }
        mLatestImage = mImageReader.acquireLatestImage();
        return mLatestImage;
    }

    private void tryClose(Image image) {
        try {
            image.close();
        } catch (Exception ignored) {
        }
    }

    private void waitForImageAvailable() {
        Log.d(LOG_TAG, "waitForImageAvailable");
        synchronized (mImageWaitingLock) {
            try {
                mImageWaitingLock.wait();
            } catch (InterruptedException e) {
                throw new ScriptInterruptedException();
            }
        }
    }

    public int getScreenWidth() {
        return mScreenWidth;
    }

    public int getScreenHeight() {
        return mScreenHeight;
    }

    public int getScreenDensity() {
        return mScreenDensity;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void release() {
        if (mMediaProjection != null) {
            mMediaProjection.stop();
        }
        if (mVirtualDisplay != null) {
            mVirtualDisplay.release();
        }
        if (mImageReader != null) {
            mImageReader.close();
        }
        if (mImageAcquireLooper != null) {
            mImageAcquireLooper.quit();
        }
        if (mImage != null) {
            mImage.close();
        }
        if (mLatestImage != null) {
            mLatestImage.close();
        }
    }
}

19 Source : ColorFinder.java
with Mozilla Public License 2.0
from feifadaima

public Point findColor(Image image, int color) {
    return findColor(image, color, new Rect(0, 0, image.getWidth(), image.getHeight()));
}

19 Source : ImageSaver.java
with GNU General Public License v3.0
from eszdman

private void addRAW(Image image) {
    if (PhotonCamera.getSettings().selectedMode == CameraMode.UNLIMITED) {
        mUnlimitedProcessor.unlimitedCycle(image);
    } else {
        Log.d(TAG, "start buffer size:" + IMAGE_BUFFER.size());
        image.getFormat();
        IMAGE_BUFFER.add(image);
    }
}

19 Source : ImageSaver.java
with GNU General Public License v3.0
from eszdman

private void addYUV(Image image) {
    Log.d(TAG, "start buffersize:" + IMAGE_BUFFER.size());
    IMAGE_BUFFER.add(image);
    if (IMAGE_BUFFER.size() == PhotonCamera.getCaptureController().mMeasuredFrameCnt && PhotonCamera.getSettings().frameCount != 1) {
        // hdrxProcessor.start(dngFile, jpgFile, IMAGE_BUFFER, mImage.getFormat(),
        // CaptureController.mCameraCharacteristics, CaptureController.mCaptureResult,
        // () -> clearImageReader(mReader));
        IMAGE_BUFFER.clear();
    }
    if (PhotonCamera.getSettings().frameCount == 1) {
        IMAGE_BUFFER.clear();
        processingEventsListener.onProcessingFinished("YUV: Single Frame, Not Processed!");
    }
}

19 Source : ImageFrame.java
with GNU General Public License v3.0
from eszdman

public clreplaced ImageFrame {

    public ByteBuffer buffer;

    public Image image;

    public float luckyParameter;

    public int number;

    public IsoExpoSelector.ExpoPair pair;

    public ImageFrame(ByteBuffer in) {
        buffer = in;
    }
}

19 Source : ImageSaver.java
with Apache License 2.0
from duanhong169

clreplaced ImageSaver implements Runnable {

    private final Image image;

    private final String filePath;

    ImageSaver(Image image, String filePath) {
        this.image = image;
        this.filePath = filePath;
    }

    @Override
    public void run() {
        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(filePath);
            output.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            image.close();
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

19 Source : TestPBActivity.java
with MIT License
from djpetti

private boolean fullDetection(Image image, float[] eyeRegion) {
    String msg;
    boolean isEyeDetected = false;
    double[] theEyes = new double[] { -1, -1, -1, -1, -1, -1, -1, -1 };
    int numOfSavedFace = getQuatNum(theFaces);
    if (numOfSavedFace == 0) {
        ImageProcessHandler.doFaceEyeDetection(image, theFaces, theEyes, eyeRegion);
    } else {
        ImageProcessHandler.doFaceTracking(image, theFaces, theEyes, eyeRegion);
    }
    Log.d(LOG_TAG, String.valueOf(isEyeDetected));
    // display result
    int numOfFaces = getQuatNum(theFaces);
    if (numOfFaces == 0) {
        Log.d(LOG_TAG, "Face Not Found");
        msg = "Face Not Found";
    } else {
        Log.d(LOG_TAG, "Face Detected");
        msg = "Face has been detected\n";
        drawHandler.clear(frame_bounding_box);
        int bounding_box_x = (int) (TEXTURE_SIZE[0] * theFaces[0]);
        int bounding_box_y = (int) (TEXTURE_SIZE[1] * theFaces[1]);
        int bounding_box_width = (int) (TEXTURE_SIZE[0] * theFaces[2]);
        int bounding_box_height = (int) (TEXTURE_SIZE[1] * theFaces[3]);
        drawHandler.showBoundingBox(bounding_box_x, bounding_box_y, bounding_box_width, bounding_box_height, TEXTURE_SIZE[0], frame_bounding_box, true);
        int numOfEyes = getQuatNum(theEyes);
        Log.d(LOG_TAG, String.valueOf(numOfFaces) + " eye has been detected");
        msg = msg + String.valueOf(numOfEyes) + " eye has been detected";
        for (int i = 0; i < numOfEyes; i++) {
            bounding_box_x = (int) (TEXTURE_SIZE[0] * theEyes[i * 4]);
            bounding_box_y = (int) (TEXTURE_SIZE[1] * theEyes[i * 4 + 1]);
            bounding_box_width = (int) (TEXTURE_SIZE[0] * theEyes[i * 4 + 2]);
            bounding_box_height = (int) (TEXTURE_SIZE[1] * theEyes[i * 4 + 3]);
            drawHandler.showBoundingBox(bounding_box_x, bounding_box_y, bounding_box_width, bounding_box_height, TEXTURE_SIZE[0], frame_bounding_box, true);
        }
    }
    // initFaceArray(theFaces);
    result_board.setText(msg);
    return isEyeDetected;
}

19 Source : QrDetector2.java
with MIT License
from contactlutforrahman

void detect(Image image) {
    needsScheduling.set(true);
    if (imageToCheckLock.tryLock()) {
        // copy image if not in use
        try {
            nextImageSet.set(false);
            imageToCheck.copyImage(image);
        } finally {
            imageToCheckLock.unlock();
        }
    } else if (nextImageLock.tryLock()) {
        // if first image buffer is in use, use second buffer
        // one or the other should always be free but if not this
        // frame is dropped..
        try {
            nextImageSet.set(true);
            nextImage.copyImage(image);
        } finally {
            nextImageLock.unlock();
        }
    }
    maybeStartProcessing();
}

19 Source : GabrielClientActivity.java
with Apache License 2.0
from cmusatyalab

/**
 * ************* Convert imageformat to Byte arrays **********************
 */
/**
 * Convert imageformat YUV_420_888 to Byte arrays.
 */
private static byte[] imageToByte(Image image) {
    byte[] byteArray = null;
    byteArray = NV21toJPEG(YUV420toNV21(image), image.getWidth(), image.getHeight(), 100);
    return byteArray;
}

19 Source : FacialRecognitionFragment.java
with MIT License
from BioID-GmbH

/**
 * lazily initialize ImageReader and select preview size
 */
private void setupPreviewSizeAndImageReader() {
    if (previewSize == null) {
        previewSize = cameraHelper.selectPreviewSize(openCamera);
    }
    if (imageReader == null) {
        // should be at least 2 according to ImageReader.acquireLatestImage() doreplacedentation
        int maxImages = 2;
        imageReader = ImageReader.newInstance(previewSize.getWidth(), previewSize.getHeight(), ImageFormat.YUV_420_888, maxImages);
        imageReader.setOnImageAvailableListener(reader -> {
            Image img = reader.acquireLatestImage();
            if (img != null) {
                try {
                    int imageRotation = cameraHelper.getImageRotation(openCamera, getRelativeDisplayRotation());
                    Context ctx = requireContext().getApplicationContext();
                    // Make a in memory copy of the image to close the image from the reader as soon as possible.
                    // This helps the thread running the preview staying up to date.
                    Yuv420Image imgCopy = Yuv420Image.copyFrom(img, imageRotation, ctx);
                    presenter.onImageCaptured(imgCopy);
                } catch (NullPointerException e) {
                // Fragment is no longer attached to Activity -> no need to process the image anymore
                } finally {
                    img.close();
                }
            }
        }, null);
    }
}

19 Source : FakeImageProxy.java
with Apache License 2.0
from androidx

public void setImage(@Nullable Image image) {
    mImage = image;
}

19 Source : AndroidImageReaderProxy.java
with Apache License 2.0
from androidx

@Override
@Nullable
public synchronized ImageProxy acquireNextImage() {
    Image image;
    try {
        image = mImageReader.acquireNextImage();
    } catch (RuntimeException e) {
        /* In API level 23 or below,  it will throw "java.lang.RuntimeException:
               ImageReaderContext is not initialized" when ImageReader is closed. To make the
               behavior consistent as newer API levels,  we make it return null Image instead.*/
        if (isImageReaderContextNotInitializedException(e)) {
            image = null;
        } else {
            // only catch RuntimeException:ImageReaderContext is not initialized
            throw e;
        }
    }
    if (image == null) {
        return null;
    }
    return new AndroidImageProxy(image);
}

19 Source : AndroidImageReaderProxy.java
with Apache License 2.0
from androidx

@Override
@Nullable
public synchronized ImageProxy acquireLatestImage() {
    Image image;
    try {
        image = mImageReader.acquireLatestImage();
    } catch (RuntimeException e) {
        /* In API level 23 or below,  it will throw "java.lang.RuntimeException:
               ImageReaderContext is not initialized" when ImageReader is closed. To make the
               behavior consistent as newer API levels,  we make it return null Image instead.*/
        if (isImageReaderContextNotInitializedException(e)) {
            image = null;
        } else {
            // only catch RuntimeException:ImageReaderContext is not initialized
            throw e;
        }
    }
    if (image == null) {
        return null;
    }
    return new AndroidImageProxy(image);
}

19 Source : AndroidImageProxy.java
with Apache License 2.0
from androidx

/**
 * An {@link ImageProxy} which wraps around an {@link Image}.
 */
final clreplaced AndroidImageProxy implements ImageProxy {

    @GuardedBy("this")
    private final Image mImage;

    @GuardedBy("this")
    private final PlaneProxy[] mPlanes;

    private final ImageInfo mImageInfo;

    /**
     * Creates a new instance which wraps the given image.
     *
     * @param image to wrap
     * @return new {@link AndroidImageProxy} instance
     */
    AndroidImageProxy(Image image) {
        mImage = image;
        Image.Plane[] originalPlanes = image.getPlanes();
        if (originalPlanes != null) {
            mPlanes = new PlaneProxy[originalPlanes.length];
            for (int i = 0; i < originalPlanes.length; ++i) {
                mPlanes[i] = new PlaneProxy(originalPlanes[i]);
            }
        } else {
            mPlanes = new PlaneProxy[0];
        }
        mImageInfo = ImmutableImageInfo.create(TagBundle.emptyBundle(), image.getTimestamp(), 0);
    }

    @Override
    public synchronized void close() {
        mImage.close();
    }

    @Override
    @NonNull
    public synchronized Rect getCropRect() {
        return mImage.getCropRect();
    }

    @Override
    public synchronized void setCropRect(@Nullable Rect rect) {
        mImage.setCropRect(rect);
    }

    @Override
    public synchronized int getFormat() {
        return mImage.getFormat();
    }

    @Override
    public synchronized int getHeight() {
        return mImage.getHeight();
    }

    @Override
    public synchronized int getWidth() {
        return mImage.getWidth();
    }

    @Override
    @NonNull
    public synchronized ImageProxy.PlaneProxy[] getPlanes() {
        return mPlanes;
    }

    /**
     * An {@link ImageProxy.PlaneProxy} which wraps around an {@link Image.Plane}.
     */
    private static final clreplaced PlaneProxy implements ImageProxy.PlaneProxy {

        @GuardedBy("this")
        private final Image.Plane mPlane;

        PlaneProxy(Image.Plane plane) {
            mPlane = plane;
        }

        @Override
        public synchronized int getRowStride() {
            return mPlane.getRowStride();
        }

        @Override
        public synchronized int getPixelStride() {
            return mPlane.getPixelStride();
        }

        @Override
        @NonNull
        public synchronized ByteBuffer getBuffer() {
            return mPlane.getBuffer();
        }
    }

    @Override
    @NonNull
    public ImageInfo getImageInfo() {
        return mImageInfo;
    }

    @Override
    @ExperimentalGetImage
    public synchronized Image getImage() {
        return mImage;
    }
}

19 Source : AndroidImageProxyTest.java
with Apache License 2.0
from androidx

/**
 * Unit tests for {@link AndroidImageProxy}.
 */
@SmallTest
@RunWith(AndroidJUnit4.clreplaced)
public final clreplaced AndroidImageProxyTest {

    private static final long INITIAL_TIMESTAMP = 138990020L;

    private final Image mImage = mock(Image.clreplaced);

    private final Image.Plane mYPlane = mock(Image.Plane.clreplaced);

    private final Image.Plane mUPlane = mock(Image.Plane.clreplaced);

    private final Image.Plane mVPlane = mock(Image.Plane.clreplaced);

    private ImageProxy mImageProxy;

    @Before
    public void setUp() {
        when(mImage.getPlanes()).thenReturn(new Image.Plane[] { mYPlane, mUPlane, mVPlane });
        when(mYPlane.getRowStride()).thenReturn(640);
        when(mYPlane.getPixelStride()).thenReturn(1);
        when(mYPlane.getBuffer()).thenReturn(ByteBuffer.allocateDirect(640 * 480));
        when(mUPlane.getRowStride()).thenReturn(320);
        when(mUPlane.getPixelStride()).thenReturn(1);
        when(mUPlane.getBuffer()).thenReturn(ByteBuffer.allocateDirect(320 * 240));
        when(mVPlane.getRowStride()).thenReturn(320);
        when(mVPlane.getPixelStride()).thenReturn(1);
        when(mVPlane.getBuffer()).thenReturn(ByteBuffer.allocateDirect(320 * 240));
        when(mImage.getTimestamp()).thenReturn(INITIAL_TIMESTAMP);
        mImageProxy = new AndroidImageProxy(mImage);
    }

    @Test
    public void close_closesWrappedImage() {
        mImageProxy.close();
        verify(mImage).close();
    }

    @Test
    public void getCropRect_returnsCropRectForWrappedImage() {
        when(mImage.getCropRect()).thenReturn(new Rect(0, 0, 20, 20));
        replacedertThat(mImageProxy.getCropRect()).isEqualTo(new Rect(0, 0, 20, 20));
    }

    @Test
    public void setCropRect_setsCropRectForWrappedImage() {
        mImageProxy.setCropRect(new Rect(0, 0, 40, 40));
        verify(mImage).setCropRect(new Rect(0, 0, 40, 40));
    }

    @Test
    public void getFormat_returnsFormatForWrappedImage() {
        when(mImage.getFormat()).thenReturn(ImageFormat.YUV_420_888);
        replacedertThat(mImageProxy.getFormat()).isEqualTo(ImageFormat.YUV_420_888);
    }

    @Test
    public void getHeight_returnsHeightForWrappedImage() {
        when(mImage.getHeight()).thenReturn(480);
        replacedertThat(mImageProxy.getHeight()).isEqualTo(480);
    }

    @Test
    public void getWidth_returnsWidthForWrappedImage() {
        when(mImage.getWidth()).thenReturn(640);
        replacedertThat(mImageProxy.getWidth()).isEqualTo(640);
    }

    @Test
    public void getTimestamp_returnsTimestampForWrappedImage() {
        replacedertThat(mImageProxy.getImageInfo().getTimestamp()).isEqualTo(INITIAL_TIMESTAMP);
    }

    @Test
    public void getPlanes_returnsPlanesForWrappedImage() {
        ImageProxy.PlaneProxy[] wrappedPlanes = mImageProxy.getPlanes();
        Image.Plane[] originalPlanes = new Image.Plane[] { mYPlane, mUPlane, mVPlane };
        replacedertThat(wrappedPlanes.length).isEqualTo(3);
        for (int i = 0; i < 3; ++i) {
            replacedertThat(wrappedPlanes[i].getRowStride()).isEqualTo(originalPlanes[i].getRowStride());
            replacedertThat(wrappedPlanes[i].getPixelStride()).isEqualTo(originalPlanes[i].getPixelStride());
            replacedertThat(wrappedPlanes[i].getBuffer()).isEqualTo(originalPlanes[i].getBuffer());
        }
    }

    @Test
    @UseExperimental(markerClreplaced = ExperimentalGetImage.clreplaced)
    public void getImage_returnsWrappedImage() {
        replacedertThat(mImageProxy.getImage()).isEqualTo(mImage);
    }
}

19 Source : VideoProcessor.java
with Apache License 2.0
from androidthings

private void imageToBitmap(Image image, Bitmap bitmap) {
    if (image == null) {
        return;
    }
    convertYUVImageToBitmap(image, bitmap, output, cachedYuvBytes);
}

18 Source : OneCameraZslImpl.java
with Apache License 2.0
from Yuloran

/**
 * Given an image reader, extracts the JPEG image bytes and then closes the
 * reader.
 *
 * @param img     the image from which to extract jpeg bytes or compress to
 *                jpeg.
 * @param degrees the angle to rotate the image clockwise, in degrees. Rotation is
 *                only applied to YUV images.
 * @return The bytes of the JPEG image. Newly allocated.
 */
private byte[] acquireJpegBytes(Image img, int degrees) {
    ByteBuffer buffer;
    if (img.getFormat() == ImageFormat.JPEG) {
        Image.Plane plane0 = img.getPlanes()[0];
        buffer = plane0.getBuffer();
        byte[] imageBytes = new byte[buffer.remaining()];
        buffer.get(imageBytes);
        buffer.rewind();
        return imageBytes;
    } else if (img.getFormat() == ImageFormat.YUV_420_888) {
        buffer = mJpegByteBufferPool.acquire();
        if (buffer == null) {
            buffer = ByteBuffer.allocateDirect(img.getWidth() * img.getHeight() * 3);
        }
        int numBytes = JpegUtilNative.compressJpegFromYUV420Image(new AndroidImageProxy(img), buffer, JPEG_QUALITY, degrees);
        if (numBytes < 0) {
            throw new RuntimeException("Error compressing jpeg.");
        }
        buffer.limit(numBytes);
        byte[] imageBytes = new byte[buffer.remaining()];
        buffer.get(imageBytes);
        buffer.clear();
        mJpegByteBufferPool.release(buffer);
        return imageBytes;
    } else {
        throw new RuntimeException("Unsupported image format.");
    }
}

18 Source : ImageCaptureManager.java
with Apache License 2.0
from Yuloran

@Override
public void onImageAvailable(ImageReader reader) {
    long startTime = SystemClock.currentThreadTimeMillis();
    final Image img = reader.acquireLatestImage();
    if (img != null) {
        int numOpenImages = mNumOpenImages.incrementAndGet();
        if (DEBUG_PRINT_OPEN_IMAGE_COUNT) {
            Log.v(TAG, "Acquired an image. Number of open images = " + numOpenImages);
        }
        long timestamp = img.getTimestamp();
        // Try to place the newly-acquired image into the ring buffer.
        boolean swapSuccess = doImageSwap(img);
        if (!swapSuccess) {
            // If we were unable to save the image to the ring buffer, we
            // must close it now.
            // We should only get here if the ring buffer is closed.
            img.close();
            numOpenImages = mNumOpenImages.decrementAndGet();
            if (DEBUG_PRINT_OPEN_IMAGE_COUNT) {
                Log.v(TAG, "Closed an image. Number of open images = " + numOpenImages);
            }
        }
        tryExecutePendingCaptureRequest(timestamp);
        long endTime = SystemClock.currentThreadTimeMillis();
        long totTime = endTime - startTime;
        if (totTime > DEBUG_MAX_IMAGE_CALLBACK_DUR) {
            // If it takes too long to swap elements, we will start skipping
            // preview frames, resulting in visible jank.
            Log.v(TAG, "onImageAvailable() took " + totTime + "ms");
        }
    }
}

18 Source : ImageCaptureManager.java
with Apache License 2.0
from Yuloran

private boolean doImageSwap(final Image newImage) {
    return mCapturedImageBuffer.swapLeast(newImage.getTimestamp(), new SwapTask<CapturedImage>() {

        @Override
        public CapturedImage create() {
            CapturedImage image = new CapturedImage();
            image.addImage(newImage);
            return image;
        }

        @Override
        public CapturedImage swap(CapturedImage oldElement) {
            oldElement.reset();
            CapturedImage image = new CapturedImage();
            image.addImage(newImage);
            return image;
        }

        @Override
        public void update(CapturedImage existingElement) {
            existingElement.addImage(newImage);
        }

        @Override
        public long getSwapKey() {
            return -1;
        }
    });
}

18 Source : ImageCaptureManager.java
with Apache License 2.0
from Yuloran

/**
 * Tries to capture a pinned image for the given key from the ring-buffer.
 *
 * @return the pair of (image, captureResult) if image is found, null
 * otherwise.
 */
public Pair<Image, TotalCaptureResult> tryCapturePinnedImage(long timestamp) {
    final Pair<Long, CapturedImage> toCapture = mCapturedImageBuffer.tryGetPinned(timestamp);
    Image pinnedImage = null;
    TotalCaptureResult imageCaptureResult = null;
    // Return an Image
    if (toCapture != null && toCapture.second != null) {
        pinnedImage = toCapture.second.tryGetImage();
        imageCaptureResult = toCapture.second.tryGetMetadata();
    }
    return Pair.create(pinnedImage, imageCaptureResult);
}

18 Source : AndroidImageReaderProxy.java
with Apache License 2.0
from Yuloran

@Override
@Nullable
public ImageProxy acquireNextImage() {
    synchronized (mLock) {
        Image image = mDelegate.acquireNextImage();
        if (image == null) {
            return null;
        } else {
            return new AndroidImageProxy(image);
        }
    }
}

18 Source : AndroidImageReaderProxy.java
with Apache License 2.0
from Yuloran

@Override
@Nullable
public ImageProxy acquireLatestImage() {
    synchronized (mLock) {
        Image image = mDelegate.acquireLatestImage();
        if (image == null) {
            return null;
        } else {
            return new AndroidImageProxy(image);
        }
    }
}

18 Source : AndroidImageProxy.java
with Apache License 2.0
from Yuloran

/**
 * An {@link ImageProxy} backed by an {@link android.media.Image}.
 */
@ThreadSafe
public clreplaced AndroidImageProxy implements ImageProxy {

    /**
     * An {@link ImageProxy.Plane} backed by an
     * {@link android.media.Image.Plane}.
     */
    public clreplaced Plane implements ImageProxy.Plane {

        private final int mPixelStride;

        private final int mRowStride;

        private final ByteBuffer mBuffer;

        public Plane(Image.Plane imagePlane) {
            // Copying out the contents of the Image.Plane means that this Plane
            // implementation can be thread-safe (without requiring any locking)
            // and can have getters which do not throw a RuntimeException if
            // the underlying Image is closed.
            mPixelStride = imagePlane.getPixelStride();
            mRowStride = imagePlane.getRowStride();
            mBuffer = imagePlane.getBuffer();
        }

        /**
         * @see {@link android.media.Image.Plane#getRowStride}
         */
        @Override
        public int getRowStride() {
            return mRowStride;
        }

        /**
         * @see {@link android.media.Image.Plane#getPixelStride}
         */
        @Override
        public int getPixelStride() {
            return mPixelStride;
        }

        /**
         * @see {@link android.media.Image.Plane#getBuffer}
         */
        @Override
        public ByteBuffer getBuffer() {
            return mBuffer;
        }
    }

    private final Object mLock;

    /**
     * {@link android.media.Image} is not thread-safe, so all interactions must
     * be guarded by {@link #mLock}.
     */
    @GuardedBy("mLock")
    private final android.media.Image mImage;

    private final int mFormat;

    private final int mWidth;

    private final int mHeight;

    private final long mTimestamp;

    private final ImmutableList<ImageProxy.Plane> mPlanes;

    @GuardedBy("mLock")
    private Rect mCropRect;

    public AndroidImageProxy(android.media.Image image) {
        mLock = new Object();
        mImage = image;
        // Copying out the contents of the Image means that this Image
        // implementation can be thread-safe (without requiring any locking)
        // and can have getters which do not throw a RuntimeException if
        // the underlying Image is closed.
        mFormat = mImage.getFormat();
        mWidth = mImage.getWidth();
        mHeight = mImage.getHeight();
        mTimestamp = mImage.getTimestamp();
        Image.Plane[] planes;
        planes = mImage.getPlanes();
        if (planes == null) {
            mPlanes = ImmutableList.of();
        } else {
            List<ImageProxy.Plane> wrappedPlanes = new ArrayList<>(planes.length);
            for (int i = 0; i < planes.length; i++) {
                wrappedPlanes.add(new Plane(planes[i]));
            }
            mPlanes = ImmutableList.copyOf(wrappedPlanes);
        }
    }

    /**
     * @see {@link android.media.Image#getCropRect}
     */
    @Override
    public Rect getCropRect() {
        synchronized (mLock) {
            try {
                mCropRect = mImage.getCropRect();
            } catch (IllegalStateException imageClosedException) {
                // If the image is closed, then just return the cached CropRect.
                return mCropRect;
            }
            return mCropRect;
        }
    }

    /**
     * @see {@link android.media.Image#setCropRect}
     */
    @Override
    public void setCropRect(Rect cropRect) {
        synchronized (mLock) {
            mCropRect = cropRect;
            try {
                mImage.setCropRect(cropRect);
            } catch (IllegalStateException imageClosedException) {
            // Ignore.
            }
        }
    }

    /**
     * @see {@link android.media.Image#getFormat}
     */
    @Override
    public int getFormat() {
        return mFormat;
    }

    /**
     * @see {@link android.media.Image#getHeight}
     */
    @Override
    public int getHeight() {
        return mHeight;
    }

    /**
     * @see {@link android.media.Image#getPlanes}
     */
    @Override
    public List<ImageProxy.Plane> getPlanes() {
        return mPlanes;
    }

    /**
     * @see {@link android.media.Image#getTimestamp}
     */
    @Override
    public long getTimestamp() {
        return mTimestamp;
    }

    /**
     * @see {@link android.media.Image#getWidth}
     */
    @Override
    public int getWidth() {
        return mWidth;
    }

    /**
     * @see {@link android.media.Image#close}
     */
    @Override
    public void close() {
        synchronized (mLock) {
            mImage.close();
        }
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this).add("format", getFormat()).add("timestamp", getTimestamp()).add("width", getWidth()).add("height", getHeight()).toString();
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (!(other instanceof ImageProxy)) {
            return false;
        }
        ImageProxy otherImage = (ImageProxy) other;
        return otherImage.getFormat() == getFormat() && otherImage.getWidth() == getWidth() && otherImage.getHeight() == getHeight() && otherImage.getTimestamp() == getTimestamp();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getFormat(), getWidth(), getHeight(), getTimestamp());
    }
}

18 Source : AutomotivePlanner.java
with MIT License
from via-intelligent-vision

/**
 *  Buffer image frame to task.
 * @param missionID buffer target task.
 * @param frame is the object of {@link android.media.Image}.
 * @param roiX the x of roi.
 * @param roiY the y of roi.
 * @param roiWidth the width of roi.
 * @param roiHeight the height of roi.
 * @return true will return if operation success, otherwise, false will return. if the task is inactive, this operation will return false.
 * @exception IllegalArgumentException will throw if the channel of frame not 3.
 */
public boolean bufferFrame(@NonNull SensingTaskID missionID, @NonNull Image frame, int roiX, int roiY, int roiWidth, int roiHeight) {
    boolean ret = false;
    SensingUnit unit = mSensingUnitList.get(missionID.ordinal());
    if (frame != null && unit != null && unit.module != null && unit.task != null) {
        if (frame.getPlanes().length == 3) {
            // YUV or RGB
            Image.Plane yPlane = frame.getPlanes()[0];
            Image.Plane uPlane = frame.getPlanes()[1];
            Image.Plane vPlane = frame.getPlanes()[2];
            // TODO : check frame format is support or not.
            boolean isFormatValid = true;
            // buffer frane
            if (isFormatValid) {
                ret = unit.module.bufferFrame(yPlane.getBuffer(), uPlane.getBuffer(), vPlane.getBuffer(), frame.getWidth(), frame.getHeight(), yPlane.getRowStride(), uPlane.getRowStride(), vPlane.getRowStride(), yPlane.getPixelStride(), uPlane.getPixelStride(), vPlane.getPixelStride(), roiX, roiY, roiWidth, roiHeight);
                unit.task.notifyFrameReady();
            }
        } else {
            throw new IllegalArgumentException("The channel of source frame must be 3 , current is " + frame.getPlanes().length);
        }
    }
    return ret;
}

18 Source : ImageWrapper.java
with Mozilla Public License 2.0
from tzz2015

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static ImageWrapper ofImage(Image image) {
    if (image == null) {
        return null;
    }
    return new ImageWrapper(toBitmap(image));
}

18 Source : VNCServer.java
with BSD 3-Clause "New" or "Revised" License
from TeskaLabs

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void push(Image image, int pixelFormat) {
    Image.Plane[] planes = image.getPlanes();
    ByteBuffer b = planes[0].getBuffer();
    if (pixelFormat == PixelFormat.RGBA_8888) {
        // planes[0].getPixelStride() has to be 4 (32 bit)
        jni_push_pixels_rgba_8888(b, planes[0].getRowStride());
    } else if (pixelFormat == PixelFormat.RGB_565) {
        // planes[0].getPixelStride() has to be 16 (16 bit)
        jni_push_pixels_rgba_565(b, planes[0].getRowStride());
    } else {
        Log.e(TAG, "Image reader acquired unsupported image format " + pixelFormat);
    }
}

18 Source : QuickWindowFloatView.java
with Apache License 2.0
from sdwfqin

private void startCapture() {
    Image image = mImageReader.acquireLatestImage();
    if (image == null) {
        // 开始截屏
        getVirtualDisplay();
        LogUtils.e("getVirtualDisplay");
        show();
    } else {
        // 保存截屏
        mSubscribe = Observable.create((ObservableOnSubscribe<Bitmap>) emitter -> {
            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();
            File fileImage = null;
            if (bitmap != null) {
                try {
                    fileImage = new File(getContext().getExternalMediaDirs()[0], System.currentTimeMillis() + ".jpg");
                    if (!fileImage.exists()) {
                        fileImage.createNewFile();
                    }
                    FileOutputStream out = new FileOutputStream(fileImage);
                    if (out != null) {
                        ToastUtils.showShort("正在保存中...");
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                        out.flush();
                        out.close();
                        Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri contentUri = Uri.fromFile(fileImage);
                        media.setData(contentUri);
                        getContext().sendBroadcast(media);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    fileImage = null;
                }
            }
            if (fileImage != null) {
                emitter.onNext(bitmap);
            }
            emitter.onComplete();
        }).compose(RxSchedulersUtils.rxObservableSchedulerHelper()).subscribe(bitmap -> {
            // 预览图片
            if (bitmap != null) {
                ToastUtils.showShort("截图已经成功保存到相册");
                mIv_img.setImageBitmap(bitmap);
            }
        }, throwable -> {
        }, this::show);
    }
}

18 Source : YUVTools.java
with Apache License 2.0
from rome753

public static ImageBytes getBytesFromImage(Image image) {
    final Image.Plane[] planes = image.getPlanes();
    Image.Plane p0 = planes[0];
    Image.Plane p1 = planes[1];
    Image.Plane p2 = planes[2];
    ByteBuffer b0 = p0.getBuffer();
    ByteBuffer b1 = p1.getBuffer();
    ByteBuffer b2 = p2.getBuffer();
    int r0 = b0.remaining();
    int r1 = b1.remaining();
    int r2 = b2.remaining();
    int w0 = p0.getRowStride();
    int h0 = r0 / w0;
    if (r0 % w0 > 0)
        h0++;
    int w1 = p1.getRowStride();
    int h1 = r1 / w1;
    if (r1 % w1 > 1)
        h1++;
    int w2 = p2.getRowStride();
    int h2 = r2 / w2;
    if (r2 % w2 > 2)
        h2++;
    int y = w0 * h0;
    int u = w1 * h1;
    int v = w2 * h2;
    byte[] bytes = new byte[y + u + v];
    b0.get(bytes, 0, r0);
    // u
    b1.get(bytes, y, r1);
    // v
    b2.get(bytes, y + u, r2);
    return new ImageBytes(bytes, w0, h0);
}

18 Source : YUVTools.java
with Apache License 2.0
from rome753

/**
 * 从ImageReader中获取byte[]数据
 */
public static ImageBytes getBytesFromImageReader(ImageReader imageReader) {
    try (Image image = imageReader.acquireNextImage()) {
        return getBytesFromImage(image);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

18 Source : YUVDetectView.java
with Apache License 2.0
from rome753

public void input(final Image image) {
    final ImageBytes imageBytes = YUVTools.getBytesFromImage(image);
    if (imageBytes != null) {
        final int w = isFlip ? imageBytes.height : imageBytes.width;
        final int h = isFlip ? imageBytes.width : imageBytes.height;
        displayImage(imageBytes.bytes, w, h);
    }
}

18 Source : RScanCamera.java
with BSD 3-Clause "New" or "Revised" License
from rhymelph

private Result decodeImage(Image image) {
    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    byte[] array = new byte[buffer.remaining()];
    buffer.get(array);
    // 图片宽度
    int width = image.getWidth();
    // 图片高度
    int height = image.getHeight();
    setAutoOpenFlash(width, height, array);
    PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(array, width, height, 0, 0, width, height, false);
    BinaryBitmap binaryBitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
    try {
        return reader.decode(binaryBitmap);
    } catch (Exception e) {
        binaryBitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
        try {
            return reader.decode(binaryBitmap);
        } catch (NotFoundException ex) {
        // ex.printStackTrace();
        }
    // Log.d(TAG, "decodeImage: rotate45");
    // binaryBitmap = binaryBitmap.rotateCounterClockwise45();
    // try {
    // return reader.decodeWithState(binaryBitmap);
    // } catch (NotFoundException ex) {
    // Log.d(TAG, "decodeImage: rotate90");
    // //          Log.d(TAG, "replacedyze: error ");
    // binaryBitmap = binaryBitmap.rotateCounterClockwise45();
    // try {
    // return reader.decodeWithState(binaryBitmap);
    // } catch (NotFoundException ex2) {
    // //          Log.d(TAG, "replacedyze: error ");
    // 
    // }
    // }
    // Log.d(TAG, "replacedyze: error ");
    } finally {
        buffer.clear();
        reader.reset();
    }
    return null;
}

18 Source : GPUImageChain.java
with MIT License
from Piasy

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onFrameData(final Image image, final Runnable postProcessedTask) {
    final int width = image.getWidth();
    final int height = image.getHeight();
    if (mGLRgbaBuffer == null) {
        mGLRgbaBuffer = ByteBuffer.allocateDirect(width * height * 4);
    }
    if (mGLYuvBuffer == null) {
        // 16 bytes alignment
        int bufHeight = (width * mGLRender.getFrameWidth() / mGLRender.getFrameHeight()) & 0xfffffff0;
        mGLYuvBuffer = ByteBuffer.allocateDirect(width * bufHeight * 3 / 2);
    }
    if (!mGLRender.isBusyDrawing()) {
        RgbYuvConverter.image2rgba(image, mGLRgbaBuffer.array());
        mGLRender.scheduleDrawFrame(mGLRgbaBuffer, width, height, () -> {
            if (!mGLRender.isEnableFilter() && !mGLRender.isPaused()) {
                sendNormalImage(image);
            }
            postProcessedTask.run();
        });
    } else {
        postProcessedTask.run();
    }
}

18 Source : GPUImageChain.java
with MIT License
from Piasy

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void sendNormalImage(Image image) {
    if (mIsFrontCamera && mEnableMirror) {
        if (mGLRender.getRotation() == Rotation.ROTATION_90) {
            RgbYuvConverter.image2yuvCropFlip(image, mGLRender.getVideoHeight(), mGLYuvBuffer.array());
        } else {
            RgbYuvConverter.image2yuvCropRotateC180Flip(image, mGLRender.getVideoHeight(), mGLYuvBuffer.array());
        }
    } else {
        if (mGLRender.getRotation() == Rotation.ROTATION_90) {
            RgbYuvConverter.image2yuvCropRotateC180(image, mGLRender.getVideoHeight(), mGLYuvBuffer.array());
        } else {
            RgbYuvConverter.image2yuvCrop(image, mGLRender.getVideoHeight(), mGLYuvBuffer.array());
        }
    }
    mVideoCaptureCallback.onFrameData(mGLYuvBuffer.array(), image.getWidth(), mGLRender.getVideoHeight());
}

18 Source : Images.java
with Mozilla Public License 2.0
from newPersonKing

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ImageWrapper captureScreen() {
    ScriptRuntime.requiresApi(21);
    if (mScreenCapturer == null) {
        throw new SecurityException("No screen capture permission");
    }
    Image capture = mScreenCapturer.capture();
    if (capture == mPreCapture && mPreCaptureImage != null) {
        return mPreCaptureImage;
    }
    mPreCapture = capture;
    if (mPreCaptureImage != null) {
        mPreCaptureImage.recycle();
    }
    mPreCaptureImage = ImageWrapper.ofImage(capture);
    return mPreCaptureImage;
}

See More Examples