我已经跟踪了 this 中的所有内容。 Android 官方网站。
我已将 createTempFile()
的路径存储在代码中的 currentImagePath
中。显示路径的打印。但是,该路径上似乎没有数据。
我的逻辑是将数据从该路径复制到永久路径。
btnTakePic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
captureImage(v);
/*try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}*/
//System.out.println(currentImagePath);
File from = new File(currentImagePath);
File storageFileDir = getFilesDir();
byte[] bArray = new byte[(int) from.length()];
try{
fi = new FileInputStream(from);
fi.read(bArray);
fi.close();
}catch(IOException ioExp){
ioExp.printStackTrace();
}
File picStorageDir = new File(storageFileDir,"myPics");
perStorageDir = picStorageDir;
if(!picStorageDir.isDirectory())
{
picStorageDir.mkdirs();
}
System.out.println(perStorageDir.getAbsolutePath());
System.out.println("From length: "+from.length());
try {
String[] t = currentImagePath.split("/"); // this is just to get image name
File temp = new File(picStorageDir,t[t.length-1]); // this is to set file with image name
ff = new FileOutputStream(temp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
ff.write(bArray);
} catch (IOException e) {
e.printStackTrace();
}
});
下面是captureImage()
方法
public void captureImage(View view)
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!=null)
{
File imageFile = null;
try {
imageFile = getImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if(imageFile!=null)
{
Uri imageUri = FileProvider.getUriForFile(this, "com.example.android.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, IMAGE_REQUEST);
}
System.out.println("imageFile length:"+imageFile.length());
}
}
这是日志输出
2020-04-30 14:19:32.646 31226-31226/com.example.ccalculator I/System.out: currImPath: /storage/emulated/0/Android/data/com.example.ccalculator/files/Pictures/jpg_20200430_1419032_793088582.jpg
2020-04-30 14:19:32.657 31226-31226/com.example.ccalculator I/System.out: imageFile length:0
2020-04-30 14:19:32.657 31226-31226/com.example.ccalculator I/System.out: /storage/emulated/0/Android/data/com.example.ccalculator/files/Pictures/jpg_20200430_1419032_793088582.jpg
2020-04-30 14:19:32.658 31226-31226/com.example.ccalculator I/System.out: permanent storage dir: /data/user/0/com.example.ccalculator/files/myPics
2020-04-30 14:19:32.658 31226-31226/com.example.ccalculator I/System.out: From length: 0
此时,我尚未从应用程序捕获图像。所以我想也许一旦我捕获图像,数据就会存储在各自的路径中。我尝试添加 Thread.sleep(1000);
但即使这样也没有帮助。
最佳答案
捕获返回回调,即 startActivityForResult
不会暂停线程,因此添加类似...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK) {
在回调中放置处理新图像的代码。
关于java - 无论我做什么,我都无法保存相机捕获的图像。我该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61519491/