2015-08-07 1 views
1

Открыл камеру, используя вид сверху.Сделайте снимок экрана с захваченного изображения в обзоре поверхности

Imageview in MainActivity. , когда я нажимаю на изображение. Камера открыта, и я нажимаю текстовое изображение (Capture) в виде изображения, сохраненного в памяти, и устанавливается в изображение.

Между этими двумя действиями я получаю подтверждение от пользователя, является ли захваченное изображение одобренным или нет (Ok или cancel).

Если пользователь нажимает ok, то снятое изображение устанавливается в изображение. Если пользователь нажал кнопку отмены, камера снова откроется.

Это подтверждает экран появляется с захвачены изображениями и две кнопкой (КИ и отмена)

Моего кода, чтобы открыть камеру в виде поверхности

package com.example.androidsurfaceviewexample; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.NoSuchElementException; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.hardware.Camera; 
import android.hardware.Camera.PictureCallback; 
import android.hardware.Camera.ShutterCallback; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 
import android.view.View; 
import android.widget.TextView; 
import android.widget.Toast; 
public class CameraActivity extends Activity implements SurfaceHolder.Callback { 
    TextView testView; 
    Camera camera; 
    SurfaceView surfaceView; 
    SurfaceHolder surfaceHolder; 
    PictureCallback rawCallback; 
    ShutterCallback shutterCallback; 
    PictureCallback jpegCallback; 
    public static boolean front = false; 
    Intent intent = null; 
    /** Called when the activity is first created. */ 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 
     intent = getIntent(); 
     Bundle extras = intent.getExtras(); 
     front = extras.getBoolean("front"); 
     surfaceView = (SurfaceView) findViewById(R.id.surfaceView); 
     surfaceHolder = surfaceView.getHolder(); 
     // Install a SurfaceHolder.Callback so we get notified when the 
     // underlying surface is created and destroyed. 
     surfaceHolder.addCallback(this); 
     // deprecated setting, but required on Android versions prior to 3.0 
     surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
     jpegCallback = new PictureCallback() { 
      public void onPictureTaken(byte[] data, Camera camera) { 
       FileOutputStream outStream = null; 
       try { 
        String filePath=String.format("/sdcard/%d.jpg", System.currentTimeMillis()); 
        outStream = new FileOutputStream(filePath); 
        outStream.write(data); 
        outStream.close(); 
        FirstActivity.photo = true; 
        intent = new Intent(getBaseContext(), MainActivity.class); 
        Bundle extras = new Bundle(); 
        //extras.putByteArray("path", data); 
        extras.putString("path", filePath); 
        extras.putString("front", "" + front); 
        intent.putExtras(extras); 
        startActivity(intent); 
        Log.d("Log", "onPictureTaken - wrote bytes: " + data.length); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } finally { 
       } 
       Toast.makeText(getApplicationContext(), "Picture Saved", 2000) 
         .show(); 
       refreshCamera(); 
      } 
     }; 
    } 
    public void captureImage(View v) throws IOException { 
     // take the picture 
     camera.takePicture(null, null, jpegCallback); 
    } 

    public void refreshCamera() { 
     if (surfaceHolder.getSurface() == null) { 
      // preview surface does not exist 
      return; 
     } 
     // stop preview before making changes 
     try { 
      camera.stopPreview(); 
     } catch (Exception e) { 
      // ignore: tried to stop a non-existent preview 
     } 
     // set preview size and make any resize, rotate or 
     // reformatting changes here 
     // start preview with new settings 
     if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { 
      camera.setDisplayOrientation(90); 
     } else { 
      camera.setDisplayOrientation(0); 
     } 
     try { 
      camera.setPreviewDisplay(surfaceHolder); 
      camera.startPreview(); 
     } catch (Exception e) { 
     } 
    } 
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
     // Now that the size is known, set up the camera parameters and begin 
     // the preview. 
     refreshCamera(); 
    } 

    public void surfaceCreated(SurfaceHolder holder) { 
     try { 
     // open the camera 
      System.out.println("camera id"+""+getCamera()); 
      if(front) 
      { 
       int frontExist=getCamera(); 
       if(frontExist==1) 
       camera = getFrontFacingCamera(); 
       else 
        camera = Camera.open(); 
      } 
      else 
      camera = Camera.open(); 
     } catch (RuntimeException e) { 
      // check for exceptions 
      System.err.println(e); 
      return; 
     } 
     // Camera.Parameters param; 
     // param = camera.getParameters(); 
     // modify parameter 
     // param.setPreviewSize(352, 288); 
     // camera.setParameters(param); 

     try { 
      // The Surface has been created, now tell the camera where to draw 
      // the preview. 
      camera.setPreviewDisplay(surfaceHolder); 
      camera.startPreview(); 
     } catch (Exception e) { 
      // check for exceptions 
      System.err.println(e); 
      return; 

     } 

    } 

    public void surfaceDestroyed(SurfaceHolder holder) { 
     // stop preview and release camera 
     camera.stopPreview(); 
     camera.release(); 
     camera = null; 
    } 

    Camera getFrontFacingCamera() throws NoSuchElementException { 
     Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); 
     for (int cameraIndex = 0; cameraIndex < Camera.getNumberOfCameras(); cameraIndex++) { 
      Camera.getCameraInfo(cameraIndex, cameraInfo); 
      if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 
       try { 
        return Camera.open(cameraIndex); 
       } catch (RuntimeException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     throw new NoSuchElementException("Can't find front camera."); 
    } 

    int getCamera() 
    { 
     int f=0; 
     Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); 
     for (int cameraIndex = 0; cameraIndex < Camera.getNumberOfCameras(); cameraIndex++) { 
      Camera.getCameraInfo(cameraIndex, cameraInfo); 
      if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 
       try { 
        f=1; 
        break; 
       } catch (RuntimeException e) { 
        e.printStackTrace(); 
       } 
      } 
      else 
       f=0; 
     } 
     return f; 
    } 

} 

