我尝试从内部存储中选择一个图像,然后使用imageview加载该图像。它选择图像但不显示。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
<ImageView
android:id="@+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
/>
</RelativeLayout>
这是我的布局
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private static final int SELECT_PICTURE = 100;
private static final String TAG = "MainActivity";
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imgView);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openImageChooser();
}
});
}
/* Choose an image from Gallery */
void openImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
imageView.setImageURI(null);
imageView.setImageURI(selectedImageUri);
}
}
}
}
}
在此代码中,选择图像后,它不再显示。 我的权限是
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
我发现显示mipmap可以使imageview正常工作
imageView.setImageResource(R.mipmap.ic_launcher)
这将显示图像文件的位置(工作中)
String s = selectedImageUri.toString();
Toast.makeText(this,s,Toast.LENGTH_LONG).show();
答案 0 :(得分:1)
您快到了!
您缺少的是从路径正确设置ImageView
中的图像资源的方法。尝试以下解决方案:Show Image View from file path?
使用以下代码从SD卡中存储的文件中设置位图图像。
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}