我想点击图片并将其存储在外部存储目录中。为此,我正在使用它:
public class MainActivity extends AppCompatActivity {
Button btn_pic;
ImageView iv_pic;
Context ctx = this;
Bitmap photo, bm;
String photoPath, img_dp;
private static final int CAMERA_REQUEST = 1888;
private int STORAGE_PERMISSION_CODE = 23;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_pic = (Button)findViewById(R.id.btn_pic);
iv_pic = (ImageView)findViewById(R.id.iv_pic);
btn_pic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
if(intent.resolveActivity(getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
}
catch (Exception e){
e.printStackTrace();
}
if(photoFile != null){
Uri photoUri = FileProvider.getUriForFile(ctx, "com.example.android.fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
bm = BitmapFactory.decodeFile(photoPath);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] b = byteArrayOutputStream.toByteArray();
img_dp = Base64.encodeToString(b, Base64.DEFAULT);
Log.i("image convert", img_dp);
iv_pic.setImageBitmap(photo);
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("ddmmyyyy_HHmmss").format(new Date());
String imgFileName = "JPEG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File img = File.createTempFile(imgFileName, ".jpg", storageDir);
photoPath = img.getAbsolutePath();
return img;
}
}
我的paths.xml文件是:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.falcon.apps.imagestoragedemo/files/Pictures" />
</paths>
我在AndroidManifest.xml文件中声明了一个提供程序
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/paths"></meta-data>
</provider>
我收到以下错误:
为什么我会收到此错误以及如何解决?
答案 0 :(得分:0)
除了这一行,您的代码似乎还可以:
Uri photoUri = FileProvider.getUriForFile(ctx, "com.example.android.fileprovider", photoFile);
不确定为什么你有com.example.android.fileprovider
或者你刚从某个在线来源复制了。
检查Android Documentation for Saving Files。它具有您需要的确切代码。
修改:链接
Edit2 :如果IllegalArgumentException无法解决问题,请检查您的清单。