android 如何使用返回URI保存图像?

dtcbnfnu  于 2023-03-11  发布在  Android
关注(0)|答案(2)|浏览(230)

我正在使用GitHub的图像背景移除库。我的图像在移除背景后没有保存在存储中。

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CutOut.CUTOUT_ACTIVITY_REQUEST_CODE) {
        switch (resultCode) {
            case Activity.RESULT_OK:
                Uri imageUri = CutOut.getUri(data);
                // Save the image using the returned Uri here
                //what code to add here so i can save my image
                how to save image using Retun Uri
                Intent intent1=new Intent(BackgroundRemover.this,MainActivity.class);
                startActivity(intent1);
                break;
            case CutOut.CUTOUT_ACTIVITY_RESULT_ERROR_CODE:
                Exception ex = CutOut.getError(data);
                break;
            default:
                System.out.print("User cancelled the CutOut screen");
                Intent intent2=new Intent(BackgroundRemover.this,AdvanceFeatures.class);
                startActivity(intent2);
        }
    }
}

如何使用返回URI保存图像?

wz1wpwve

wz1wpwve1#

通过URI保存图像的一种实用方法是编写以下代码:
1 -使用CutOut.getUri(data)获取图像的URI。
2-MediaStore.Images.Media.getBitmap以获取位图对象
3-getContentResolver().openOutputStream(imageUri)以获取OutputStream对象,从而将图像数据写入URI。
4 -bitmap.compress压缩图像数据并将其写入OutputStream。
5例Activity.RESULT_OK:(您的块)onActivityResult方法。

Uri imageUri = CutOut.getUri(data);
try {
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    String displayName = "my_image.png"; // Set the name of the image file here
    OutputStream fos = getContentResolver().openOutputStream(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/" + displayName));
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}
z8dt9xmd

z8dt9xmd2#

您必须从URI获取字节数组,并使用输出和输入流将字节数组转换为文件。
从URI获取字节数组

result?.data?.data?.let {
                val byteArray = contentResolver.openInputStream(it)?.readBytes() }

从URI获取文件信息

/*
 * Get the file's content URI from the incoming Intent,
 * then query the server app to get the file's display name
 * and size.
 */
returnIntent.data?.let { returnUri ->
    contentResolver.query(returnUri, null, null, null, null)
}?.use { cursor ->
    /*
     * Get the column indexes of the data in the Cursor,
     * move to the first row in the Cursor, get the data,
     * and display it.
     */
    val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
    cursor.moveToFirst()
    val fileName = cursor.getString(nameIndex)
    val fileSize = cursor.getLong(sizeIndex).toString()
}

从字节数组写入文件

if (!file.exists()) {
    file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(byteArray);
fos.close();

相关问题