前因:很久没去自己处理图片的上传的问题了,毕竟有很多成熟的框架都做了适配,不太需要自己处理,但是最近用三方的人脸识别的时候,对方就只返回了Bitmap,而公司后台又需要我上传File,后面存储需要自己去处理。
Android 10之前 我是处理如下:
try {
String fileName = new Date().getTime() + ".jpg";
String path = Environment.getExternalStorageDirectory() + "/cads/";
File dirFile = new File(path);
if (!dirFile.exists()) {
dirFile.mkdir();
}
File myCaptureFile = new File(path + fileName);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
livenessBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
uploadImage(myCaptureFile, fileName, "self", livenessBitmap);
} catch (IOException e) {
e.printStackTrace();
uploadImg.setImageDrawable(getResources().getDrawable(R.drawable.icon_img_failed));
}
但是到了Android 10 文件存储有了变化,这样处理就会有问题了,查了一下换成以下处理,特此记录一下!
try {
long time = new Date().getTime();
String fileName = time + ".jpg";
File externalFilesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File tempFile = File.createTempFile(String.valueOf(time), ".jpg", externalFilesDir);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
uploadImage(tempFile, fileName, "self", bitmap);
} catch (IOException e) {
e.printStackTrace();
selfiesImg.setImageDrawable(getResources().getDrawable(R.drawable.icon_img_failed));
}