[英]Android get image to Bitmap from filepath
我正在嘗試從電話上的特定文件路徑設置圖像。 文件路徑是手機上的照片。 文件路徑可能如下所示
/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();
}
最后沒有設置圖像。
使用此方法從文件路徑中獲取位圖
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 ;
}
嘗試這個:
File sd = Environment.getExternalStorageDirectory();
File imageFile = new File(sd+filepath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap image = BitmapFactory.decodeFile(imageFile.getAbsolutePath(),bmOptions);
嘗試這個,
@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.