最近在写一个照相的程序时,发现照片能照出来保存,可是读取时想让它显示在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="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/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;
@Override
protected 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^2
Bitmap bitmap=BitmapFactory.decodeFile(path, opts);
iv.setImageBitmap(bitmap);
}
else{
Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_LONG).show();
}
}
}
这样大图片就可以查看了
转载自原文链接, 如需删除请联系管理员。
原文链接:Android中图片无法显示,读取图片的方法,转载请注明来源!