Как захватить и сохранить изображение с помощью пользовательской камеры в Android?

Как я могу захватить изображение в пользовательской камере, а затем сохранить это изображение в android?

см. ниже ответ.

Custom_CameraActivity.java

 public class Custom_CameraActivity extends Activity { private Camera mCamera; private CameraPreview mCameraPreview; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mCamera = getCameraInstance(); mCameraPreview = new CameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mCameraPreview); Button captureButton = (Button) findViewById(R.id.button_capture); captureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCamera.takePicture(null, null, mPicture); } }); } /** * Helper method to access the camera returns null if it cannot get the * camera or does not exist * * @return */ private Camera getCameraInstance() { Camera camera = null; try { camera = Camera.open(); } catch (Exception e) { // cannot get camera or does not exist } return camera; } PictureCallback mPicture = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = getOutputMediaFile(); if (pictureFile == null) { return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } } }; private static File getOutputMediaFile() { File mediaStorageDir = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("MyCameraApp", "failed to create directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") .format(new Date()); File mediaFile; mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); return mediaFile; } } 

CameraPreview.java

 public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mSurfaceHolder; private Camera mCamera; // Constructor that obtains context and camera @SuppressWarnings("deprecation") public CameraPreview(Context context, Camera camera) { super(context); this.mCamera = camera; this.mSurfaceHolder = this.getHolder(); this.mSurfaceHolder.addCallback(this); this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { try { mCamera.setPreviewDisplay(surfaceHolder); mCamera.startPreview(); } catch (IOException e) { // left blank for now } } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { mCamera.stopPreview(); mCamera.release(); } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) { // start preview with new settings try { mCamera.setPreviewDisplay(surfaceHolder); mCamera.startPreview(); } catch (Exception e) { // intentionally left blank for a test } } } 

main.xml

      

Добавить нижние строки в файл androidmanifest.xml

    

Следующий fragment поможет вам

               

main.xml

     

PhotoHandler.java

 package org.sample; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.os.Environment; import android.util.Log; import android.widget.Toast; public class PhotoHandler implements PictureCallback { private final Context context; public PhotoHandler(Context context) { this.context = context; } @Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFileDir = getDir(); if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) { Log.d(Constants.DEBUG_TAG, "Can't create directory to save image."); Toast.makeText(context, "Can't create directory to save image.", Toast.LENGTH_LONG).show(); return; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); String date = dateFormat.format(new Date()); String photoFile = "Picture_" + date + ".jpg"; String filename = pictureFileDir.getPath() + File.separator + photoFile; File pictureFile = new File(filename); try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); Toast.makeText(context, "New Image saved:" + photoFile, Toast.LENGTH_LONG).show(); } catch (Exception error) { Log.d(Constants.DEBUG_TAG, "File" + filename + "not saved: " + error.getMessage()); Toast.makeText(context, "Image could not be saved.", Toast.LENGTH_LONG).show(); } } private File getDir() { File sdDir = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); return new File(sdDir, "CameraAPIDemo"); } } 

MakePhotoActivity.java

 package org.sample; import android.app.Activity; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import de.vogella.cameara.api.R; public class MakePhotoActivity extends Activity { private final static String DEBUG_TAG = "MakePhotoActivity"; private Camera camera; private int cameraId = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // do we have a camera? if (!getPackageManager() .hasSystemFeature(PackageManager.FEATURE_CAMERA)) { Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG) .show(); } else { cameraId = findFrontFacingCamera(); camera = Camera.open(cameraId); if (cameraId < 0) { Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show(); } } } public void onClick(View view) { camera.takePicture(null, null, new PhotoHandler(getApplicationContext())); } private int findFrontFacingCamera() { int cameraId = -1; // Search for the front facing camera int numberOfCameras = Camera.getNumberOfCameras(); for (int i = 0; i < numberOfCameras; i++) { CameraInfo info = new CameraInfo(); Camera.getCameraInfo(i, info); if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { Log.d(DEBUG_TAG, "Camera found"); cameraId = i; break; } } return cameraId; } @Override protected void onPause() { if (camera != null) { camera.release(); camera = null; } super.onPause(); } } 

См. Эту документацию

http://sofru.miximages.com/android/camera, 40, bytes); String timeStamp = new SimpleDateFormat(“yyyyMMdd_HHmmss”).format(new Date()); String imageFileName = “JPEG_” + timeStamp + “_”; File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ “.jpg”, /* suffix */ storageDir /* directory */ ); FileOutputStream stream = new FileOutputStream(image); stream.write(bytes.toByteArray()); stream.close(); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = “file:” + image.getAbsolutePath(); fileUri = image.getAbsolutePath(); Picasso.with(getActivity()).load(image).into(showbookimage); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){ // get bundle Bundle extras = intent.getExtras(); // get bitMap = (Bitmap) extras.get(“data”); // showbookimage.setImageBitmap(bitMap); try { createImageFile(bitMap); } catch (IOException e) { e.printStackTrace(); } } }

использовать picasso для изображения, чтобы отображать довольно быстро

  • Как создать кнопку динамически в android?
  • получить в данный момент fragment
  • Обработка экрана без потери данных - Android
  • Кнопка Click Listeners в Android
  • Android Smudged layout
  • CollapsingToolbarLayout субтитры
  • Android: нарисуйте круг с текстом внутри
  • Как заставить WRAP_CONTENT работать с RecyclerView
  • Кнопка пользовательской формы Android
  • Как получить соответствующие изображения в соответствующем Android-устройстве в Android Studio
  • Линейная компоновка и вес в Android
  • Interesting Posts
    Давайте будем гением компьютера.