ImageView不显示位图

时间:2018-07-24 20:48:24

标签: java android bitmap android-imageview

我正在尝试使用Bitmap显示ImageView,并且Bitmap从sharedpref路径获取它的值

 /// Activity Fields

   ٍString mWinPhotoPath, mLosePhotoPath;
    ImageView winnerImage, loserImage;
    Bitmap winImage, loseImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_winner);
//// Get shared pref values
        mWinPhotoPath = **sharedPreferences.getString(getString(R.string.sharedPreferences_winner_pic), getString(R.string.error_sorry_message));  // win pic
        mLosePhotoPath = sharedPreferences.getString(getString(R.string.sharedPreferences_loser_pic), getString(R.string.error_sorry_message)); // lose pic**


 **winImage = BitmapFactory.decodeFile(mWinPhotoPath);
loseImage = BitmapFactory.decodeFile(mLosePhotoPath);**


// Activity Objects

        **winnerImage = findViewById(R.id.winner_image);**
        **loserImage = findViewById(R.id.loser_image);**

// set values


          **winnerImage.setImageBitmap(winImage);**
          **loserImage.setImageBitmap(loseImage);**

我的日志中没有任何错误,但是问题是ImageView没有显示位图 我还检查了共享首选项是否正确获取了路径值

我的代码中是否存在逻辑错误!!? 有什么问题?

2 个答案:

答案 0 :(得分:0)

要从路径获取位图,您需要在下面使用此代码

File image = new File(mWinPhotoPath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
winImage = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);

答案 1 :(得分:0)

如果要在SharedPrefrence中存储文件的路径,则可以使用其路径将文件解码为位图。

        File f = new File(file path....);
        Bitmap map = BitmapFactory.decodeFile(f.getAbsolutePath());
        image.setImageBitmap(map);

OR

            String fileName = "...."; // file path
            File completeFile = new File(fileName);
            FileInputStream readPicture = new FileInputStream(completeFile);
            BufferedInputStream bf = new BufferedInputStream(readPicture);
            Bitmap bitmap = BitmapFactory.decodeStream(bf);