LitePal图片存储操作以及将相机与图库的照片文件存入数据库并取出加载到imageview

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里面

<ImageView
    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"?>
<ScrollView
    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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            style="@style/MainTitleStyle"
            android:elevation="5dp"
            android:orientation="horizontal"
            >
            <Button
                android:id="@+id/Ufanhui"
                android:layout_width="@dimen/button_height_small"
                android:layout_height="@dimen/button_height_small"
                android:layout_marginLeft="@dimen/spacing_smaller"
                android:background="@drawable/ic_back"/>
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:layout_weight="1"
                android:gravity="center"
                android:text="用户信息详情"
                android:textColor="@color/white"
                android:textSize="@dimen/font_largest"
                />
            <Button
                android:id="@+id/Uqueding"
                android:layout_width="@dimen/button_height_small"
                android:layout_height="@dimen/button_height_small"
                android:layout_marginRight="@dimen/spacing_smaller"
                android:background="@drawable/ic_sure"/>
        </LinearLayout>
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/font_largest"
            android:background="@color/white"
            android:focusableInTouchMode="true"
            android:orientation="vertical"
            android:paddingLeft="@dimen/spacing_normal"
            android:paddingRight="@dimen/spacing_normal"
            >
            <View
                style="@style/WireThinHorizontal"/>
            <TableRow
                android:layout_width="wrap_content"
                android:padding="@dimen/spacing_normal">

                <TextView
                    style="@style/StuInfoType"
                    android:text="账号"
                    />

                <TextView
                    android:id="@+id/Uzhanghao"
                    style="@style/StuInfoDetail"
                    android:digits="0123456789"
                    tools:text="201614550217"/>

            </TableRow>

            <View
                style="@style/WireThinHorizontal"/>

            <TableRow
                android:padding="@dimen/spacing_normal">

                <TextView
                    style="@style/StuInfoType"
                    android:text="用户名称"
                    />

                <EditText
                    android:id="@+id/Uusermingcheng"
                    style="@style/StuInfoDetail"
                    tools:text="李金泽"/>
            </TableRow>
            <View
                style="@style/WireThinHorizontal"/>

            <TableRow
                android:padding="@dimen/spacing_normal">

                <TextView
                    style="@style/StuInfoType"
                    android:text="家庭住址"
                    />

                <EditText
                    android:id="@+id/Ujiatingzhuzhi"
                    style="@style/StuInfoDetail"
                    tools:text="2班"/>
            </TableRow>
            <View
                style="@style/WireThinHorizontal"/>



            <TableRow
                android:id="@+id/Uchushengnianyuetr"
                android:background="@drawable/selector_white_button_style"
                android:padding="@dimen/spacing_normal">

                <TextView
                    style="@style/StuInfoType"
                    android:text="生日"
                    />

                <TextView
                    android:id="@+id/Uchushengnianyuetv"
                    style="@style/StuInfoDetail"
                    tools:text="1998年7月6日"/>

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:src="@drawable/icon_next"/>

            </TableRow>



            <View
                style="@style/WireThinHorizontal"/>



            <View
                style="@style/WireThinHorizontal"/>

            <TableRow
                android:padding="@dimen/spacing_normal">

                <TextView
                    style="@style/StuInfoType"
                    android:text="手机"
                    />

                <EditText
                    android:id="@+id/Udianhua"
                    style="@style/StuInfoDetail"
                    android:digits="0123456789"
                    tools:text="17369322146"/>
            </TableRow>
            <View
                style="@style/WireThinHorizontal"/>

            <TableRow
                android:padding="@dimen/spacing_normal">

                <TextView
                    style="@style/StuInfoType"
                    android:text="邮箱地址"
                    />

                <EditText
                    android:id="@+id/Uyouxiang"
                    style="@style/StuInfoDetail"
                    android:digits="0123456789" />
            </TableRow>
            <Button
            android:id="@+id/paizhao"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/xiugai"
            android:layout_centerHorizontal="true"
            android:background="@drawable/background_login_div"
            android:text="拍摄头像" />

            <View
                style="@style/WireThinHorizontal"/>
        <Button
            android:id="@+id/xiangce"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/xiugai"
            android:layout_centerHorizontal="true"
            android:background="@drawable/background_login_div"
            android:text="打开相册" />
        </TableLayout>



    </LinearLayout>
</ScrollView>

大家可以看到最下面注册了两个按钮一个为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文件

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

这个相信大家都明白不做解释了

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.userlogin.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

xml文件


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <external-path
        name="images"
        path="."/>
</resources>

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内的布局文件,大家可以更久需求进行更改

        List<LoginData> datass= 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<LoginData> 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();
}
第一次发帖 请大家海涵 谢谢大家
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值