从文件路径创建位图/ Drawable

Nar*_*hin 76 java android bitmapfactory android-drawable

我正在尝试从现有文件路径创建一个Bitmap或Drawable.

String path = intent.getStringExtra("FilePath");
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPreferredConfig = Bitmap.Config.ARGB_8888;

mImg.setImageBitmap(BitmapFactory.decodeFile(path));
// mImg.setImageBitmap(BitmapFactory.decodeFile(path, option));
// mImg.setImageDrawable(Drawable.createFromPath(path));
mImg.setVisibility(View.VISIBLE);
mText.setText(path);
Run Code Online (Sandbox Code Playgroud)

但是setImageBitmap(),setImageDrawable()没有显示路径中的图像.我打印了路径,mText它看起来像:/storage/sdcard0/DCIM/100LGDSC/CAM00001.jpg

我究竟做错了什么?有人可以帮帮我吗?

Cod*_*dow 132

从文件路径创建位图:

File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);
Run Code Online (Sandbox Code Playgroud)

如果要将位图缩放到父级的高度和宽度,请使用Bitmap.createScaledBitmap函数.

我认为你提供了错误的文件路径.:) 希望这可以帮助.


Kai*_*dul 54

这个对我有用:

File imgFile = new  File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    //Drawable d = new BitmapDrawable(getResources(), myBitmap);
    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
    myImage.setImageBitmap(myBitmap);

}
Run Code Online (Sandbox Code Playgroud)

编辑:

如果以上硬编码的sdcard目录在您的情况下不起作用,则可以获取sdcard路径:

String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new  File(sdcardPath);
Run Code Online (Sandbox Code Playgroud)

  • 尝试从`Environment.getExternalStorageDirectory().toString()`获取SdCard路径,然后尝试 (3认同)

tec*_*rer 37

这是一个解决方案:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Run Code Online (Sandbox Code Playgroud)