我想單擊一張圖片並將其存儲在外部存儲目錄中。對於這一點,我用這:IllegalArgumentException將圖像存儲在外部目錄中時出錯
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>
我得到出現以下錯誤:
爲什麼我得到這個錯誤以及如何解決它?
我複製這從這裏 https://developer.android.com/training/camera/photobasics.html 此外,而不是「com.example.android.fileprovider」,我需要給我的包名? –
在manifest和FileProvider.getUriForFile()中給'com.example.android.fileprovider'改變爲'com.falcon.apps.fileprovider'。 – Gavin
這樣做。發生此錯誤 無法找到包含/storage/emulated/0/Pictures/JPEG_22112017_161142615705050.jpg的配置根 –