繁体   English   中英

从图库和相机中获取图像(Android Studio)

[英]Getting an image from gallery and camera (Android Studio)

我正在一个项目中,用户可以通过拍照或从“图库”中选择图像来更改其个人资料图片。 尽管遵循了多个教程,但他们使用的代码对我不起作用。 每当我在Dialog Box上选择“相机”时,它会依次转到“图库”和“相机”。 同样,当我在对话框上选择“图库”时,它会转到“图库”,但仍会转到“ Camera然后再在“ Image View上显示图像。 是因为我使用的是Android Lollipop吗? 我也不太确定。

如何解决此问题?

package com.example.user.imagestuff;    
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
     String[] Items;
     ImageView mImageView;
     Button mButton;
     final int bmpHeight = 160;
     final int bmpWidth = 160;
     static final int CAMERA_CODE = 1;
     static final int GALLERY_CODE = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mImageView = (ImageView) findViewById(R.id.mImageView);
    mButton = (Button) findViewById(R.id.mButton);
    Items = getResources().getStringArray(R.array.DialogItems);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageOnClick(v);
        }
    });
}

public void ImageOnClick(View v) {
    Log.i("OnClick","True");
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle(R.string.AlertTitle);
    builder.setItems(Items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            for(int i=0; i < Items.length; i++){
                if (Items[i].equals("Camera")){
                    Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if(CameraIntent.resolveActivity(getPackageManager()) != null){
                        startActivityForResult(CameraIntent, CAMERA_CODE);
                    }

                }else if (Items[i].equals("Gallery")){
                    Log.i("GalleryCode",""+GALLERY_CODE);
                    Intent GalleryIntent = null;
                    GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    GalleryIntent.setType("image/*");
                    GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(GalleryIntent,GALLERY_CODE);
                }
            }
        }
    });
    builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK){
        switch(requestCode){
            case 1:
                Log.i("CameraCode",""+CAMERA_CODE);
                Bundle bundle = data.getExtras();
                Bitmap bmp = (Bitmap) bundle.get("data");
                Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
                mImageView.setImageBitmap(resized);

            case 0:
                Log.i("GalleryCode",""+requestCode);
                Uri ImageURI = data.getData();
                mImageView.setImageURI(ImageURI);
        }


    }
}

}

您在for循环中打开了一个意图,还有另一个错误是您没有在开关外壳中破坏外壳。 在您的开关盒中使用break

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK){
        switch(requestCode){
            case 1:
                Log.i("CameraCode",""+CAMERA_CODE);
                Bundle bundle = data.getExtras();
                Bitmap bmp = (Bitmap) bundle.get("data");
                Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
                mImageView.setImageBitmap(resized);
                break;

            case 0:
                Log.i("GalleryCode",""+requestCode);
                Uri ImageURI = data.getData();
                mImageView.setImageURI(ImageURI);
                break;
        }


    }

因为您正在使用for循环来检查Camera和Gallary字符串。 You need to remove for loop并尝试使用下面的代码

而且,您在swith情况下缺少break

final CharSequence[] items = {"Camera", "Gallery"}


                if (items[item].equals("Camera")){
                    Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if(CameraIntent.resolveActivity(getPackageManager()) != null){
                        startActivityForResult(CameraIntent, CAMERA_CODE);
                    }

                }else if (items[item].equals("Gallery")){
                    Log.i("GalleryCode",""+GALLERY_CODE);
                    Intent GalleryIntent = null;
                    GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    GalleryIntent.setType("image/*");
                    GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(GalleryIntent,GALLERY_CODE);
                }

第二选择

您也可以break; 条件匹配时用于中断for循环的关键字

请替换您的代码

public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        for(int i=0; i < Items.length; i++){
            if (Items[i].equals("Camera")){
                Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                if(CameraIntent.resolveActivity(getPackageManager()) != null){
                    startActivityForResult(CameraIntent, CAMERA_CODE);
                }

            }else if (Items[i].equals("Gallery")){
                Log.i("GalleryCode",""+GALLERY_CODE);
                Intent GalleryIntent = null;
                GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                GalleryIntent.setType("image/*");
                GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(GalleryIntent,GALLERY_CODE);
            }
        }
    }
});
builder.show();
}

public void ImageOnClick(View v) {
    Log.i("OnClick","True");
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle(R.string.AlertTitle);
    builder.setItems(Items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (Items[which].equals("Camera")){
                Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                if(CameraIntent.resolveActivity(getPackageManager()) != null){
                    startActivityForResult(CameraIntent, CAMERA_CODE);
                }

            }else if (Items[which].equals("Gallery")){
                Log.i("GalleryCode",""+GALLERY_CODE);
                Intent GalleryIntent = null;
                GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                GalleryIntent.setType("image/*");
                GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(GalleryIntent,GALLERY_CODE);
            }
        }
    });
    builder.show();
}

