谁能告诉如何将捕获的图像传递给不同的活动以在 android 中设置图像视图并存储在数据库中?有人可以提供代码吗?
谢谢
尝试这个...
1.在onActivityResult()中捕获并获取捕获图像的位图
public void capture(View view) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAPTURE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
}
}
}
2 将图像发送到下一个活动...您可以发送位图,因为它实现了 Parcelable
private void sendImage() {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("image", thumbnail);
startActivity(intent);
}
3 在NextActivity中获取图片
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bitmap image = (Bitmap) extras.get("image");
if (image != null) {
imageView.setImageBitmap(image);
}
}
您需要按照以下步骤操作:-
如果您有任何问题,请告诉我。
要将位图保存在 sdcard 中,请使用以下代码
店铺形象
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
获取图像存储路径
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}