我正在尝试从现有文件路径创建一个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
我做错了什么?有人可以帮帮我吗?
答案 0 :(得分:122)
从文件路径创建位图:
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
函数。
我认为你提供了错误的文件路径。 :)希望这有帮助。
答案 1 :(得分: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);
答案 2 :(得分:32)
这是一个解决方案:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
答案 3 :(得分:3)
好吧,使用静态Drawable.createFromPath(String pathName)
对我来说比自己解码更简单......: - )
如果您的mImg
是一个简单的ImageView
,您甚至不需要它,直接使用mImg.setImageUri(Uri uri)
。
答案 4 :(得分: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);
}
答案 5 :(得分:1)
Drawable drawable = Drawable.createFromPath(your path in string);
对于位图 -
Bitmap bitmap = BitmapFactory.decodeFile(your path in string);
答案 6 :(得分:0)
您无法通过路径访问您的drawable,因此如果您想要一个可绘制的人类可读界面,您可以以编程方式构建。
在你班级的某处声明一个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);