【问题标题】:Show Image View from file path?从文件路径显示图像视图?
【发布时间】:2011-05-10 01:37:35
【问题描述】:

我需要仅使用文件名而不是资源 ID 来显示图像。

ImageView imgView = new ImageView(this);
imgView.setBackgroundResource(R.drawable.img1);

我在可绘制文件夹中有图像 img1。我希望从文件中显示该图像。

我该怎么做?

【问题讨论】:

    标签: android imageview android-imageview android-file


    【解决方案1】:

    如果您的资源已经在资源文件夹中,为什么您需要使用路径设置图像,Labeeb 是正确的,

    只有当您的图像存储在 SD 卡中时才需要这种路径。

    并且尝试使用以下代码从存储在 SD 卡中的文件设置位图图像。

    File imgFile = new  File("/sdcard/Images/test_image.jpg");
    
    if(imgFile.exists()){
    
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    
        ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
    
        myImage.setImageBitmap(myBitmap);
    
    }
    

    并在清单文件中包含此权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    【讨论】:

    • 几乎:“decodeFile”接受一个字符串而不是一个“java.io.File”。
    • Martin 在 java.io.File 上调用的方法 getAbsolutePath() 正在返回字符串。
    • 虽然这可行且正确,但从不建议“命中”主线程上的磁盘。 BitmapFactory相关方法应该在bg线程中调用。毕加索会自动为您处理。
    • 因此您几乎不想复制粘贴此代码,因为您实际上是将整个原始图像加载到内存中。图像应在后台调整大小并加载到内存中。然后图像应该设置为 ImageView。
    • 假设文件已正确调整大小并且您拥有文件路径,我建议使用以下方法:stackoverflow.com/questions/3004713/…。即ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
    【解决方案2】:

    我觉得你可以用这个

    Bitmap bmImg = BitmapFactory.decodeFile("path of your img1");
    imageView.setImageBitmap(bmImg);
    

    【讨论】:

    • 位图 bmImg = BitmapFactory.decodeFile("res\\drawable-hdpi\\img1.png");我像上面一样设置路径但我无法显示图像
    • 你不能在这里使用你的资源路径。只能用于存储图像形式的 sd 卡或其他内存。我想知道,如果您的资源在资源文件夹中,为什么您需要使用路径设置图像
    【解决方案3】:

    你也可以使用:

    
    
        File imgFile = new  File(“filepath”);
        if(imgFile.exists())
        {
            ImageView myImage = new ImageView(this);
            myImage.setImageURI(Uri.fromFile(imgFile));
    
        }
    
    

    这将为您隐含位图解码。

    【讨论】:

      【解决方案4】:

      所有答案都已过时。最好将picasso 用于此类目的。它有很多功能,包括背景图像处理。

      我有没有提到它超级好用:

      Picasso.with(context).load(new File(...)).into(imageView);
      

      【讨论】:

      • 如果使用图库或相机中的文件,它不需要权限。
      • 更新:Picasso.get().load(new File(...)).into(imageView);
      【解决方案5】:
      String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
      
      File imgFile = new File(path);
      if(imgFile.exists())
      {
         Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
         ImageView imageView=(ImageView)findViewById(R.id.imageView);
        imageView.setImageBitmap(myBitmap);
      }
      

      【讨论】:

        【解决方案6】:

        来自官网:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

        ImageView image = (ImageView) findViewById(R.id.imagePreview);           
        try {
            image.setImageBitmap(decodeSampledBitmap(picFilename));
        } catch (Exception e) {
            e.printStackTrace();
        }
        

        方法如下:

            private int calculateInSampleSize(
                    BitmapFactory.Options options, int reqWidth, int reqHeight) {
                // Raw height and width of image
                final int height = options.outHeight;
                final int width = options.outWidth;
                int inSampleSize = 1;
        
                if (height > reqHeight || width > reqWidth) {
        
                    final int halfHeight = height / 2;
                    final int halfWidth = width / 2;
        
                    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                    // height and width larger than the requested height and width.
                    while ((halfHeight / inSampleSize) > reqHeight
                            && (halfWidth / inSampleSize) > reqWidth) {
                        inSampleSize *= 2;
                    }
                }
        
                return inSampleSize;
            }
        
            private Bitmap decodeSampledBitmap(String pathName,
                    int reqWidth, int reqHeight) {
        
                // First decode with inJustDecodeBounds=true to check dimensions
                final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(pathName, options);
        
                // Calculate inSampleSize
                options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        
                // Decode bitmap with inSampleSize set
                options.inJustDecodeBounds = false;
                return BitmapFactory.decodeFile(pathName, options);
            }
        
        //I added this to have a good approximation of the screen size: 
            private Bitmap decodeSampledBitmap(String pathName) {
                Display display = getWindowManager().getDefaultDisplay();
                Point size = new Point();
                display.getSize(size);
                int width = size.x;
                int height = size.y;
                return decodeSampledBitmap(pathName, width, height);
            }   
        

        【讨论】:

          【解决方案7】:

          如何在 Android 中显示文件夹路径中的图像

          首先:确保您已将权限添加到 Mainfest 文件中:

           <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
          

          :创建一个班级我的画廊

          public class MyGallery extends Activity {
          
          
              private GridView gridView;
              private String _location;
          
              private String newFolder = "/IslamicGif/";
              private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
              private AdView mAdView;
              private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
              public static String[] imageFileList;
              TextView gallerytxt;
          
              public static ImageAdapter imageAdapter;
          
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  requestWindowFeature(Window.FEATURE_NO_TITLE);
                  setContentView(R.layout.mygallery);
                  /*if (MenuClass.mInterstitialAd.isLoaded()) {
                      MenuClass.mInterstitialAd.show();
                  }*/
          
                  gallerytxt = (TextView) findViewById(R.id.gallerytxt);
                  /*gallerytxt.setTextSize(20);
                  int[] color = {Color.YELLOW,Color.WHITE};
                  float[] position = {0, 1};
                  Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
                  LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
                  Shader shader_gradient0 = lin_grad0;
                  gallerytxt.getPaint().setShader(shader_gradient0);*/
                  ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
                  btn_back.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View view) {
                          MyGallery.this.finish();
                      }
                  });
          
          
                  mAdView = (AdView) findViewById(R.id.adView);
                  AdRequest adRequest = new AdRequest.Builder()
                          .build();
                  mAdView.loadAd(adRequest);
                  gridView = (GridView) findViewById(R.id.gridView);
          
                  new MyGalleryAsy().execute();
          
                  gridView.setOnItemClickListener(new OnItemClickListener() {
          
                      @Override
                      public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                          // TODO Auto-generated method stub
                          Intent intent = new Intent(MyGallery.this, ImageDetail.class);
                          intent.putExtra("ImgUrl", imageFileList[pos]);
          
                          //Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
                          startActivity(intent);
                      }
                  });
          
          
              }
          
              protected void onStart() {
                  super.onStart();
                  if (ImageDetail.deleted) {
                      photo = new ArrayList<Bitmap>();
                      new MyGalleryAsy().execute();
                      ImageDetail.deleted = false;
                  }
          
              }
          
              public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
                  private ProgressDialog dialog;
                  Bitmap mBitmap;
          
                  @Override
                  protected void onPreExecute() {
                      dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
                      dialog.show();
                  }
          
                  @Override
                  protected Void doInBackground(Void... arg0) {
          
                      readImage();
                      return null;
                  }
          
                  @Override
                  protected void onPostExecute(Void result) {
          
                      dialog.dismiss();
                      DisplayMetrics displayMatrics = new DisplayMetrics();
                      getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
                      int screenWidth = displayMatrics.widthPixels / 3;
          
                      if (photo.size() > 0) {
                          imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
                          gridView.setAdapter(imageAdapter);
                      }
          
                  }
          
              }
          
          
              private void readImage() {
                  // TODO Auto-generated method stub
          
          
                  try {
                      if (isSdPresent()) {
                          _location = extStorageDirectory + newFolder;
                      } else
                          _location = getFilesDir() + newFolder;
                      File file1 = new File(_location);
          
                      if (file1.isDirectory()) { // sdCard == true
                          imageFileList = file1.list();
                          if (imageFileList != null) {
                              for (int i = 0; i < imageFileList.length; i++) {
                                  try {
                                      photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
                                  } catch (Exception e) {
                                      // TODO: handle exception
                                      //Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
                                  }
                              }
                          }
                      }
                  } catch (Exception e) {
                      // TODO: handle exception
                  }
              }
          
              public static boolean isSdPresent() {
                  return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
              }
          
              public class ImageAdapter extends BaseAdapter {
          
                  private Context context;
                  private LayoutInflater layoutInflater;
                  private int width;
                  private int mGalleryItemBackground;
          
                  public ImageAdapter(Context c) {
                      context = c;
          
                  }
          
                  public ImageAdapter(Context c, int width) {
                      context = c;
                      this.width = width;
                  }
          
                  public int getCount() {
                      return photo.size();
                  }
          
                  public Object getItem(int position) {
                      return null;
                  }
          
                  public long getItemId(int position) {
                      return 0;
                  }
          
                  public View getView(int position, View convertView, ViewGroup parent) {
                      View v = convertView;
                      layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                      v = layoutInflater.inflate(R.layout.galleryadapter, null);
          
                      RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);
          
                      ImageView imageView = new ImageView(context);
                      layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
                      imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                      layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
                      imageView.setImageBitmap(photo.get(position));
          
                      return v;
          
                  }
          
                  public void updateItemList(ArrayList<Bitmap> newItemList) {
                      photo = newItemList;
                      notifyDataSetChanged();
                  }
              }
          
          
          }
          

          现在创建它的 Xml 类

          <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:ads="http://schemas.android.com/apk/res-auto"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@drawable/bg"
          android:orientation="vertical">
          
          <RelativeLayout
              android:id="@+id/relativeLayout"
              android:layout_width="match_parent"
              android:layout_height="56dp"
              android:background="@color/colorPrimary"
              android:minHeight="?attr/actionBarSize">
          
              <TextView
                  android:id="@+id/gallerytxt"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_centerHorizontal="true"
                  android:layout_centerVertical="true"
                  android:layout_gravity="center"
                  android:fontFamily="@string/font_fontFamily_medium"
                  android:text="My Gallery"
                  android:textAppearance="?android:attr/textAppearanceMedium"
                  android:textColor="@android:color/black"
                  android:textStyle="bold" />
          
              <ImageButton
                  android:id="@+id/btn_back"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_alignParentLeft="true"
                  android:layout_alignParentStart="true"
                  android:layout_centerVertical="true"
                  android:layout_marginLeft="12dp"
                  android:background="@drawable/ic_arrow_back_black_24dp" />
          </RelativeLayout>
          
          
          <com.google.android.gms.ads.AdView
              android:id="@+id/adView"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_alignParentBottom="true"
              android:layout_alignParentLeft="true"
              android:layout_alignParentStart="true"
              android:layout_gravity="center|bottom"
              android:visibility="gone"
              ads:adSize="BANNER"
              ads:adUnitId="@string/banner_id" />
          
          <GridView
              android:id="@+id/gridView"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_above="@+id/adView"
              android:layout_alignParentLeft="true"
              android:layout_alignParentStart="true"
              android:layout_below="@+id/relativeLayout"
              android:horizontalSpacing="5dp"
              android:numColumns="2"
              android:smoothScrollbar="true"
              android:verticalSpacing="5dp"></GridView>
          
          ## 还要制作适配器galleryadapter.xml ##
          <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          xmlns:ads="http://schemas.android.com/apk/res-auto"
          android:orientation="vertical"
          android:id="@+id/galleryLayout"
          android:padding="2dp">
          
          [![在此处输入图像描述][1]][1]

          要详细查看图像,请创建一个新类 ImageDetail:##

           public class ImageDetail extends Activity implements OnClickListener {
              public static InterstitialAd mInterstitialAd;
              private ImageView mainImageView;
              private LinearLayout menuTop;
              private TableLayout menuBottom;
              private Boolean onOff = true;
              private ImageView delButton, mailButton, shareButton;
          
              private String imgUrl = null;
              private AdView mAdView;
              TextView titletxt;
              private String newFolder = "/IslamicGif/";
              private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
              public static boolean deleted = false;
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  requestWindowFeature(Window.FEATURE_NO_TITLE);
                  setContentView(R.layout.image_detail);
          
                  mAdView = (AdView) findViewById(R.id.adView);
                  AdRequest adRequest = new AdRequest.Builder()
                          .build();
                  mAdView.loadAd(adRequest);
                  mAdView.setAdListener(new AdListener() {
                      @Override
                      public void onAdLoaded() {
                          mAdView.setVisibility(View.VISIBLE);
                      }
                  });
                  mainImageView = (ImageView) findViewById(R.id.mainImageView);
                  menuTop = (LinearLayout) findViewById(R.id.menuTop);
                  menuBottom = (TableLayout) findViewById(R.id.menuBottom);
                  titletxt = (TextView) findViewById(R.id.titletxt);
                  titletxt.setTextSize(22);
                  mInterstitialAd = new InterstitialAd(this);
                  mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));
          
                  mInterstitialAd.setAdListener(new AdListener() {
                      @Override
                      public void onAdClosed() {
                          requestNewInterstitial();
          
                      }
                  });
                  requestNewInterstitial();
                  delButton = (ImageView) findViewById(R.id.delButton);
                  mailButton = (ImageView) findViewById(R.id.mailButton);
                  shareButton = (ImageView) findViewById(R.id.shareButton);
          
                  Bundle exBundle = getIntent().getExtras();
                  if (exBundle != null) {
                      imgUrl = exBundle.getString("ImgUrl");
                  }
                  if (isSdPresent()) {
                      imgUrl = extStorageDirectory + newFolder + imgUrl;
                  } else
                      imgUrl = getFilesDir() + newFolder + imgUrl;
          
                  if (imgUrl != null) {
                      GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
                      Glide.with(this).load(imgUrl).into(imageViewTarget);
          
                  }
          
          
                  delButton.setOnClickListener(this);
                  mailButton.setOnClickListener(this);
                  shareButton.setOnClickListener(this);
          
          
              }
          
              public static boolean isSdPresent() {
                  return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
              }
          
          
              @Override
              public void onClick(View arg0) {
                  // TODO Auto-generated method stub
                  switch (arg0.getId()) {
                      case R.id.shareButton:
                          Image_Link();
                          break;
                      case R.id.delButton:
                          deleted();
                          break;
                      case R.id.mailButton:
                          sendemail();
                          break;
                      default:
                          break;
                  }
              }
          
              private void sendemail() {
          
                  try {
          
                      File photo = new File(imgUrl);
                      Uri imageuri = Uri.fromFile(photo);
          
          
                      String url = Constant.AppUrl;
          
                      SpannableStringBuilder builder = new SpannableStringBuilder();
                      builder.append("Face Placer App Available here..Play Link");
                      int start = builder.length();
                      builder.append(url);
                      int end = builder.length();
          
                      builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
          
                      Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
                      String[] recipients2 = new String[]{"mymail@email.com", "",};
                      emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
                      emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
                      emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
                      emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
                      emailIntent2.setType("text/html");
                      emailIntent2.setType("image/JPEG");
                      startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
          
                  } catch (Exception e) {
                      // TODO: handle exception
          
                      Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                  }
              }
          
          
              private void Image_Link() {
          
                  try {
          
                      File photo = new File(imgUrl);
                      Uri imageuri = Uri.fromFile(photo);
          
          
                      String url = Constant.AppUrl;
          
                      SpannableStringBuilder builder = new SpannableStringBuilder();
                      builder.append("Face Placer App Available here..Play Link");
                      int start = builder.length();
                      builder.append(url);
                      int end = builder.length();
          
                      builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
          
                      Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
                      String[] recipients2 = new String[]{"mymail@email.com", "",};
                      emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
                      emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
                      emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
                      emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
                      emailIntent2.setType("text/html");
                      emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
                      emailIntent2.setType("image/JPEG");
                      startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
          
                  } catch (Exception e) {
                      // TODO: handle exception
          
                      Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                  }
              }
          
          
              private void deleted() {
                  if (mInterstitialAd.isLoaded()) {
                      mInterstitialAd.show();
                  }
          
                  AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
                  builder.setTitle(getString(R.string.removeoption));
                  builder.setMessage(getString(R.string.deleteimage));
                  builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int id) {
                          // User clicked OK button
                          dialog.cancel();
                          File fileDel = new File(imgUrl);
                          boolean isCheck1 = fileDel.delete();
          
                          if (isCheck1) {
                              deleted = true;
                              finish();
                              MyGallery.imageAdapter.notifyDataSetChanged();
          
                          } else {
                              Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
                          }
                      }
                  });
          
                  builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int id) {
                          // User clicked OK button
                          dialog.cancel();
          
                      }
                  });
                  Dialog dialog = builder.create();
                  dialog.show();
          
          
              }
          
          
              private boolean isNetworkConnected() {
                  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                  NetworkInfo ni = cm.getActiveNetworkInfo();
                  if (ni == null) {
                      // There are no active networks.
                      return false;
                  } else
                      return true;
              }
          
              private void requestNewInterstitial() {
                  AdRequest adRequest = new AdRequest.Builder()
                          .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                          .build();
          
                  mInterstitialAd.loadAd(adRequest);
              }
          
          }
          

          创建其 xml image_detail.xml

          <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:ads="http://schemas.android.com/apk/res-auto"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:background="@drawable/bg"
          android:orientation="vertical">
          
          <ImageView
              android:id="@+id/mainImageView"
              android:layout_width="match_parent"
              android:layout_height="fill_parent"
              android:layout_alignParentBottom="true"
              android:contentDescription="@string/app_name"
              android:focusable="true"
              android:focusableInTouchMode="true" />
          
          <LinearLayout
              android:id="@+id/adlayout"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:orientation="horizontal"
              android:visibility="gone"></LinearLayout>
          
          <LinearLayout
              android:id="@+id/menuTop"
              android:layout_width="fill_parent"
              android:layout_height="56dp"
              android:layout_alignWithParentIfMissing="true"
              android:layout_below="@+id/adlayout"
              android:background="@color/colorPrimary"
              android:orientation="vertical"
              android:padding="10.0dip"
              android:visibility="visible">
          
              <TextView
                  android:id="@+id/titletxt"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:gravity="center"
                  android:text="Islamic Gifs"
                  android:textColor="#000000"
                  android:textSize="22sp"
                  android:textStyle="bold" />
          </LinearLayout>
          
          <TableLayout
              android:id="@+id/menuBottom"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentBottom="true"
              android:background="@color/colorPrimary"
              android:padding="10.0dip"
              android:stretchColumns="*"
              android:visibility="visible">
          
              <TableRow>
          
                  <LinearLayout
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:gravity="center_horizontal">
          
                      <ImageView
                          android:id="@+id/mailButton"
                          android:layout_width="52dp"
                          android:layout_height="52dp"
                          android:background="@drawable/selector_shareimage"
                          android:contentDescription="@string/app_name" />
                  </LinearLayout>
          
                  <LinearLayout
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:gravity="center_horizontal">
          
                      <ImageView
                          android:id="@+id/shareButton"
                          android:layout_width="52dp"
                          android:layout_height="52dp"
                          android:background="@drawable/selector_shareimage_small"
                          android:contentDescription="@string/app_name" />
                  </LinearLayout>
          
                  <LinearLayout
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:gravity="center_horizontal">
          
                      <ImageView
                          android:id="@+id/delButton"
                          android:layout_width="52dp"
                          android:layout_height="52dp"
                          android:background="@drawable/selector_delete"
                          android:contentDescription="@string/app_name" />
                  </LinearLayout>
              </TableRow>
          </TableLayout>
          
          <com.google.android.gms.ads.AdView
              android:id="@+id/adView"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_below="@+id/menuTop"
              android:layout_centerHorizontal="true"
              android:visibility="gone"
              ads:adSize="BANNER"
              ads:adUnitId="@string/banner_id"></com.google.android.gms.ads.AdView>
          

          将你自己的 Drawable 添加到 Selector 类中,并创建它 res>drawable>selector_shareimage.xml

          <?xml version="1.0" encoding="utf-8"?>
          
          <item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
          <item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
          <item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
          <item android:drawable="@drawable/result_bt_mail_s"/>
          

          不要忘记为 sdk 版本 29 和 30 添加应用程序标签 以添加此行

          android:requestLegacyExternalStorage="true"

           <application
              android:allowBackup="true"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:requestLegacyExternalStorage="true"
              android:roundIcon="@mipmap/ic_launcher_round"
              android:supportsRtl="true"
              android:theme="@style/AppTheme">
          

          【讨论】:

          • 这个问题只是关于“从文件路径显示图像视图”!
          • 少即是多的好例子!你的回答过于复杂了。
          【解决方案8】:

          你可以使用:

          ImageView imgView = new ImageView(this);
          InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
          imgView.setImageDrawable(Drawable.createFromStream(is, ""));
          

          【讨论】:

            【解决方案9】:

            您可以使用它来访问特定文件夹并获取特定图像

             public void Retrieve(String path, String Name)
               {
                File imageFile = new File(path+Name);
            
                if(imageFile.exists()){
            
                    Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
                    myImage = (ImageView) findViewById(R.id.savedImage);
                    myImage.setImageBitmap(myBitmap);
                    Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();
            
                }
            }
            

            然后你可以调用它

            Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
            Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();
            

            【讨论】:

              【解决方案10】:
                     public static Bitmap decodeFile(String path) {
                  Bitmap b = null;
                  File f = new File(path);
                  // Decode image size
                  BitmapFactory.Options o = new BitmapFactory.Options();
                  o.inJustDecodeBounds = true;
              
                  FileInputStream fis = null;
                  try {
                      fis = new FileInputStream(f);
                      BitmapFactory.decodeStream(fis, null, o);
                      fis.close();
              
                      int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
                      int scale = 1;
                      if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                          scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
                      }
              
                      // Decode with inSampleSize
                      BitmapFactory.Options o2 = new BitmapFactory.Options();
                      o2.inSampleSize = scale;
              
                      fis = new FileInputStream(f);
                      b = BitmapFactory.decodeStream(fis, null, o2);
                      fis.close();
              
                  } catch (Exception e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              
                  return b;
              }
              
              public static Bitmap showBitmapFromFile(String file_path)
              {
                  try {
                      File imgFile = new  File(file_path);
                      if(imgFile.exists()){
              
                          Bitmap pic_Bitmap = decodeFile(file_path);
                          return pic_Bitmap;
              
                      }
                  } catch (Exception e) {
                      MyLog.e("Exception showBitmapFromFile");
                      return null;
                  }
                  return null;
              }   
              

              如果您在列表视图中使用图像加载,请使用 Aquery 概念。

              https://github.com/AshishPsaini/AqueryExample

                   AQuery  aq= new AQuery((Activity) activity, convertView);
                          //load image from file, down sample to target width of 250 pixels .gi 
                  File file=new File("//pic/path/here/aaaa.jpg");
                  if(aq!=null)
                  aq.id(holder.pic_imageview).image(file, 250);
              

              【讨论】:

                【解决方案11】:

                onLoadImage 满载

                private void onLoadImage(final String imagePath) {
                    ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size
                
                    //ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
                    com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
                    imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
                
                    imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(final String imageUri, View view) {
                            super.onLoadingStarted(imageUri, view);
                
                            progress2.setVisibility(View.VISIBLE);
                
                            new Handler().post(new Runnable() {
                                public void run() {
                                    progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
                
                                    // Picasso.with(getContext()).load(imagePath).into(imageView);
                                    // Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);
                
                                    Glide.with(getContext())
                                            .load(imagePath)
                                            .asBitmap()
                                            .into(imageView);
                                }
                          });
                        }
                
                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            if (view == null) {
                                progress2.setVisibility(View.INVISIBLE);
                            }
                            // else { 
                              Log.e("onLoadImage", "onLoadingComplete");
                            //   progress2.setVisibility(View.INVISIBLE);
                            // }
                            // setLoagingCompileImage();
                        }
                
                        @Override
                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                            super.onLoadingFailed(imageUri, view, failReason);
                            if (view == null) {
                                progress2.setVisibility(View.INVISIBLE);
                            }
                            Log.e("onLoadingFailed", imageUri);
                            Log.e("onLoadingFailed", failReason.toString());
                        }
                
                        @Override
                        public void onLoadingCancelled(String imageUri, View view) {
                            super.onLoadingCancelled(imageUri, view);
                            if (view == null) {
                                progress2.setVisibility(View.INVISIBLE);
                            }
                            Log.e("onLoadImage", "onLoadingCancelled");
                        }
                    });
                }
                

                【讨论】:

                  【解决方案12】:
                  private void showImage(ImageView img, String absolutePath) {
                    
                      BitmapFactory.Options options = new BitmapFactory.Options();
                      options.inSampleSize = 8;
                      Bitmap bitmapPicture = BitmapFactory.decodeFile(absolutePath);
                      img.setImageBitmap(bitmapPicture);
                  
                  }
                  

                  【讨论】:

                    【解决方案13】:

                    大多数答案都有效,但没有人提到高分辨率图像会减慢应用程序的速度,在我的例子中,我使用了图像 RecyclerView,它在 30 张图像中占用了 0.9 GB 的设备内存。

                    I/Choreographer:跳过了 73 帧!该应用程序可能也在做 在它的主线程上做了大量工作。

                    解决方案是 Sipmle,您可以像这里一样降低质量:Reduce resolution of Bitmap

                    但我使用简单的方式,Glide 处理剩下的工作

                    fanContext?.let {
                                Glide.with(it)
                                    .load(Uri.fromFile(File(item.filePath)))
                                    .into(viewHolder.imagePreview)
                            }
                    

                    【讨论】:

                      【解决方案14】:
                      mageView.setImageResource(R.id.img);
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-11-16
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2019-01-08
                        • 2019-01-13
                        • 2016-06-12
                        相关资源
                        最近更新 更多