您没有使用break语句,这就是为什么将其移至下一条语句。 在激发意图时只使用break语句

public void ImageOnClick (View v){
        Log.i("OnClick", "True");
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.AlertTitle);
        builder.setItems(Items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for (int i = 0; i < Items.length; i++) {
                    if (Items[i].equals("Camera")) {
                        Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        if (CameraIntent.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(CameraIntent, CAMERA_CODE);
                        }
                        break;

                    } else if (Items[i].equals("Gallery")) {
                        Log.i("GalleryCode", "" + GALLERY_CODE);
                        Intent GalleryIntent = null;
                        GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        GalleryIntent.setType("image/*");
                        GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(GalleryIntent, GALLERY_CODE);
                    }
                    break;
                }
            }
        });
        builder.show();
    }

为了有效使用位置值,当您设置onclickListener时,它返回一个int变量,该变量是被单击列表的位置。 您的情况是int which因此您可以简单地使用

 public void ImageOnClick (View v){
            Log.i("OnClick", "True");
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle(R.string.AlertTitle);
            builder.setItems(Items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                        if (Items[which].equals("Camera")) {
                            Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            if (CameraIntent.resolveActivity(getPackageManager()) != null) {
                                startActivityForResult(CameraIntent, CAMERA_CODE);
                            }
                            break;

                        } else if (Items[which].equals("Gallery")) {
                            Log.i("GalleryCode", "" + GALLERY_CODE);
                            Intent GalleryIntent = null;
                            GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            GalleryIntent.setType("image/*");
                            GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(GalleryIntent, GALLERY_CODE);
                        }
                        break;

                }
            });
            builder.show();
        }

同样在OnActivityResult方法中使用break语句,否则会两种情况

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case 1:
                Log.i("CameraCode", "" + CAMERA_CODE);
                Bundle bundle = data.getExtras();
                Bitmap bmp = (Bitmap) bundle.get("data");
                Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth, bmpHeight, true);
                mImageView.setImageBitmap(resized);
                break;
            case 0:
                Log.i("GalleryCode", "" + requestCode);
                Uri ImageURI = data.getData();
                mImageView.setImageURI(ImageURI);
                break;
        }


    }
}

这对我来说很好。

public static final int CAMERA_PERMISSION =100;
public static final int REQUEST_IMAGE_CAPTURE =101;
public static final int READ_STORAGE_PERMISSION =102;
public static final int REQUEST_IMAGE_PICK =103 ;
private Dialog mCameraDialog;
private Uri mImageURI;

/**
 * Method to show list dialog to choose photo form gallery or camera.
 */
private void showChoosePhotoDialog() {
    mCameraDialog.setContentView(R.layout.dialog_choose_photo);
    if(mCameraDialog.getWindow()!=null)
        mCameraDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    mCameraDialog.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCameraDialog.dismiss();
            onCameraOptionSelected();
        }
    });
    mCameraDialog.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCameraDialog.dismiss();
            onGalleryOptionSelected();
        }
    });
    mCameraDialog.show();
}

/**
 * Method to open gallery.
 */
private void onGalleryOptionSelected() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intentGallery, REQUEST_IMAGE_PICK);
        overridePendingTransition(R.anim.push_left_right, R.anim.push_right_left);
    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                READ_STORAGE_PERMISSION);
    }
}

/**
 * Method to open chooser.
 */
private void onCameraOptionSelected() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                        CAMERA_PERMISSION);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION);
            }
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    CAMERA_PERMISSION);

        } else {
            mImageURI = Uri.parse(AppUtils.getFilename());
            startActivityForResult(AppUtils.getCameraChooserIntent(EditProfileActivity.this, mImageURI + ""),
                    REQUEST_IMAGE_CAPTURE);
        }
    } else {
        mImageURI = Uri.parse(AppUtils.getFilename());
        startActivityForResult(AppUtils.getCameraChooserIntent(this, mImageURI + ""),
                REQUEST_IMAGE_CAPTURE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case CAMERA_PERMISSION:
            int j = 0;
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED)
                    j = 1;
            }
            if (j == 1) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) || (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.CAMERA))) {
                    //           Toast.makeText(this, R.string.s_camera_permission, Toast.LENGTH_SHORT).show();
                } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) || !ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.CAMERA)) {
                    // Open phone settings page. 
                    //         Toast.makeText(this, getString(R.string.s_app_needs_camera_permission), Toast.LENGTH_SHORT).show();
                }
            } else
                onCameraOptionSelected();
            break;

        case READ_STORAGE_PERMISSION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                onGalleryOptionSelected();
            else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                //             Toast.makeText(this, getString(R.string.s_storage_permission), Toast.LENGTH_SHORT).show();
            } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                 // Open Phone Settings   
            }
    }
}

暂无
暂无

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

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