从文件路径创建位图/可绘制

问题描述 投票:67回答:6

我正在尝试从现有文件路径创建一个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);

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

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

java android android-drawable bitmapfactory
6个回答
123
投票

从文件路径创建位图:

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);

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

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


53
投票

这个对我有用:

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);

}

编辑:

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

String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new  File(sdcardPath);

32
投票

这是一个解决方案:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

3
投票

好吧,使用静态Drawable.createFromPath(String pathName)对我来说比自己解码更简单... :-)

如果你的mImg是一个简单的ImageView,你甚至不需要它,直接使用mImg.setImageUri(Uri uri)


1
投票
static ArrayList< Drawable>  d;
d = new ArrayList<Drawable>();
for(int i=0;i<MainActivity.FilePathStrings1.size();i++) {
  myDrawable =  Drawable.createFromPath(MainActivity.FilePathStrings1.get(i));
  d.add(myDrawable);
}

0
投票

你不能通过一个路径访问你的drawables,所以如果你想要一个可绘制的人类可读界面,你可以用编程方式构建。

在你的类中的某个地方声明一个HashMap:

private static HashMap<String, Integer> images = null;

//Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once
  }
}

现在访问 -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.