Android Studio获取ImageView文件路径/URI上传AWS S3报错解决方案问询
问题根源
你当前的错误核心是陷入了一个开发误区:ImageView控件本身不会存储它所展示的图片的原始文件路径/URI,你拼接的Uri用了ImageView的控件idR.id.ivProfilePicture,这个id是控件的布局标识,和图片资源/存储路径完全无关,所以会触发资源不存在的报错。
你不需要强行找图片路径,既然Amplify支持直接上传输入流,直接从ImageView拿到展示的Bitmap转成输入流上传即可。
解决方案代码
普通位图场景(ImageView展示的是JPG/PNG等常规图片)
private void uploadInputStream() { // 获取ImageView实例 ImageView ivProfilePicture = findViewById(R.id.ivProfilePicture); // 从ImageView取到展示的Bitmap Bitmap bitmap = ((BitmapDrawable) ivProfilePicture.getDrawable()).getBitmap(); // 将Bitmap转成输入流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 可根据需求更换压缩格式为PNG,第二个参数为压缩质量,100为最高质量 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); InputStream exampleInputStream = new ByteArrayInputStream(baos.toByteArray()); // 调用Amplify上传 Amplify.Storage.uploadInputStream( "ExampleKey", exampleInputStream, result -> Log.i("MyAmplifyApp", "Successfully uploaded: " + result.getKey()), storageFailure -> Log.e("MyAmplifyApp", "Upload failed", storageFailure) ); }
矢量图兼容场景(ImageView展示的是VectorDrawable矢量图)
如果展示的是矢量图,不能直接强转BitmapDrawable,需要先将矢量图画到Bitmap中再处理:
private void uploadInputStream() { ImageView ivProfilePicture = findViewById(R.id.ivProfilePicture); Drawable drawable = ivProfilePicture.getDrawable(); // 将VectorDrawable转成Bitmap Bitmap bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888 ); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); // 后续转输入流、上传逻辑和上面一致 ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); InputStream exampleInputStream = new ByteArrayInputStream(baos.toByteArray()); Amplify.Storage.uploadInputStream( "ExampleKey", exampleInputStream, result -> Log.i("MyAmplifyApp", "Successfully uploaded: " + result.getKey()), storageFailure -> Log.e("MyAmplifyApp", "Upload failed", storageFailure) ); }
优化建议
如果这张图是用户从相册选择/相机拍摄得到的,建议你在给ImageView设置图片的时候,就把原始的图片Uri存到全局变量里,后续上传的时候直接用这个Uri拿输入流,不需要转Bitmap,性能更好且能保留图片原始质量。
内容的提问来源于stack exchange,提问作者aaa
相关产品推荐
相关产品推荐

