android之从SD卡加载大图片

和加载小图片一样,首先要让图片存放于Genymotion的SD卡,上篇已经讲了怎么放了,可以看一下上篇,这里就不在说了。。

加载大图片比小图片要复杂一点,要获取屏幕的宽高和图片的宽高,而且大图片放的更清晰了。

代码如下:

布局和上篇的一样

MainActivity:

public class MainActivity extends Activity {

	/*
	 * 从SD卡里加载图片
	 */
	private ImageView iv;
	public void loadImage(View view) {
		// TODO Auto-generated method stub
		if (Environment.getExternalStorageState().
				equals(Environment.MEDIA_MOUNTED)) {
			//路径
			String path=Environment.getExternalStorageDirectory()+
					"/img_big_1.jpg";
			//获取屏幕的宽,高
			WindowManager windowManager=(WindowManager) getSystemService(WINDOW_SERVICE);
//			int screenWidth=windowManager.getDefaultDisplay().getWidth();
//			int screenHeight=windowManager.getDefaultDisplay().getHeight();//过时了
			Display display=windowManager.getDefaultDisplay();
			Point point=new Point();
			display.getSize(point);
			int screenWidth=point.x;
			int screenHeight=point.y;
			System.out.println(screenWidth);
			System.out.println(screenHeight);
			
			//获取原图的宽高
			try {
				ExifInterface exifInterface=new ExifInterface(path);
				int imageWidth=exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0);
				int imageHeight=exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0);
				int sampleWidth=(int)(imageWidth*1.0f/screenWidth+0.5f);//加0.5就是为了四舍五入
				int sampleHeight=(int)(imageHeight*1.0f/screenHeight+0.5f);
				int sample=(int)(Math.sqrt(sampleWidth*sampleWidth+sampleHeight*sampleHeight)+0.5f);
				
				Options options=new Options();
				//设置图片的采样率
				//options.inSampleSize=4;//原宽*1/4   原高*1/4 
				options.inSampleSize=sample;
				//Bitmap bitmap=BitmapFactory.decodeFile(path);
				//iv.setImageBitmap(bitmap);
				Bitmap bitmap=BitmapFactory.decodeFile(path,options);
				iv.setImageBitmap(bitmap);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv=(ImageView) findViewById(R.id.iv);
	}
}


权限:

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



效果图:


要源码的点这儿



你可能感兴趣的:(图片,Path,imageview,大图片,SD卡)