简体   繁体   English

Android从文件路径获取图像到位图

[英]Android get image to Bitmap from filepath

I'm trying to set the image from a specific filepath ON THE PHONE.我正在尝试从电话上的特定文件路径设置图像。 The filepath is to the photo on the phone.文件路径是手机上的照片。 the filepath could look like this文件路径可能如下所示

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

Here is the code.这是代码。

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

In the end the image is not set.最后没有设置图像。

Use This Method to get Bitmap from Filepath使用此方法从文件路径中获取位图

public Bitmap getBitmap(String path) {
Bitmap bitmap=null;
try {
    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 bitmap ;
}

try this:尝试这个:

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

Try this,尝试这个,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM