拍摄照片,将其保存在app drawables中并将其显示在ImageButton中

时间:2012-11-20 22:46:06

标签: android android-activity camera

我有一个带有ImageButton的Android应用。当用户点击它时,意图启动以显示相机活动。当用户捕获图像时,我想将其保存在应用程序的可绘制文件夹中,并将其显示在用户单击的相同ImageButton中,替换以前的可绘制图像。我使用了此处发布的活动:Capture Image from Camera and Display in Activity

...但是当我捕获图像时,活动不会返回包含ImageButton的活动。

编辑代码是:

public void manage_shop()
{
    static final int CAMERA_REQUEST = 1888;

    [...]
    ImageView photo = (ImageView)findViewById(R.id.getimg);
    photo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
            startActivityForResult(camera, CAMERA_REQUEST); 
        }
    }); 
   [...]
}

onActivityResult():

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
  ImageButton getimage = (ImageButton)findViewById(R.id.getimg);

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
    {  
        Bitmap getphoto = (Bitmap) data.getExtras().get("data"); 
        getimage.setImageBitmap(getphoto);
    }
}

如何将拍摄的图像存储在可绘制文件夹中?

2 个答案:

答案 0 :(得分:2)

将图像保存到文件后,您可以使用以下代码段添加到图库。

ContentValues values = new ContentValues(); 
values.put(MediaStore.Images.Media.TITLE, new File(path).toString());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, path);
getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI , values);

将文件保存到目录中执行以下操作

private saveFileToDir() {
    final InputStream in = Wherever you input stream comes from;

    File f = generatePhotoFile();

    OutputStream out = new FileOutputStream(f);
    byte[] buffer = new byte[1024];

    int len;
    while ((len=in.read(buffer))>0)
    {
        out.write(buffer,0,len);
    }

    in.close();
    out.flush();
    out.close();        
}

private File generatePhotoFile() throws IOException {
    Date date = new Date();
    DateFormat df = new SimpleDateFormat("yyyymmdd_hhmmss");

    String newPicFile = "IMG_"+ df.format(date) + ".jpg";

    File f = new File(Environment.getExternalStorageDirectory()+"/DCIM/Camera/", newPicFile);

    if (!f.exists())
    {
        if(!f.getParentFile().exists())
            f.getParentFile().mkdir();

        f.createNewFile();
    }

    return f;
}       

答案 1 :(得分:0)

  

如何将拍摄的图像存储在可绘制文件夹中?

无法动态地将图像保存到可绘制文件夹:

请参阅:

android image save to res/drawable folder

Write to /res/drawable/ on the fly?