java - 从图库 Android 应用中拍照时 ImageView 不显示图像

标签 java android imageview

我的 Android 应用程序中的 ImageView 存在一些问题,我想在从相机拍照或从图库获取图像后将图像裁剪为圆形。当我从相机拍照时,该功能通常是正常的,但如果我从图库中获取图像,我会收到一些错误,但未在 logcat 中显示。

这是我的代码:

此代码用于调用选项菜单来拍照或从图库中获取:

private void selectImage() {
    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
    AlertDialog.Builder builder = new AlertDialog.Builder(ActivityRegister.this);
    builder.setTitle("Add Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo")) {
                //define the file-name to save photo taken by Camera activity
                String fileName = "new-photo-name.jpg";
                //create parameters for Intent with filename
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, fileName);
                values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
                //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                //create new Intent
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", -1);
                intent.putExtra("aspectY", -1);
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 200);

                startActivityForResult(intent, PICK_Camera_IMAGE);
            }else if (options[item].equals("Choose from Gallery")){
                try{
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    intent.putExtra("crop", "true");
                    intent.putExtra("aspectX", -1);
                    intent.putExtra("aspectY", -1);
                    intent.putExtra("outputX", 200);
                    intent.putExtra("outputY", 200);
                    intent.putExtra("return-data", true);

                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
                }catch (Exception e){
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
                }
            }else if (options[item].equals("Cancel")){
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

裁剪以使图像变圆:

public Bitmap getCroppedBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    Bitmap _bmp = Bitmap.createScaledBitmap(output, 300, 300, false);
    return _bmp;
}

此代码用于解码相机或图库中的图像

public void decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);
    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;
    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    ivImages.setImageBitmap(getCroppedBitmap(bitmap));
}

这是我的 onActivityResult() 代码:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri selectedImageUri = null;
    String filePath = null;
    switch (requestCode) {
        case PICK_IMAGE:
            if (resultCode == Activity.RESULT_OK) {
                Bundle extra = data.getExtras();
                if(extra != null) {
                    selectedImageUri = data.getData();
                }
            }
            break;
        case PICK_Camera_IMAGE:
            if (resultCode == RESULT_OK) {
                //use imageUri here to access the image
                selectedImageUri = imageUri;
                /*
                Bitmap mPic = (Bitmap) data.getExtras().get("data");
                selectedImageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mPic, getResources().getString(R.string.app_name), Long.toString(System.currentTimeMillis())));
                */
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
            }
            break;
    }

    if(selectedImageUri != null){
        try {
            // OI FILE Manager
            String filemanagerstring = selectedImageUri.getPath();
            // MEDIA GALLERY
            String selectedImagePath = getPath(selectedImageUri);
            if (selectedImagePath != null) {
                filePath = selectedImagePath;
            } else if (filemanagerstring != null) {
                filePath = filemanagerstring;
            } else {
                Toast.makeText(getApplicationContext(), "Unknown path", Toast.LENGTH_LONG).show();
                Log.e("Bitmap", "Unknown path");
            }

            if (filePath != null) {
                decodeFile(filePath);
            } else {
                bitmap = null;
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Internal error", Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
    }
}

抱歉我的英语不好

最佳答案

我也遇到了同样的问题。要获得图像,请这样做。这对我有用

如果您尝试将 imageView 设置为所选图像,则代码如下所示。

Activity 类别

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

    if ( resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();





        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
        } catch (IOException e) {
            e.printStackTrace();
        }

         Bitmap resized = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
              imageView.setImageBitmap(ProfilePicture.getRoundedRectBitmap(resized));



    }


}

图像转换器类

public class ProfilePicture {
    public static Bitmap getRoundedRectBitmap() {
        Bitmap result = null;
        try {
            result = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(result);

            int color = 0xff424242;
            Paint paint = new Paint();
            Rect rect = new Rect(0, 0, 200, 200);

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawCircle(50, 50, 50, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
   canvas.drawBitmap(bitmap, rect, rect, paint);



        } catch (NullPointerException e) {
        } catch (OutOfMemoryError o) {
        }
        return result;
    }

此行 MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage); 可帮助您在 ContentResolver 的帮助下从图库中获取选定的图像。

我希望这对您有帮助。特纳克尤

关于java - 从图库 Android 应用中拍照时 ImageView 不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36195392/

相关文章:

android - ImageView限制拖放和缩小屏幕

java - 我尝试编写自己的 makefile,但它不起作用

Java在HashSet中HashMap的存储和查找

java - Android 中的 HTML 请求

Android Geofence api 与插入设备的主动轮询

android - Imageview 在屏幕边缘缩小

java - 无法设置ImagView的图像

java - 如何使用自定义布局创建对话框弹出窗口?

android - 签名的应用程序崩溃和未签名的 apk 运行

java - 从html中获取原始文本