Android从filepath获取图像到Bitmap

时间:2015-08-19 06:29:23

标签: java android android-studio bitmapimage

我试图从手机上的特定文件路径设置图像。文件路径是手机上的照片。文件路径看起来像这样

/storage/emulated/0/Pictures/picture.jpg

这是代码。

Bitmap image = null;

//trying to set the image from filepath
try {
    image = BitmapFactory.decodeStream((InputStream) new URL(filepath).getContent());
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

if (image == null) {
    //This becomes true because the image is not set
    Toast.makeText(getApplicationContext(),"image == null",Toast.LENGTH_LONG).show();
}

最后没有设置图像。

3 个答案:

答案 0 :(得分:11)

使用此方法从Filepath获取位图

public Bitmap getBitmap(String path) {
try {
    Bitmap bitmap=null;
    File f= new File(path);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
     image.setImageBitmap(bitmap);
} catch (Exception e) {
    e.printStackTrace();
    return null;
}}

答案 1 :(得分:4)

试试这个:

File sd = Environment.getExternalStorageDirectory();
File imageFile = new File(sd+filepath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap image = BitmapFactory.decodeFile(imageFile.getAbsolutePath(),bmOptions);

答案 2 :(得分:0)

试试这个,

     @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  Intent intent = new Intent(Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(intent, 0);
 }});
 }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK){
 Uri targetUri = data.getData();
 textTargetUri.setText(targetUri.toString());
 Bitmap bitmap;
 try {
  bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
  targetImage.setImageBitmap(bitmap);
 } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}