将字节数组图像传递给下一个Activity

时间:2018-05-28 14:11:32

标签: android layout

我的应用程序包括Image Capture Face Recognition我需要实现的是将字节数组图像转换为位图,并将位图传递给下一个Activity,下一个Activity将接收位图并在图像视图中显示它,而不是转换将位图转换为base 64。

我不知道如何将上述任务应用到我现有的代码中。 因此,当捕获图像时,它会显示,一旦点击保存按钮就会将图像传递给下一个活动,并再次将位图转换为base64。

FaceTrackerAcivity.java

public final class FaceTrackerActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "FaceTracker";

private CameraSource mCameraSource = null;

private CameraSourcePreview mPreview;
private GraphicOverlay mGraphicOverlay;
private ImageView btnCapture;
private ImageView btnChangeCamera;
private ImageView btnCancel;
private ImageView btnSave;
private FrameLayout frmResult;
private ImageView imgPicture;


Bitmap bmp;
private static final int RC_HANDLE_GMS = 9001;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private static final int RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM = 3;
private int cameraId = CameraSource.CAMERA_FACING_BACK;

Intent x;

//==============================================================================================
// Activity Methods
//==============================================================================================

/**
 * Initializes the UI and initiates the creation of a face detector.
 */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
    btnCapture = (ImageView) findViewById(R.id.btn_capture);
    btnChangeCamera = (ImageView) findViewById(R.id.btn_change_camera);
    btnCancel = (ImageView) findViewById(R.id.btn_cancel);
    btnSave = (ImageView) findViewById(R.id.btn_save);
    frmResult = (FrameLayout) findViewById(R.id.frm_capture_result);
    imgPicture = (ImageView) findViewById(R.id.img_capture_result);

    boolean hasPermissionCamera = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermissionCamera) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, RC_HANDLE_CAMERA_PERM);
    } else {
        boolean hasPermissionWriteStorage = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
        if (!hasPermissionWriteStorage) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM);
        } else {
            createCameraSource(cameraId);
        }
    }


    btnCapture.setOnClickListener(this);
    btnChangeCamera.setOnClickListener(this);
}


private void createCameraSource(int cameraId) {

    Context context = getApplicationContext();
    FaceDetector detector = new FaceDetector.Builder(context)
            .setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
            .build();

    detector.setProcessor(
            new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory())
                    .build());

    if (!detector.isOperational()) {

        Log.w(TAG, "Face detector dependencies are not yet available.");
    }

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    mCameraSource = new CameraSource.Builder(context, detector)
            .setRequestedPreviewSize(metrics.heightPixels, metrics.widthPixels)
            .setFacing(cameraId)
            .setAutoFocusEnabled(true)
            .setRequestedFps(30.0f)
            .build();
}


@Override
protected void onResume() {
    super.onResume();

    startCameraSource();
}


@Override
protected void onPause() {
    super.onPause();
    mPreview.stop();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mCameraSource != null) {
        mCameraSource.release();
    }
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case RC_HANDLE_CAMERA_PERM: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                finish();
                startActivity(getIntent());
            }
            break;
        }
        case RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                finish();
                startActivity(getIntent());
            }
            break;
        }
    }
}


private void startCameraSource() {

    // check that the device has play services available.
    int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
            getApplicationContext());
    if (code != ConnectionResult.SUCCESS) {
        Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
        dlg.show();
    }

    if (mCameraSource != null) {
        try {
            mPreview.start(mCameraSource, mGraphicOverlay);
        } catch (IOException e) {
            Log.e(TAG, "Unable to start camera source.", e);
            mCameraSource.release();
            mCameraSource = null;
        }
    }
}

@Override
public void onClick(View v) {
    int id = v.getId();

    if (id == R.id.btn_capture) {
        Toast.makeText(this, "capture", Toast.LENGTH_SHORT).show();
        mCameraSource.takePicture(null, new CameraSource.PictureCallback() {
            @Override
            public void onPictureTaken(final byte[] bytes) {
                int orientation = Exif.getOrientation(bytes);


                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);



                switch (orientation) {
                    case 90:
                        bmp = Utils.rotateImage(bmp, 90);
                        break;
                    case 180:
                        bmp = Utils.rotateImage(bmp, 180);
                        break;
                    case 270:
                        bmp = Utils.rotateImage(bmp, 270);
                        break;
                }

                if (cameraId == CameraSource.CAMERA_FACING_FRONT) {
                    bmp = Utils.flip(bmp, Constants.FLIP_HORIZONTAL);
                }

                if (bmp != null) {
                    frmResult.setVisibility(View.VISIBLE);
                    imgPicture.setImageBitmap(bmp);
                    btnCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            frmResult.setVisibility(View.GONE);
                        }
                    });
                    btnSave.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SavePhotoTask savePhotoTask = new SavePhotoTask();
                            savePhotoTask.execute(bytes);


                        }
                    });
                }
            }
        });
    } else if (id == R.id.btn_change_camera) {
        mCameraSource.release();
        mCameraSource = null;
        cameraId = cameraId == CameraSource.CAMERA_FACING_BACK ? CameraSource.CAMERA_FACING_FRONT : CameraSource.CAMERA_FACING_BACK;
        createCameraSource(cameraId);
        startCameraSource();
    }
}


private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
    @Override
    public Tracker<Face> create(Face face) {
        return new GraphicFaceTracker(mGraphicOverlay);
    }
}


private class GraphicFaceTracker extends Tracker<Face> {
    private GraphicOverlay mOverlay;
    private FaceGraphic mFaceGraphic;

    GraphicFaceTracker(GraphicOverlay overlay) {
        mOverlay = overlay;
        mFaceGraphic = new FaceGraphic(overlay);
    }


    @Override
    public void onNewItem(int faceId, Face item) {
        mFaceGraphic.setId(faceId);
    }


    @Override
    public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
        mOverlay.add(mFaceGraphic);
        mFaceGraphic.updateFace(face);
    }


    @Override
    public void onMissing(FaceDetector.Detections<Face> detectionResults) {
        mOverlay.remove(mFaceGraphic);
    }


    @Override
    public void onDone() {
        mOverlay.remove(mFaceGraphic);
    }
}

class SavePhotoTask extends AsyncTask<byte[], String, String> {
    @Override
    protected String doInBackground(byte[]... data) {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "TRACKER_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        try {
            File photo = File.createTempFile(imageFileName, ".jpg", storageDir);
            FileOutputStream fos = new FileOutputStream(photo.getPath());
            fos.write(data[0]);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}}

NEXT.java

public class NEXT extends AppCompatActivity {


ImageView y;
Intent intent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.next);

    y = (ImageView) findViewById(R.id.myimage);

    Bitmap bitmap = (Bitmap) intent.getParcelableExtra("key");
    y.setImageBitmap(bitmap);


}}

1 个答案:

答案 0 :(得分:0)

普京大数据(&gt; 1Mo)可以产生android.os.TransactionTooLargeException,参考:

  

Binder事务缓冲区当前具有有限的固定大小   1Mb ,由正在进行的所有正在进行的事务共享   处理。因此,当存在许多异常时,可以抛出此异常   即使在大多数个别交易中,交易仍在进行中   中等大小。

最好的方法是创建一个类并将图像放入其中,然后您可以从任何活动访问它