gpt4 book ai didi

android - 将通过 Intent.ACTION_PICK 选取的图像复制到文件

转载 作者:行者123 更新时间:2023-11-29 17:42:42 25 4
gpt4 key购买 nike

我的代码允许用户通过单击按钮使用 Intent.ACTION_PICK 选择图像:

public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}

如何将所选图像复制到已创建的文件中?

最佳答案

您将需要实现 onActivityResult,当您的 Activity 从用户从他们的图库中选择照片后恢复时调用。

Intent 数据将是一个Uri,您需要提取磁盘上图像的绝对路径。

像这样:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_PHOTO && resultCode == Activity.RESULT_OK) {
File file = getBitmapFile(data);
if(file != null) {
// do something with the file
}
}
}


public File getBitmapFile(Intent data) {
Uri selectedImage = data.getData();
Cursor cursor = getContentResolver().query(selectedImage, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();

int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String selectedImagePath = cursor.getString(idx);
cursor.close();

return new File(selectedImagePath);
}

如果您的用户在手机上启用了 Picassa(或任何其他基于云的照片服务),则操作系统可能会允许他们从该来源选择图像。问题是这样做的结果不符合 getBitmapFile 中的逻辑——也就是说,它与选择本地文件不同。要解决此问题,您可以确保您的 Picker Intent 仅允许本地文件:

photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);

要将 Bitmap 存储到另一个文件,您将需要更多方法:

private boolean writeBitmapToFile(Bitmap bitmap, File destination) {
FileOutputStream out = null;
try {
out = new FileOutputStream(destination);
return bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception ex) {
Log.i(TAG, String.format("Error writing bitmap to %s: %s", destination.getAbsoluteFile(), ex.getMessage()));
return false;
} finally {
try {
if (out != null) {
out.close();
}
}catch (IOException ex) {}
}
}

private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
return image;
}

要使用这些方法:

writeBitmapToFile(位图, createImageFile());

关于android - 将通过 Intent.ACTION_PICK 选取的图像复制到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28002907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com