Android中图片无法显示,读取图片的方法

编程入门 行业动态 更新时间:2024-10-23 09:33:43

Android中<a href=https://www.elefans.com/category/jswz/34/1770705.html style=图片无法显示,读取图片的方法"/>

Android中图片无法显示,读取图片的方法

最近在写一个照相的程序时,发现照片能照出来保存,可是读取时想让它显示在ImageView中,却怎么也显示不出来,后来经过查阅资料才知道是图片太大了,下面来分享一种处理照片显示问题的方式。
1.首先得获得相应的权限,SD卡读取的权限

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

2.布局文件为activity_main.xml

<LinearLayout xmlns:android=""xmlns:tools=""android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><ImageView android:id="@+id/iv"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"/>
</LinearLayout>

3.对文件进行处理

public class MainActivity extends Activity {private ImageView iv;private int windowheight;private int windowwidth;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);WindowManager wm=(WindowManager) getSystemService(WINDOW_SERVICE);windowheight=wm.getDefaultDisplay().getHeight();windowwidth=wm.getDefaultDisplay().getWidth();iv=(ImageView) findViewById(R.id.iv);String path=Environment.getExternalStorageDirectory()+File.separator+"Myphoto.png";     File file=new File(path);if(file.exists()){BitmapFactory.Options opts=new Options();opts.inJustDecodeBounds=true;Bitmap bm=BitmapFactory.decodeFile(path,opts);int imageHeight =opts.outHeight;int imageWidth=opts.outWidth;       int scaleX=imageWidth/windowwidth;int scaleY=imageHeight/windowheight;int scale=1;if(scaleX>scaleY&scaleY>=1){scale=scaleX;}if(scaleY>scaleX&scaleX>=1){scale=scaleY;}opts.inJustDecodeBounds=false;opts.inSampleSize=scale;//采样率变为原来图片的1/scale^2Bitmap bitmap=BitmapFactory.decodeFile(path, opts); iv.setImageBitmap(bitmap);      }else{Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_LONG).show();}                }
}

这样大图片就可以查看了


更多推荐

Android中图片无法显示,读取图片的方法

本文发布于:2024-03-09 15:32:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1725379.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图片   方法   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!