Comment puis-je enregistrer l'image de la Caméra?
Voici mon code:
package com.commonsware.android.skeleton;
import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.*;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
//----------------------------------------------------------------------
public class SimpleBulbActivity extends Activity {
private Preview mPreview;
private static final String TAG = "CameraDemo";
FrameLayout preview;
Camera mCamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
}
protected void onResume() {
super.onResume();
//Setup the FrameLayout with the Camera Preview Screen
mPreview = new Preview(this);
preview = (FrameLayout)findViewById(R.id.preview);
preview.addView(mPreview);
}
public void snap() {
mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] _data, Camera _camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera _camera) {
FileOutputStream outStream = null;
try {
//write to local sandbox file system
//outStream =
//CameraDemo.this.openFileOutput(String.format("%d.jpg",
//System.currentTimeMillis()), 0);
//Or write to sdcard
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
//----------------------------------------------------------------------
class Preview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Preview(Context context) {
super(context);
//Install a SurfaceHolder.Callback so we get notified when the
//underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
//The Surface has been created, acquire the camera and tell it where
//to draw.
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(Environment.getExternalStorageDirectory().toString());
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: "
+ data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
mCamera.release();
mCamera = null;
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
//Surface will be destroyed when we return, so stop the preview.
//Because the CameraDevice object is not a shared resource, it's very
//important to release it when the activity is paused.
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.05;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
//Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
//Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
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.
Camera.Parameters parameters = mCamera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, w, h);
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if(display.getRotation() == Surface.ROTATION_0)
{
parameters.setPreviewSize(optimalSize.height, optimalSize.width);
mCamera.setDisplayOrientation(90);
}
if(display.getRotation() == Surface.ROTATION_90)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
}
if(display.getRotation() == Surface.ROTATION_180)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
}
if(display.getRotation() == Surface.ROTATION_270)
{
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
mCamera.setDisplayOrientation(0);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
}
Bon j'ai modifié mon code un peu.
J'ai ceci dans ma page principale:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/layout">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Camera Demo"
android:textSize="24sp" />
<FrameLayout android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout android:id="@+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>
<ImageView android:src="@drawable/litbulb"
android:layout_width="match_parent"
android:layout_height="112dip" />
</FrameLayout>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/buttonClick"
android:text="Snap!" android:layout_gravity="center"></Button>
</LinearLayout>
Lorsque je clique sur le "Snap!" ou buttonClick
bouton, il est censé capturer et enregistrer l'image, mais il ne l'est pas. Quelqu'un peut-il m'aider à modifier ce code afin de ne?
Aussi, il se plante à chaque fois que je quitte l'application. Voici la logcat de données:
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): FATAL EXCEPTION: main
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): java.lang.RuntimeException: Method called after release()
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at android.hardware.Camera.setHasPreviewCallback(Native Method)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at android.hardware.Camera.access$600(Camera.java:114)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at android.hardware.Camera$EventHandler.handleMessage(Camera.java:519)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at android.os.Handler.dispatchMessage(Handler.java:99)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at android.os.Looper.loop(Looper.java:123)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at java.lang.reflect.Method.invoke(Method.java:521)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
12-21 13:30:47.820: ERROR/AndroidRuntime(3906): at dalvik.system.NativeStart.main(Native Method)
vous pouvez essayer ce stackoverflow.com/questions/649057/...
OriginalL'auteur Willem Ellis | 2011-12-21
Vous devez vous connecter pour publier un commentaire.
D'accord, je pense que j'ai de la façon qui vous sont sens, et l'accident s'est arrêté, mais il n'est pas encore l'enregistrement de l'image.
Toutes mes excuses, l'incident est toujours en cours.
OriginalL'auteur Reddy
Juste en regardant ton code,
Vous avez besoin pour passer vos rappels dans la méthode takePicture
mPreview.getCamera().takePicture(shutterCallback, rawCallback, null, jpegCallback);
Jetez un oeil ici pour plus de détails.
Votre trace de la pile semble suggérer qu'il ne sait pas quoi faire une fois qu'il a pris la photo.
Aussi je soupçonne que vous pourriez être en pointant du doigt le mauvais répertoire racine pour l'écriture...
essayez ceci:
De l'environnement.getExternalStorageDirectory().toString()
The method getCamera() is undefined for the type SimpleBulbActivity.Preview
Où suis-je l'insertion de ce deuxième ligne?Ok j'ai modifié le code de la façon dont je pense que vous étiez sens. La panne ne se produit plus, mais l'image n'est toujours pas sauver.
Toutes mes excuses, l'incident est toujours en cours.
J'ai compris pourquoi il n'était pas de prendre la photo. J'ai maintenant de prendre la photo, mais quand je quitte l'application, je ne vois pas la photo dans ma galerie. Toutes les pensées?
Il ne le fait pas automatiquement, allez à votre galerie. Google ajouter des photos à votre galerie pour en faire une réalité.
OriginalL'auteur Genia S.
Ici, il est:
Souviens-toi aussi de faire quelque chose comme:
si l'image a été correctement enregistré. De cette façon, la prochaine fois que l'utilisateur ouvre la galerie ou tout autre support brwsing application, vous venez de prendre de l'image seront inscrites correctement.
OriginalL'auteur type-a1pha