java - 需要从相机和图库中选择图像的代码 - 适用于所有 Android 手机

标签 java android

private void selectImage() {

    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(
            PostProperty2Activity.this);
    builder.setTitle("Add 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");
                Log.d("File f ", "" + Uri.fromFile(f));
                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);



                Bitmap.CompressFormat.JPEG.toString();

                intent.setType("image/*");

                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {

            File f = new File(Environment.getExternalStorageDirectory()
                    .toString());
            Log.d("File fd ", "" + Uri.fromFile(f));
            Log.d("getactivity f ", "" + f);
            Log.d("flistfile f ", "" + f.listFiles());

            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);
                pdialog.show();

                profileimage.setImageBitmap(bm);

                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Upostr";
                f.delete();

                File wallpaperDirectory = new File(path);
                wallpaperDirectory.mkdirs();
                OutputStream fOut = null;
                File file = new File(wallpaperDirectory,
                        String.valueOf(System.currentTimeMillis()) + ".jpg");
                imagepath = file.getAbsolutePath();

                try {
                    fOut = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                    fOut.flush();
                    fOut.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();

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

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

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

            imagevalue = "image";
            uploadImageToServer();
            // upload(imagepath);
        } else if (requestCode == SELECT_FILE) {

            Uri selectedImageUri = data.getData();

            Log.d("uri", "" + selectedImageUri);

            String tempPath = getPath(selectedImageUri);
            Bitmap bm;
            BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
            bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
            pdialog.show();
            profileimage.setImageBitmap(bm);

            imagepath = getRealPathFromURI(selectedImageUri);
            imagevalue = "image";
            uploadImageToServer();
            // upload(imagepath);
        }
    }
}

此代码适用于 smasung 或 sony,但不适用于 intex 和其他一些 android 设备。如果我在此代码中添加裁剪,它也会在索尼中崩溃......

这个问题有什么解决方案吗?

最佳答案

if (options[item].equals("Choose from Gallery")) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                    Intent photoPickerIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    photoPickerIntent.setType("image/*");
                    photoPickerIntent.addCategory(photoPickerIntent.CATEGORY_OPENABLE);
                    startActivityForResult(photoPickerIntent, 2);
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                } else {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    img_path = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString();
                    startActivityForResult(intent, 2);
                }
            }

关于java - 需要从相机和图库中选择图像的代码 - 适用于所有 Android 手机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34304382/

相关文章:

java - 环境变量在 websocket 中不可用

java - 框架如何调用 javabean 上的 get 和 set 方法?

java - 无法使用 SimpleDateFormat 解析德语星期几缩写

android - radio 组对象在哪里

android - genymotion 模拟器上的致命信号 11 (SIGSEGV) 代码=2 不使用 NDK

java - 读取 excel 文件时出错

java - 使用 Testng xml 运行脚本时出现 NullPointerException,但使用 "Running Testng Programatically"运行时脚本工作正常

View 的 Android 拖动/动画

android - ChildEventListener 不一致?

java - 玩游戏服务和 LibGDX : How to sign-in correctly?