如何将图片的content:// URI转换为Base64字符串
Got it, converting a content:// URI to a Base64 string in Android is straightforward once you know the steps. Let's modify your existing code to make this work:
Convert content:// URI to Base64 String in Android
Step 1: Add a helper method to stream image data to bytes
First, create a utility function to read the image content from the URI into a byte array. You can add this to your activity or a dedicated helper class:
private byte[] getBytesFromInputStream(InputStream inputStream) throws IOException { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, bytesRead); } return byteBuffer.toByteArray(); }
Step 2: Update your onActivityResult logic
Modify your existing code to handle the URI, read the image data, and encode it to Base64:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 123 && resultCode == RESULT_OK) { Uri selectedFile = data.getData(); if (selectedFile != null) { Log.e("image", selectedFile.toString()); try { // Open input stream from the content URI InputStream inputStream = getContentResolver().openInputStream(selectedFile); // Convert stream to byte array byte[] imageBytes = getBytesFromInputStream(inputStream); // Encode byte array to Base64 string String base64Image = android.util.Base64.encodeToString(imageBytes, android.util.Base64.DEFAULT); // Log or use your Base64 string here Log.e("Base64 Image", base64Image); // Clean up: close the input stream if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); // Add user-facing error handling here (e.g., toast message) } } } }
Key Notes to Keep in Mind:
- Permissions: For Android 6.0+ (API 23+), you usually don't need
READ_EXTERNAL_STORAGEwhen picking images via the system gallery intent—your app gets temporary access to the file automatically. - Memory Usage: Large images can consume significant memory when converted to Base64. If you don't need full resolution, consider resizing the image first to reduce byte size.
- Base64 Flags: Use
Base64.NO_WRAPinstead ofDEFAULTif you want to avoid line breaks in the output (useful for JSON or API requests).
内容的提问来源于stack exchange,提问作者kalucki23
相关产品推荐
相关产品推荐

