有时候为了能让用户自定义软件的背景,我们需要实现从系统相册选择一张图片并将其进行保存,在后面打开的时候继续使用该图片充当背景。为什么要保存到私有空间呢?保存和到读取私有空间的内容是不需要权限的。由于实现的代码比较简单所以就直接上代码吧!
activity_main.xml 代码就一个相对布局和一张图片、一个按钮。
<RelativeLayout 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:gravity="center" >
<ImageView
android:id="@+id/img_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="@+id/bt_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择图片"
android:onClick="getPhoto"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageView img_photo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Strin path= getExternalCacheDir().toString()+"/img.jpg";//获取私有空间的图片
img_photo = v.findViewById(R.id.img_photo);
Bitmap bitmap = openImage(path);
img_photo.setImageBitmap(bitmap);//将此图片的位图设置为保存在私有空间的图片
}
public Bitmap openImage(String path) {
Bitmap bitmap = null;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));//打开保存在私有空间的图片
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("文件不存在!");
}
return bitmap;
}
public void getPhoto() {
Intent intent = new Intent();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
} else {
intent.setAction(Intent.ACTION_GET_CONTENT);
}//判断系统的版本,4.4及以上和4.4以下处理方式不同
intent.setType("image/*");
startActivityForResult(intent, 1001);//调用系统图库
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {//判断是不是我们选择图片按钮的回调
if (resultCode == Activity.RESULT_OK && null != data) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(getExternalCacheDir().toString()+"/img.jpg"));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);//将图片复制到私有空间
bos.flush();
bos.close();
Toast.makeText(MainActivity.this, "修改成功,重启后生效!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "修改失败,请重试!", Toast.LENGTH_SHORT).show();
}
}
}
}