所以,我正在做一个大学项目,我允许用户从相机/图库中选择一个图像,然后选择一个mp3。我想将这两个选定的文件保存到具有相同名称的内部存储目录中(只有扩展名.mp3/.jpg会有所不同(
我已经设法获取了创建文件夹的代码以及从相机/图库中获取图像,但我似乎无法弄清楚如何将其保存到内部存储目录或如何以相同的方式获取 mp3。
创建文件夹的代码
try{ File folder = new File(Environment.getExternalStorageDirectory() + "/InkousticMedia");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
}catch (Exception e){
Log.e("MODEL", "ERROR: " + e.toString());
}
从媒体存储获取图像的代码:
public class SaveTattooActivity extends AppCompatActivity {
public void getPhoto()
{
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1)
{
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getPhoto();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_tattoo);
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}else
{
getPhoto();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && requestCode == RESULT_OK && data != null)
{
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我已经查看了堆栈上的其他类似问题,但它们都有很大差异,并且似乎没有具体的答案,我可以将mp3和图像都保存到目录中。
这是我用来保存图像的代码,请检查此 github 存储库 https://github.com/Rawkush/Status-Saver。
File f1,f2;
f1 = new File(uri.toString());
String fname = f1.getName();
f2 = new File(Environment.getExternalStorageDirectory()+"/YOUR_FOLDER/");
f2.mkdirs();
try {
FileUtils.copyFileToDirectory(f1,f2);
ContentValues values =new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN,System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg");
values.put(MediaStore.MediaColumns.DATA,f2.toString()+"/"+fname);
getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}finally {
Toast.makeText(getContext(),"Saved",Toast.LENGTH_LONG).show();
}