这是我用来保存设备上相机和图库中的图片的行代码:
相机意图:
private void abrirCamera() {
ContentValues values = new ContentValues();
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//Camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, CAMERA);
}
画廊意图:
public void abrirGaleria() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
这是用于在设备上保存文件夹的 onActivityResult:
@NonNull
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onResume();
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY) {//Verify the requestCode
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), contentURI);
int altura = bitmap.getHeight();//altura;
int largura = bitmap.getWidth();//largura
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
} else {
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
}
atualizarLista();
}
if (requestCode == CAMERA && data == null) {//Android 10 (Android Q > API 23)
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = Objects.requireNonNull(getActivity()).getContentResolver().query(image_uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String caminho = cursor.getString(column_index);//diretorio
cursor.close();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image_uri);
int altura = bitmap.getHeight();
int largura = bitmap.getWidth();
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
apagaFotoOriginal(caminho);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
atualizarLista();
}
if (requestCode == CAMERA && String.valueOf(data).equals("Intent { act=inline-data (has extras) }")) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(image_uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String caminho = cursor.getString(column_index);//diretorio
cursor.close();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image_uri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "Title", null);
int altura = bitmap.getHeight();//altura;
int largura = bitmap.getWidth();//largura
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
apagaFotoOriginal(caminho);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
atualizarLista();
}
if (requestCode == CAMERA && data == null) {//Android 10 (Android Q > API 23)
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = Objects.requireNonNull(getActivity()).getContentResolver().query(image_uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String caminho = cursor.getString(column_index);//diretorio
cursor.close();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image_uri);
int altura = bitmap.getHeight();
int largura = bitmap.getWidth();
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
apagaFotoOriginal(caminho);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
atualizarLista();
}
}
}
用于在设备上保存图片的方法,与您的 Android 版本一致:
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File diretorioAndroid8_9 = new File(Environment.getExternalStorageDirectory() + File.separator + IMAGE_DIRECTORY);
if (!diretorioAndroid8_9.exists()) {//cria o diretorio caso não existir
diretorioAndroid8_9.mkdirs();
}
try {
id = foto_ugbDao.proximoID(compet, codugb);
String teste = "";
if (id <= 9) {// ID <= 9
int a = id;
String b = String.format("%02d", a);
String fileName = compet + codugb + b;
if (verificaNomeArquivo(fileName)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {
salvarArquivoAPI23(bytes, diretorioAndroid8_9, b);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {
salvarArquivoAPI23(bytes, diretorioAndroid8_9, b);
}
}
} else {// id >= 10
String fileName = compet + codugb + id;
if (verificaNomeArquivo(fileName)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {//criação de arquivo com id maior que 10, em API de nivel inferior a 29 (Android Q)
salvarArquivoAPI23(bytes, diretorioAndroid8_9, fileName);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {
salvarArquivoAPI23(bytes, diretorioAndroid8_9, fileName);
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private void salvarArquivoAPI23(ByteArrayOutputStream bytes, File diretorioAndroid8_9, String b) throws IOException {
String ss = compet + codugb + id;
File f = new File(diretorioAndroid8_9, ss);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(context,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
}
private void salvarArquivoAPI29(Bitmap myBitmap, ByteArrayOutputStream bytes, String fileName) throws IOException {
OutputStream outputStream = null;
ContentResolver resolver = getActivity().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
String diretorioAndroid10 = Environment.DIRECTORY_PICTURES + IMAGE_DIRECTORY;
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, diretorioAndroid10);
Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
if (uri != null) {
outputStream = resolver.openOutputStream(uri);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
Log.println(Log.ERROR, "API29", String.valueOf(uri));
} else {
File f = new File(diretorioAndroid10, fileName + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(context,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
}
}
日志返回:
java.lang.RuntimeException:将结果 ResultInfo{who=null, request=65538, result=-1, data=null} 传递给活动 {br.agr.terraviva.modelogestao/br.agr.terraviva.modelogestao.ui.act005 失败.AuditoriaUGBActivity}: android.database.CursorIndexOutOfBoundsException: 请求索引 0,在 android.app.ActivityThread.deliverResults(ActivityThread.java:5080) 处的 android.app.ActivityThread.handleSendResult(ActivityThread.java:5121) 处的大小为 0 android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2183) 在 android.os.Handler.dispatchMessage(Handler.java:107) 在 android.os.Looper.loop(Looper.java:241) 在 android.app.ActivityThread.main(ActivityThread.java:7604) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android .internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941) 原因:android.database.CursorIndexOutOfBoundsException:请求索引 0,与大小为 0 在 android.database.AbstractCursor.checkPosition(AbstractCursor.java:515) 在 android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:138) 在 android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:52) 在android.database.CursorWrapper.getString(CursorWrapper.java:141) 在 br.agr.terraviva.modelogestao.ui.act005.FA04.onActivityResult(FA04.java:350) 在 androidx.fragment.app.FragmentActivity。onActivityResult(FragmentActivity.java:170) 在 android.app.Activity.dispatchActivityResult(Activity.java:8136) 在 android.app.ActivityThread.deliverResults(ActivityThread.java:5073) 在 android.app.ActivityThread.handleSendResult(ActivityThread.java :5121) 在 android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor. java:95) 在 android.os.Handler.dispatchMessage(Handler.java:107) 在 android.os.Looper.loop(Looper.java:241) 的 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2183) ) 在 com.android.internal.os 的 java.lang.reflect.Method.invoke(Native Method) 的 android.app.ActivityThread.main(ActivityThread.java:7604)。RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)