从文件path创build一个位图/绘图

我试图从现有的文件path创build一个位图或绘图。

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()不显示path中的图像。 我用mText打印path,它看起来像: /storage/sdcard0/DCIM/100LGDSC/CAM00001.jpg

我究竟做错了什么? 任何人都可以帮助我?

从文件path创build位图:

 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函数。

我认为你正在给错误的文件path。 :) 希望这可以帮助。

这个对我有用:

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

编辑:

如果上面的硬编码SD卡目录不工作在你的情况下,你可以获取SD卡path:

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

这里是一个解决scheme:

 Bitmap bitmap = BitmapFactory.decodeFile(filePath); 

那么,使用静态的Drawable.createFromPath(String pathName)似乎比自己解码它更简单一点::-)

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

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

你不能通过一个path访问你的drawable,所以如果你想要一个可读的界面,你可以用编程的方式构build你的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);