SurfaceView Layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context="com.example.androidsurfaceviewexample.CameraActivity" > 


    <SurfaceView 
     android:id="@+id/surfaceView" 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="0.66" /> 

    <LinearLayout 
     android:id="@+id/capture" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:clickable="true" 
     android:gravity="center" 
     android:onClick="captureImage" 
     android:orientation="horizontal" > 
     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:padding="10dp" 
      android:text="Capture" 
      android:textAppearance="?android:attr/textAppearanceLarge" /> 
    </LinearLayout> 

</LinearLayout> 

Как могу я взять весь вид захваченного изображения с поверхности?

Пожалуйста, помогите решить эту проблему ...

+0

вы хотите только захватить видимое изображение с поверхностиView? –

+0

@HugoGresse благодарит за ваш ответ. Я хочу просмотр при нажатии на захват. Это снято изображение ... – Asha

ответ

0

Если вы только wan't иметь точное изображение отображаемых SurfaceView пикселей, вы можете использовать следующий метод:

/** 
* Take a screenshot of the view 
* @param view the view to capture 
* @return the bitmap representing the pixels of the given view 
*/ 
@Nullable 
public static Bitmap loadBitmapFromView(View view) { 
    try { 
     view.setDrawingCacheEnabled(true); 
     Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); 
     view.setDrawingCacheEnabled(false); 
     return bitmap; 
    } catch (OutOfMemoryError error){ 
     TeadsLog.d(LOG_TAG, "Out of Memory while loadBitmapFromView"); 
     return null; 
    } 
} 
+0

Как вызвать этот метод .... – Asha

+0

Когда вы не хотите делать захват, назовите его как 'ViewUtils.loadBitmapFromView (surfaceView);'. Предполагая, что вы поместите этот метод в имя класса utils 'ViewUtils' –

Смежные вопросы