Android使用文件系统保存从相机或图库中拍摄的图像

时间:2011-12-07 12:10:40

标签: android image sqlite camera gallery

我想将图像uri从摄像机或图库保存到SQLite中。 我想显示从SQLite调用uri的图像。 如果我想这样做,有人说你必须将图像uri保存到SQLite中作为字节,并且 您可以在imageView上设置图片。 我理解这个理论,但我仍然对我的编码感到困惑。 如果是这样,我想将格式化的图像保存到SD卡或某处。 有人说使用BitmapFactorydecodeResource。 并从R.drawable致电uri。 但是,我不知道如何将图像保存到R.drawable文件夹中。 你可以帮帮我吗?我会给你一些我的编码。 我正在努力将图像保存到SQLite中以及如何加载它,以及如何在两周内修改它!

很抱歉很长时间编码。我不知道我现在在哪里。 谢谢。

fridgeDetails.java

populateFields();

private void populateFields() 
{
    if (mRowId != null)
    {
        Cursor data = mDbHelper.fetchItem(mRowId);
        startManagingCursor(data);
        //load image from sqlite
        byte[] blob = data.getBlob(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_IMAGE));
        mImageView.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length));
        nameEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_NAME)));
        categoryEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_CATEGORY)));
        expired_Date_Btn.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_EXPIRED_DATE)));
    }
    else{
    expired_Date_Btn.setText(
            new StringBuilder()
            .append(mDay).append("/")
            //month is 0 based. Then add 1
            .append(mMonth + 1).append("/")
            .append(mYear).append(" "));    
    }

}
    //create dialog for taking image
    ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
    AlertDialog.Builder builder  = new AlertDialog.Builder(this);
    builder.setTitle("Select Image");

    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) 
        {
            if(item==0)
            {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                try
                {
                    cameraIntent.putExtra("return-data", true);
                    startActivityForResult(cameraIntent, PICK_FROM_CAMERA); 
                }
                catch(ActivityNotFoundException e)
                {
                    e.printStackTrace();
                }                   
            }
            else
            {
                Intent galleryIntent = new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                //image chooser
                startActivityForResult(Intent.createChooser(galleryIntent, "Complete action using"), PICK_FROM_GALLERY);
            }
        }   
    });

confirmButton.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View v) {
            //set alarm with expiration date                
            am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            setOneTimeAlarm();
            Toast.makeText(fridgeDetails.this, "Alarm automatic set", Toast.LENGTH_SHORT).show();
            saveState();
            setResult(RESULT_OK);
            finish();
        }

    });

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
     if (resultCode != RESULT_OK) return;
       switch (requestCode)
       {
        case PICK_FROM_CAMERA:
            Bundle extras = data.getExtras();
            Bitmap selectedImage = (Bitmap) extras.get("data");
            selectedImage = Bitmap.createScaledBitmap(selectedImage, 200, 200, false);
            mImageView.setImageBitmap(selectedImage);
            break;

        case PICK_FROM_GALLERY:
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
            Bitmap bt=Bitmap.createScaledBitmap(bitmap, 200, 200, false);
            mImageView.setImageBitmap(bt);
        break;
       }
}

protected void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    saveState();
}

@Override
protected void onPause()
{
    super.onPause();
    saveState();
}

@Override
protected void onResume()
{
    super.onResume();
    populateFields();
}

private void saveState() 
{
    String name = (String) nameEdit.getText().toString();
    String category = (String) categoryEdit.getText().toString();
    String expired_date = (String) expired_Date_Btn.getText().toString();
    byte[] image = ConvertDrawableToByteArray(mImageView.getDrawable());
    if(mRowId == null)
    {
        long id = mDbHelper.insertItem(category, name, expired_date, image);

        if(id>0)
        {
            mRowId = id;
        }           
    }
    else 
    {
        mDbHelper.updateItem(mRowId, category, name, expired_date, image);
    }   
}

public static byte[] ConvertDrawableToByteArray(Drawable drawableResource) {
    Bitmap imageBitmap = ((BitmapDrawable) drawableResource).getBitmap();
    ByteArrayOutputStream imageByteStream = new ByteArrayOutputStream();
    imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, imageByteStream);
    byte[] imageByteData = imageByteStream.toByteArray();
    return imageByteData;
}

2 个答案:

答案 0 :(得分:1)

可以从OnActivityResult方法中的data.getData()获取图像文件的位置。您可以将位置保存为Sqlite中的字符串。然后使用

 imageView.setImageBitmap(BitmapFactory.decodeFile(filename) 

显示图像。

默认位置是您的app文件夹。如果要存储在其他位置,请按照以下代码

传递位置
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

有关详细信息,请参阅 - http://developer.android.com/guide/topics/media/camera.html

答案 1 :(得分:0)

选中Get the URI of Captured image

选中Inserting image to DB as BLOB and Retrieve it back and display.

它包括来自服务器的下载图像并插入到数据库中,只需根据您的要求进行更改。