public class TestActivity extends Activity {
ImageView iv_01;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// 创建用于将图像保存到sd卡上的fileoutputstream对象
FileOutputStream os = new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+"/goicnn.jpg");
InputStream is = getResources().getAssets().open("goicon.jpg"); //打开assets目录下的图片文件,并返回imputstream对象
byte[] buffer = new byte[8191]; //定义一个bye数组,保存每次向sd卡中的文件写入的数据,最多 8K;
int count = 0;
//写入数据
while ((count = is.read(buffer)) >=0) {
os.write(buffer, 0, count);
}
os.close();
is.close();
Toast.makeText(this, "存入图片到sd卡成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO: handle exception
}
iv_01 = (ImageView) findViewById(R.id.iv_01);
readSdData();
}
private void readSdData() {
String fileName = android.os.Environment.getExternalStorageDirectory()+"/goicnn.jpg";
if (!new File(fileName).exists()) {
Toast.makeText(TestActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
return;
}
try {
FileInputStream fis = new FileInputStream(fileName);
Bitmap bitmap = BitmapFactory.decodeStream(fis);//从文件流中装载Bitmap对象
iv_01.setImageBitmap(bitmap);
fis.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>