【问题标题】:How to store images into ORMLite如何将图像存储到 ORMLite
【发布时间】:2019-02-07 18:44:01
【问题描述】:

我有一个应用程序,每个成员都有一张个人资料照片。用户可以从图库中选择图像。我要将用户的个人资料图像存储到 ORMLite 数据库中。

     profileImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(i, 999);
                }
            });

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri uri = data.getData();
            try {
                photo = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                profileImage.setImageBitmap(photo);
                user.setMember_picture(imageToByte(photo));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private byte[] imageToByte(Bitmap b){
        ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 0, outputstream);
        return outputstream.toByteArray();
    }

在 Uer 类中:

  @DatabaseField(columnName = "PICTURE", dataType = DataType.BYTE_ARRAY)
    private byte[] member_picture;

但它不起作用!

【问题讨论】:

    标签: android sqlite ormlite


    【解决方案1】:

    您可以将图像作为字符串存储在数据库中。为此,您必须使用 Base64 类,例如:

    private String imageToString(Bitmap b){
        ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 0, outputstream);
        return Base64.encodeToString(outputstream.toByteArray(), Base64.DEFAULT);         
    }  
    

    但不要忘记在您的@DatabaseField 中更新DataType

    【讨论】:

      【解决方案2】:

      在数据库中存储图像(或任何类型的文件)通常不是最佳解决方案,因为从 IO 角度来看访问它们可能非常昂贵且速度慢。当您的用户选择特别大的图像时,这个问题可能会更加复杂。

      一种良好且常用的做法是保存图像文件的副本,然后将该文件的路径存储在数据库中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-17
        • 2019-05-06
        • 2019-03-10
        • 2023-04-09
        • 1970-01-01
        • 2021-10-14
        • 2017-03-27
        • 2015-02-28
        相关资源
        最近更新 更多