public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Here, the counter will be incremented each time, and the
// picture taken by camera will be stored as 1.jpg,2.jpg
// and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
}
catch (IOException e)
{
}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
6. You need to override the method onActivityResult of the activity or fragment like this:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
magicalTakePhoto.resultPhoto(requestCode, resultCode, data);
// example to get photo
// imageView.setImageBitmap(magicalTakePhoto.getMyPhoto());
}
7 回答
请看下面的演示代码 .
这是用于UI的XML文件,
这是你的Java类文件,
Note:
在清单文件中指定以下权限,
拍照有两种方法:
1 - 使用Intent制作照片
2 - 使用相机API
我认为你应该使用第二种方式,其中两种方式有sample code here .
You can use Magical Take Photo library.
1. try with compile in gradle
2. You need this permission in your manifest.xml
3. instance the class like this
//“this”是当前的活动参数
4. if you need to take picture use the method
5. if you need to select picture in device, try with the method:
6. You need to override the method onActivityResult of the activity or fragment like this:
注意:只有使用此库,您才能在设备中选择图片,这使用最小的API 15 .
对于那些来到这里寻找使用Android的Camera和Camera2 API以编程方式拍摄照片/照片的方法,请查看Google自己提供的开源示例here .
将图像存储在所需的文件夹中
拍照功能
广播新图像否则 pic will not be visible in image gallery
权限
以下是打开相机的简单方法:
并设置
CAMERA_PIC_REQUEST= 1 or 0