gpt4 book ai didi

android - 如何使用原生 Android 相机捕获图像并将其存储

转载 作者:IT老高 更新时间:2023-10-28 21:37:35 25 4
gpt4 key购买 nike

我在捕获图像并将其从 native 相机应用程序存储时遇到问题。这是我的一些代码示例。

_path = Environment.getExternalStorageDirectory() + "make_machine_example.jpg";
File file = new File( _path );
Uri outputFileUri = Uri.fromFile( file );

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

startActivityForResult( intent, 0 );

拍摄完照片并返回到原始 Activity 后,当我通过 Android DDMS 文件资源管理器导航到我的 sd 卡时,图片不存在。有人知道为什么没有保存吗?

最佳答案

这是最终产品,以防有人仍在访问此线程:

public class CameraCapture extends Activity {

protected boolean _taken = true;
File sdImageMainDirectory;

protected static final String PHOTO_TAKEN = "photo_taken";

@Override
public void onCreate(Bundle savedInstanceState) {

try {

super.onCreate(savedInstanceState);
File root = new File(Environment
.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root, "myPicName");


startCameraActivity();
}
} catch (Exception e) {
finish();
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}

}

protected void startCameraActivity() {

Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case 0:
finish();
break;

case -1:

try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
} catch (Exception e) {
e.printStackTrace();
}

finish();
startActivity(new Intent(CameraCapture.this, Home.class));

}

}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(CameraCapture.PHOTO_TAKEN)) {
_taken = true;
}
}

@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(CameraCapture.PHOTO_TAKEN, _taken);
}

public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}

}

关于android - 如何使用原生 Android 相机捕获图像并将其存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3442462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com