android - 如何将图像存储在数据库中并在 ListView 中显示

标签 android database sqlite listview

我想在数据库中存储一些图像,稍后恢复它们并在自定义 ListView 上显示它们。我该怎么做?

这是我到目前为止所做的:

//here, we are making a folder named picFolder to store pics taken by the camera using this application
dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() + "/picFolder/"; 
    File newdir = new File(dir); 
    if(!newdir.exists()){
        newdir.mkdirs();
    }


//Switch cases are 

案例 R.id.btnPhotoGallary2:

        Intent gallaryIntent = new Intent(Intent.ACTION_PICK,
                   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(gallaryIntent , TAKE_GALLARY_CODE);//one can be replced with any action code
        break;

    case R.id.btnPhotoCamera1:
        count++;
        String file = dir+count+".jpg";
        File newfile = new File(file);
        try {
            newfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }       

        capturedPhotoUri = Uri.fromFile(newfile);

        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedPhotoUri);

        startActivityForResult(cameraIntent, TAKE_CAMERA_CODE);
        break;

//将照片设置为 Button/ImageView

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case 0://Captured photo from Camera
        if(resultCode == RESULT_OK){  
            String pathNamePhoto = capturedPhotoUri.getPath().toString();
            System.out.println("Photo Path Is :"+pathNamePhoto);
            d = BitmapDrawable.createFromPath(pathNamePhoto);
            ivProfile.setImageDrawable(d);
            Log.d("CameraDemo", "Pic saved");
            Log.v("CapturedPhoto PATH ==>> ",pathNamePhoto);
            pd.setProfImagepath(pathNamePhoto);
        }
        dialog.dismiss();
        break;


    case 1://Select Image from Gallery
        if(resultCode == RESULT_OK){  
            Uri selImageUri = data.getData();
            String pathNameImage = getPath(selImageUri);
            System.out.println("Image Path Is :"+pathNameImage);

            ivProfile.setImageURI(selImageUri);
            Log.d("GallaryDemo", "Get Pic ");
            Log.v("IMAGE PATH ==>> ",pathNameImage);
            pd.setProfImagepath(pathNameImage);
        }          
        dialog.dismiss();
        break;
    }

}

//获取图片真实路径

    @SuppressWarnings("deprecation")
public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

最佳答案

嗯,我对在数据库中存储图像的建议是:不要。 效果不佳,最好使用路径存储。这在 this question 上讨论过.

但是。如果你真的出于任何原因存储它。尝试将图像编码为 Base64 String,并将其存储在您的数据库中。

Android 有 Base64 class为了这。尝试使用以下代码 fragment 进行编码:

Bitmap bitmap = BitmapFactory.decodeFile("image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // Could be Bitmap.CompressFormat.PNG or Bitmap.CompressFormat.WEBP
byte[] bai = baos.toByteArray();

String base64Image = Base64.encodeToString(bai, Base64.DEFAULT);

// Call your method to save this string on the DB here.

并且您必须尝试以下操作对其进行解码:

byte[] data = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap bm;
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
bm = BitmapFactory.decodeByteArray(data, 0, data.length, opt);

// Now do whatever you want with the Bitmap.

您可以查看 Bitmap 类的文档 here .

关于android - 如何将图像存储在数据库中并在 ListView 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30987876/

相关文章:

google-app-engine - 如何导入谷歌应用引擎sqlite数据文件?

android - 无法在 Android Studio 中解析符号 'annotation'?

android - Android 的快速对话框之类的框架?

php - Fusionchart : Some String Chracters Not Display In Fusion Pie Chart

sql - 在 nvarchar 列中找到两个或更多相似字符

SQL选择具有唯一ID的不同

php - PDO SQLite 查询零结果问题

android - 如何处理 Ion(android 库)没有互联网连接?

android - ARCore:模拟器和统一

java - 外键也是主键的一部分