简体   繁体   English

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

[英]Need a image selecting code from camera and gallery - working for all android phones

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);
        }
    }
}

This code is working on smasung or sony but not on intex and some other android devices. 此代码适用于smasung或sony,但不适用于intex和其他一些Android设备。 And if I add croping in this code it crashes in sony also... 如果我在此代码中添加裁剪,它也会在sony中崩溃...

Any solution for this issue? 解决这个问题的任何方法?

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);
                }
            }

The above solution is perfect to open the gallery on phone, but it will crash when user selects an Image because it does not have a 以上解决方案非常适合在手机上打开图库,但是当用户选择图像时它会崩溃,因为它没有

startActivityForResult(intent, Pick_Image);

The following code is just for picking image from gallery 以下代码仅用于从图库中选取图像

Button uploadImage;
private static final int SELECT_PICTURE = 1;
private static final int RESULT_OK = 50;
uploadImage = (Button) view.findViewById(R.id.uploadbtn);  //just for reference

uploadImage.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {

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



@Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SELECT_PICTURE && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
           // Do what you want to do with the image
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Check this: 检查一下:

        // Camera.
        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);

        for (ResolveInfo res : listCam)
        {
            final String packageName = res.activityInfo.packageName;
            final Intent intent = new Intent(captureIntent);

            try
            {
                intent.putExtra(
                        android.provider.MediaStore.EXTRA_OUTPUT,
                        getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                BitmapTools.GetCameraExtraOutput()));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            intent.setPackage(packageName);
            cameraIntents.add(intent);
        }

        // Filesystem.
        final Intent galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

        // Chooser of filesystem options.
        final Intent chooserIntent = Intent.createChooser(galleryIntent, GR(R.string.select));

        // Add the camera options.
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[] {}));
        m_bOnGetBillImage = true;
        startActivityForResult(chooserIntent, REQUEST_SELECT_BILL_IMAGE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM