android eclipse的相机源代码

时间:2013-01-24 06:36:00

标签: android eclipse camera

我需要一些帮助。问题是我在名片读卡器上做了一个应用程序,需要使用相机功能拍照。但是如何使我的应用程序能够查看我已保存的多个图片而无需退出应用程序并转到图库?下面是我使用的相机源代码..谢谢

`

CameraMainActivity.Java

private static final int REQUEST_CODE = 1;
private static final int CAMERA_PIC_REQUEST = 1337;
private Bitmap bitmap;
private ImageView imageView;
private Button save, capture;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera_main);
    imageView = (ImageView) findViewById(R.id.result);
    save = (Button) findViewById(R.id.save);
    save.setOnClickListener(this);
    capture = (Button) findViewById(R.id.capture);
    capture.setOnClickListener(this);
}

public void captureImage() {
    // Capture image from camera

        Intent intent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(intent, CAMERA_PIC_REQUEST);

}

public void pickImage() {
    // To pick a image from file system
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_CODE) {
            try {
                // We need to recycle unused bitmaps
                if (bitmap != null) {
                    bitmap.recycle();
                }
                InputStream stream = getContentResolver().openInputStream(
                        data.getData());
                bitmap = BitmapFactory.decodeStream(stream);
                stream.close();
                imageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (requestCode == CAMERA_PIC_REQUEST) {

                if (bitmap != null) {
                    bitmap.recycle();
                }
                bitmap = (Bitmap) data.getExtras().get("data");
                if (data.getExtras().get("data") == null)
                Toast.makeText(getApplicationContext(),
                        "No image returned", Toast.LENGTH_LONG).show();
                else
                imageView.setImageBitmap(bitmap);



        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_camera_main, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if (v == save) {
        BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
        File sdCardDirectory = Environment.getExternalStorageDirectory();
        File image = new File(sdCardDirectory, "test.png");
        boolean success = false;

        // Encode the file as a PNG image.
        FileOutputStream outStream;
        try {

            outStream = new FileOutputStream(image);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            /* 100 to keep full quality of the image */

            outStream.flush();
            outStream.close();
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (success) {
            Toast.makeText(getApplicationContext(),
                    "Image saved with success", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Error during image saving", Toast.LENGTH_LONG).show();
        }
    } else if (v == capture) {
        captureImage();
    }

}

}

我正在使用按钮启动相机

main.xml中

    <Button
        android:id="@+id/takeviewpic"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take/View Pic" />

Android Manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature
    android:name="android.hardware.camera"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera.front"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera.autofocus"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera.flash"
    android:required="false" />
<uses-feature android:name="android.hardware.screen.landscape" />
<uses-feature
    android:name="android.hardware.wifi"
    android:required="false" />
<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />

<uses-sdk android:minSdkVersion="10" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <uses-library android:name="com.google.android.maps" />
    <activity
        android:name="sp.com.Splash"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Main"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="main" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity android:name=".NameCardList" >
    </activity>
    <activity android:name=".DetailForm" >
    </activity>
    <activity android:name=".EditPreferences" >
    </activity>
    <activity android:name=".NameCardMap" >
    </activity>
    <activity android:name=".SmsReceiver" >
    </activity>
    <activity
        android:name=".CameraMainActivity"
        android:label="@string/app_name" 
        android:clearTaskOnLaunch="true"
        android:configChanges="orientation|keyboardHidden"
        android:stateNotNeeded="true"
    />
</application>

`

2 个答案:

答案 0 :(得分:2)

我的相机示例可以帮助您: -

import android.hardware.Camera;

import android.hardware.Camera.CameraInfo;

import android.os.Bundle;

import android.app.Activity;

import android.content.pm.PackageManager;

import android.util.Log;

import android.view.Menu;

import android.view.View;

import android.widget.Toast;


public class Main 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);


 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();

}



}

另一类照片处理程序.. !!!: -

 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.provider.SyncStateContract.Constants;
 import android.util.Log;
 import android.widget.Toast;

  public class PhotoHandler implements PictureCallback {
private final Context context;

  public PhotoHandler(Context context) {
    this.context = context;
  }

  public void onPictureTaken(byte[] data, Camera camera) {

    File pictureFileDir = getDir();

    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

      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) {

      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");
  }

 }

如果你想要别的东西,请添加评论...... !!!!!

答案 1 :(得分:0)

使用ImageView(或ImageViews)设置活动,并将其上的源设置为您创建的文件。