Dadaji
Dadaji

Reputation: 43

How to store the image in database and shows in listview

I want to store some images on a database, recover them later and show them on a custom ListView. How can I do that?

Here's what I've done so far:

//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 

case 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;

// Set Photo to 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;
    }

}

//Get Real Path Of Image

    @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);
}

Upvotes: 1

Views: 160

Answers (2)

Mauker
Mauker

Reputation: 11497

Well, my advice for storing images on a database is: Don't. It's not effective, and it's best to store them using paths. This was discussed on this question.

But. If you're really into storing that for whatever reason. Try to encode the image as a Base64 String, and store it on your DB.

Android has the Base64 class for this. Try to use the following snippet to encode:

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.

And you'll have to decode it try the following:

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.

You can see the docs for the Bitmap class here.

Upvotes: 3

Priya Singhal
Priya Singhal

Reputation: 1291

1.Convert or encode image to base64 string and store it as a string in database. Decode it again into image when you read from database. 2. Convert image to bytearray and store it in DB.

Upvotes: 0

Related Questions