簡體   English   中英

將圖像保存到Android中的SD卡

[英]Save Image to SD Card in android

我是Android的新手,我試圖創建一個應用以拍攝照片或上傳到屏幕(我目前正在使用它),然后通過單擊按鈕將圖像保存到SD卡。 當我按一下保存按鈕時,該應用程序停止工作,我們將不勝感激。 下面是我的代碼

public class Upload extends Fragment {
private Button bt_browse;
private ImageView iv_photo;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String uploadImagePath = "";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.upload,
            container, false);
    bt_browse = (Button) rootView.findViewById(R.id.button1);
    iv_photo = (ImageView) rootView.findViewById(R.id.iv_photo);

    bt_browse.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            selectImage();
        }
    });



    return rootView;

}



private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Select Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment
                        .getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"), SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {
            File f = new File(Environment.getExternalStorageDirectory()
                    .toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bm;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);

                bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                iv_photo.setImageBitmap(bm);
                uploadImagePath = f.getAbsolutePath();

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == SELECT_FILE) {
            Uri selectedImageUri = data.getData();

            String tempPath = getPath(selectedImageUri, getActivity());
            Bitmap bm;
            BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
            bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
            iv_photo.setImageBitmap(bm);
            uploadImagePath = tempPath;

        }
    }
}

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

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

//automatically handle clicks on the Home/Up button, so long

 // as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

OnMenuItemClickListener SaveImageClickListener = new OnMenuItemClickListener() {

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Bitmap bitmap;
        OutputStream output;

        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_camera);

        File filepath = Environment.getExternalStorageDirectory();

        File dir = new File(filepath.getAbsolutePath() + "/Save Image Example");
        dir.mkdirs();

        File file = new File(dir, "myimage.png");


        try {
            output = new FileOutputStream(file);

            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
            output.flush();
            output.close();

        }catch(Exception e) {
            e.printStackTrace();
        }


        return false;
    }
};
}

您是否已對清單文件獲得WRITE_EXTERNAL_STORAGE權限? 如果沒有,請添加

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM