如何通过Uri设置ImageView?解析createImageFile()方法实现
Hey there! Let's break down two key things you're asking about: how to set an ImageView using a Uri and what that createImageFile() method you shared is doing.
一、实现从Uri设置ImageView的功能
Setting an ImageView from a Uri can be done with native Android APIs or a third-party library (way easier!). Let's cover both options, plus important notes for compatibility.
1. Native Android Implementation
This uses ContentResolver to fetch the image from the Uri and load it into the ImageView:
// Assume you've already obtained the target Uri (e.g., from gallery or camera) Uri imageUri = ...; ImageView imageView = findViewById(R.id.your_image_view_id); try { // Open an input stream from the Uri using ContentResolver InputStream inputStream = getContentResolver().openInputStream(imageUri); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); imageView.setImageBitmap(bitmap); // Don't forget to close the stream to avoid resource leaks if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); // Set a placeholder image if loading fails imageView.setImageResource(R.drawable.load_failed_placeholder); }
2. Simplified Implementation with Glide (Recommended)
Glide handles all the messy stuff: permission checks, caching, adapting to different Uri types, and error handling. It's the go-to for Android image loading:
Uri imageUri = ...; ImageView imageView = findViewById(R.id.your_image_view_id); Glide.with(this) .load(imageUri) .placeholder(R.drawable.loading_placeholder) // Show while loading .error(R.drawable.load_failed_placeholder) // Show if load fails .into(imageView);
Key Notes
- Permissions: On Android 9 and below, you need the
READ_EXTERNAL_STORAGEpermission to access images from external storage. Android 10+ uses Scoped Storage, so this permission isn't required for media files accessed via MediaStore. - FileProvider: For Android 7+, if you're using a
file://Uri (e.g., from a local file you created), you must useFileProviderto generate acontent://Uri instead—otherwise you'll get aFileUriExposedException.
二、解析createImageFile()方法
First, let's fix the incomplete code you shared (the last line was cut off). Here's the full, functional version:
private File createImageFile() { // Get the system's public Pictures directory File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // Generate a unique timestamp for the filename SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String timeStamp = sdf.format(new Date()); // Create a File object for the new image (doesn't create the actual file yet) File imageFile = new File(picturesDirectory, "picture" + timeStamp +".jpg"); // Save the file path to SharedPreferences for later access SharedPreferences fileLocation = getSharedPreferences("filePath", Context.MODE_PRIVATE); SharedPreferences.Editor editor = fileLocation.edit(); editor.putString("file", imageFile.getAbsolutePath()); editor.apply(); // Async save (use commit() only if you need immediate confirmation) return imageFile; }
Line-by-Line Breakdown
- Line 2: Fetches the system's public
Picturesfolder—this is a shared directory all apps can access (with proper permissions). - Lines 4-5: Creates a timestamp string formatted as
YYYYMMDD_HHMMSSto ensure each image filename is unique (no overwriting existing files). - Line 7: Creates a
Fileinstance pointing to the new image's location. Note: this doesn't create the actual file on disk yet—you'll need to callimageFile.createNewFile()or write data to it via an output stream. - Lines 9-12: Saves the absolute path of the image file to
SharedPreferences(a lightweight storage for app-specific data).MODE_PRIVATEensures only your app can read this data, andapply()saves changes asynchronously (better for main thread performance).
Important Caveats
- Scoped Storage Compatibility: On Android 10+,
Environment.getExternalStoragePublicDirectory()is deprecated. Instead, useMediaStoreto save images to public storage, or use your app's private directory (getExternalFilesDir(Environment.DIRECTORY_PICTURES)). - Permissions: On Android 9 and below, you need the
WRITE_EXTERNAL_STORAGEpermission to create files in the publicPicturesdirectory. - Error Handling: The code above doesn't handle exceptions that might occur when creating the file (e.g., insufficient storage). Add a
try-catchblock aroundimageFile.createNewFile()if you're generating the actual file.
内容的提问来源于stack exchange,提问作者lmthrn

