Android 笔记 litepal 图片存储与加载
今天本想仿qq制作从相机或图库加载照片当做头像,遇到了很多问题,特写此笔记以作总结.
主要用的变量与常量如下
public static final int TAKE_PHOTO = 1; public static final int CHOOSE_PHOTO = 2; private Button paizhao, xiangce; private Uri imageUri; private byte[]images=new byte[1024]; private Bitmap bitmap;
1.把图片存储到数据库
我已经创建了LoginData表,图片存储代码如下
private byte[] headshot;//头像 public byte[] getHeadshot() { return headshot; } public void setHeadshot(byte[] headshot) { this.headshot = headshot; }
2.
把图片转换为字节
private byte[]img(Bitmap bitmap){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); }
到这里我们的数据库以及图片的二进制转换已经做好了接下来说明一下图库与相机的使用
我用的布局文件是谷歌原生自带的抽屉菜单这个imageview在content里面
android:id="@+id/imagetouxiang"
android:onClick="click"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:contentDescription="@string/nav_header_desc"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:layout_weight="6"
android:src="@mipmap/touxiang"
/>
大家可以看到我为这个图片静态注册了一个点击事件点击事件的代码如下
public void click(View view){ Intent intent=new Intent(this,UserMseeage.class); intent.putExtra("账号",userzhanghao); startActivity(intent); }
这里向下一个活动传入了一个账号以便于在数据库中查询数据
xml version="1.0" encoding="utf-8"?>
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:background="@color/light_grey">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
style="@style/MainTitleStyle"
android:elevation="5dp"
android:orientation="horizontal"
>
大家可以看到最下面注册了两个按钮一个为xiangce一个为paizhao 到现在我的布局文件介绍好了,大家可以根据自己的需求进行更改
接下来说明一下如何从相机或相册获取图片数据
paizhao=(Button)findViewById(R.id.paizhao); xiangce=(Button)findViewById(R.id.xiangce) ; xiangce.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ContextCompat.checkSelfPermission(UserMseeage.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(UserMseeage.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } else { openAlbum(); } } }); paizhao.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //创建file对象,用于存储拍照后的图片; File outputImage = new File(getExternalCacheDir(), "output_image.png"); try { if (outputImage.exists()) { outputImage.delete(); } outputImage.createNewFile(); } catch (Exception e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= 24) { imageUri = FileProvider.getUriForFile(UserMseeage.this, "com.example.userlogin.fileprovider", outputImage); } else { imageUri = Uri.fromFile(outputImage); } //启动相机程序 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_PHOTO); } });
@RequiresApi(api = Build.VERSION_CODES.KITKAT) private void handleImageOnKitKat(Intent data) { String imagePath = null; Uri uri = data.getData(); if (DocumentsContract.isDocumentUri(this, uri)) { //如果document类型的Uri,则通过document来处理 String docID = DocumentsContract.getDocumentId(uri); assert uri != null; if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docID.split(":")[1]; //解析出数字格式的id String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/piblic_downloads"), Long.valueOf(docID)); imagePath = getImagePath(contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { //如果是content类型的uri,则使用普通方式使用 imagePath = getImagePath(uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { //如果是file类型的uri,直接获取路径即可 imagePath = uri.getPath(); } displayImage(imagePath); } private void displayImage(String imagePath) { if (imagePath != null) { bitmap = BitmapFactory.decodeFile(imagePath);; } else { Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show(); } } private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); } private String getImagePath(Uri uri, String selection) { String path = null; //通过Uri和selection来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 1: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { openAlbum(); } else { Toast.makeText(this, "you denied the permission", Toast.LENGTH_SHORT).show(); } break; } } private void openAlbum() { Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO); }
接下来是修改清单文件与xml文件
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这个相信大家都明白不做解释了
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.userlogin.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
xml文件
xml version="1.0" encoding="utf-8"?>
name="images"
path="."/>
panh="."表示根目录
好了大部分代码已经贴出来了 接下来是 处理从相机或者相册返回的数据并存入数据库
protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PHOTO: if (resultCode == RESULT_OK) { try { bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); } catch (Exception e) { e.printStackTrace(); } } break; case CHOOSE_PHOTO: if (resultCode == RESULT_OK) { if (Build.VERSION.SDK_INT >= 19) { //4.4及以上的系统使用这个方法处理图片; handleImageOnKitKat(data); } else { handleImageBeforeKitKat(data); //4.4及以下的系统使用这个方法处理图片 } } default: break; } }
好了到这里我们的从相机或相册取出来的图片资源已经保存在了bitmap中接下来 需要用到我们最开始定义的二进制转化函数将图片资源转换为二进制数并存入数据库中
images=img(bitmap); LoginData shuju=new LoginData();
shuju.setHeadshot(images);
如果你是最开始进行数据库的存储别忘了shuju.save();进行保存
我这里由于是对数据进行更新所以代码如下
shuju.setHeadshot(images); shuju.updateAll("user=?",userzhnghao);
到现在数据已经已二进制的形式存入了数据库中,接下来我们讯号将其取出并加载到imageview中
touxiang=(ImageView)headview.findViewById(R.id.imagetouxiang) ;
首先找到布局文件 我这里为content内的布局文件,大家可以更久需求进行更改
Listdatass= DataSupport.where("user=?",userzhanghao).find(LoginData.class); //判断数据是否为空 if(!datass.isEmpty()){ for (LoginData loginData1:datass){ name.setText(loginData1.getYonghumingcheng()); youxiang.setText(loginData1.getYouxiang()); byte[]imagess=loginData1.getHeadshot(); Bitmap bms = BitmapFactory.decodeByteArray(imagess, 0,imagess.length); touxiang.setImageBitmap(bms); break; }}else { name.setText(""); youxiang.setText(""); }
这里领用了litepal插件查询功能 查找到当前账号所对应的数,这里我用了list大家可以根据需求进行更改
接下来判断链表是否为控制也就是查询是否有数据然后对数据进行操作
通过getHeadshot()获取二进制,然后将其转化为 bima资源文件
接下来调用 imagview的setimafebitmap方法更改图片
到这里就大功告成了下面是我的效果图
点击拍摄头像 拍摄成功后 点击对号进行保存
从相册取数据的方法相同
这里要有一点注意由于更换数据后我的返回按钮是利用了finish()所以还需要在onstart()再次进行一次图片的加载
protected void onStart() { NavigationView navigationView=(NavigationView)findViewById(R.id.nav_view); View headview=navigationView.getHeaderView(0); name=(TextView)headview.findViewById(R.id.headname); youxiang=(TextView)headview.findViewById(R.id.headyouxiang); touxiang=(ImageView)headview.findViewById(R.id.imagetouxiang) ; List第一次发帖 请大家海涵 谢谢大家data111= DataSupport.where("user=?",userzhanghao).find(LoginData.class); for (LoginData loginData1:data111){ mima=loginData1.getPwd(); name.setText(loginData1.getYonghumingcheng()); youxiang.setText(loginData1.getYouxiang()); if(loginData1.getHeadshot()!=null) { byte[] images =loginData1.getHeadshot(); Bitmap bm = BitmapFactory.decodeByteArray(images, 0, images.length); touxiang.setImageBitmap(bm); } break; } super.onStart(); }