从图库中选择位图图像,然后在按钮上单击保存到Sd卡

时间:2015-01-05 08:30:19

标签: android

对所有人来说,你好非常好。实际上我想从图库中选择一个图像然后我想将所选图像保存在Android设备中可用的Sdcard中。

2 个答案:

答案 0 :(得分:0)

使用以下代码,您可以从图库中选取图像

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

之后,将通过onActivityResult()方法

返回拾取的图像
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE && data != null && data.getData() != null) {
        Uri _uri = data.getData();
        Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
        cursor.moveToFirst();

        //Get the image file path
        final String imageFilePath = cursor.getString(0);
        cursor.close();

        //save it the sdcard
        saveToSDCard(imageFilePath);
    }
    super.onActivityResult(requestCode, resultCode, data);
}

答案 1 :(得分:0)

从Sd卡中挑选图片:

Intent mediaChooser = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            // comma-separated MIME types
            mediaChooser.setType("image/*");
            startActivityForResult(mediaChooser, RESULT_LOAD_WATER_IMAGE);

和活动结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case 0:

        if (resultCode == RESULT_OK) {


            String path;

            path = getRealPathFromURI(data.getData());


        }
        break;


}

getRealPathFromURI的实现:

public String getRealPathFromURI(Uri contentUri) {
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } catch (Exception e) {
        return contentUri.getPath();
    }
}

点击后将图像保存到SD卡:

    // TODO Auto-generated method stub
    String root = Environment.getExternalStorageDirectory()
            .toString();
    File myDir = new File(root + "/Your Folder Name");
    myDir.mkdirs();
    String fname = "Your File Name";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try
    {
    FileOutputStream out = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
    }
    catch (Exception e) {
    e.printStackTrace();
    System.out.println("error" + e);
    }