【问题标题】:Android - Image is not showing in ImageView and not save to gallery from cameraAndroid - 图像未显示在 ImageView 中,也未从相机保存到图库
【发布时间】:2018-11-21 06:17:40
【问题描述】:

我尝试从相机获取图像并将其设置为图像视图并保存到图库,图片已成功捕获,但图片未显示到图像视图且未保存到图库。不知道哪里出了问题。

我在这里尝试了很多帖子,但仍然没有解决我的问题。

这是我的代码

定义:

android.support.v7.widget.Toolbar toolbar;
private String id_sales, pilihanUploadPp, imagePath;
private EditText namaEdt, usernameEdt, notelpEdt, emailEdt;
private ProgressDialog progress;
private CompositeDisposable disposables = new CompositeDisposable();
private SessionManager sessionManager;
private int CAMERA_PERM_CODE = 1;
private static final int IMG_REQUEST1 = 100, IMG_REQUEST2 = 200;
private ImageView pp_img;

onCreate 方法:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ubah_profil);

        sessionManager = new SessionManager(this);

        namaEdt = findViewById(R.id.nama_edit_edt);
        usernameEdt = findViewById(R.id.username_edit_edt);
        notelpEdt = findViewById(R.id.telp_edit_edt);
        emailEdt = findViewById(R.id.email_edit_edt);
        pp_img = findViewById( R.id.pp_edit_iv );
        Button ubahBtn = findViewById(R.id.ubah_edit_btn);

        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull( getSupportActionBar() ).setTitle("Ubah Profil");

        ActionBar actionbar = getSupportActionBar();
        assert actionbar != null;
        actionbar.setDisplayHomeAsUpEnabled(true);

        getIntentDataFromFragmentProfil();
        ubahBtn.setOnClickListener(this);
        pp_img.setOnClickListener( this );
    }

onClick 方法:

@Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ubah_edit_btn:
                updateProfil();
            break;
            case R.id.pp_edit_iv:
                selectImage();
            break;
        }
    }

selectImage 方法:

private void selectImage() {
        final CharSequence[] items = {"Kamera", "Galeri", "Batal"};

        AlertDialog.Builder builder = new AlertDialog.Builder( UbahProfilActivity.this );
        builder.setTitle( "Ubah Foto Profil" );
        builder.setItems( items , (dialog , which) -> {
            if (items[which].equals( "Kamera" )){
                pilihanUploadPp = "Kamera";
                if (ContextCompat.checkSelfPermission( UbahProfilActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                    cameraIntent();
                } else {
                    reqCameraPerms();
                }
            }
        } );
        builder.show();
    }

cameraIntent 方法:

private void cameraIntent(){
        Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
        if (intent.resolveActivity( getPackageManager()) != null){
            File photoFile = null;
            try{
                photoFile = createImageFile();
            } catch (IOException ioex){
                Toast.makeText( this , "Error: "+ioex , Toast.LENGTH_SHORT ).show();
            }
            if (photoFile!=null){
                Uri outputFileUri = FileProvider.getUriForFile( this , "com.example.bismillah.newsahabatauto2000.Activity.provider" , photoFile );
                intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
                startActivityForResult( intent, IMG_REQUEST1 );
            }
        }
    }

createImageFile 方法:

private File createImageFile() throws IOException {
        String timeStamp =
                new SimpleDateFormat("yyyyMMdd_HHmmss",
                        Locale.getDefault()).format(new Date());
        String imageFileName = "IMG_" + timeStamp + "_";
        File storageDir =
                getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        imagePath = image.getAbsolutePath();
        return image;
    }

最后是 onActivityResult 方法:

@Override
    protected void onActivityResult(int requestCode , int resultCode , Intent data) {
        super.onActivityResult( requestCode , resultCode , data );
        try{
            if (requestCode==IMG_REQUEST1 && resultCode==RESULT_OK){
                if (data !=null && data.getExtras() !=null){
                    Bitmap imageBitmap = (Bitmap) data.getExtras().get( "data" );
                    pp_img.setImageBitmap( imageBitmap );
                }
            }
        }catch (Exception e){
            Toast.makeText( this , "Error: "+e , Toast.LENGTH_SHORT ).show();
        }
    }

【问题讨论】:

  • 怎么知道图片是成功抓拍的?
  • 当我点击“pp_img”时设备正在进入相机模式,然后我确实捕捉到了图片。但是当恢复活动时,图像视图仍然没有图片,我的画廊也仍然没有图片@Ümañgßürmån
  • 请在 onActivityResult 添加一个断点并检查你在 data 中得到了什么
  • description of ACTION_IMAGE_CAPTURE 声明当您指定 EXTRA_OUTPUT 时,您将放弃 (Bitmap) data.getExtras().get( "data" )。请注意,如果 EXTRA_OUTPUT 不存在,则在额外字段中将小尺寸图像作为 Bitmap 对象返回。这对于只需要小图像的应用程序很有用。如果 pp_img 不是很小,那么这个位图的质量就不够了,你需要从磁盘加载图像。

标签: android imageview android-gallery android-camera-intent


【解决方案1】:

试试这段代码,它非常适合我,

private final static int CAMERA = 0, GALLERY = 1;

private static final int REQUEST_PERMISSIONS_EXTERNAL_STORAGE = 1;
private Uri selectedImage = null

私人无效 onClickUploadPicture() { requestAppPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_PERMISSIONS_EXTERNAL_STORAGE,新的 setPermissionListener() { @覆盖 公共无效 onPermissionGranted(int requestCode) { 新 ImagePicker(CreateBusinessAccountActivity.this, 新 ImagePicker.onItemClick() { @覆盖 公共无效 onCameraClicked() { 显示相机(); }

                        @Override
                        public void onGalleryClicked() {
                            Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(pickPhoto, GALLERY);
                        }
                    }).show();
                }

                @Override
                public void onPermissionDenied(int requestCode) {
                    showSnackBar(toolbar, getString(R.string.please_grant_permission), Snackbar.LENGTH_INDEFINITE,
                            getString(R.string.settings), () -> {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                                startActivity(intent);
                            });
                }
            });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case CAMERA:
            if (resultCode == RESULT_OK) {
                Log.e(TAG, String.valueOf(selectedImage));

                glideUtils.loadCircleImageFromLocal("file://" + selectedImage, mBinding.companyLogo.ivUserImage);
                userData.setProfileOrLogoUri(selectedImage);
                mBinding.companyLogo.ivFlag.setVisibility(View.VISIBLE);
                mBinding.companyLogo.ivFlag.setImageResource(R.drawable.ic_selected_check_with_green_circle);
                mBinding.companyLogo.tvFullName.setText(getResources().getString(R.string.update_profile_pic));
            }
            break;
        case GALLERY:
            if (resultCode == RESULT_OK) {
                assert data != null;
                selectedImage = data.getData();
                assert selectedImage != null;
                Log.e(TAG, selectedImage.toString());

                glideUtils.loadCircleImageFromLocal(new File(getRealPathFromURI(CreateBusinessAccountActivity.this, selectedImage)).getAbsolutePath(), mBinding.companyLogo.ivUserImage);
                userData.setProfileOrLogoUri(Uri.parse(getRealPathFromURI(CreateBusinessAccountActivity.this, selectedImage)));
                mBinding.companyLogo.ivFlag.setVisibility(View.VISIBLE);
                mBinding.companyLogo.ivFlag.setImageResource(R.drawable.ic_selected_check_with_green_circle);
                mBinding.companyLogo.tvFullName.setText(getResources().getString(R.string.update_profile_pic));
            }
            break;


}

【讨论】:

    【解决方案2】:

    我使用Image Cropper 进行捕获,或者从手机添加图像,并对其进行裁剪, 并为我保存这个作品:

    File file = null;
    
    
            String taskFolderPath = Environment.getExternalStorageDirectory().toString() + "/DCIM/myPhotos/" + sID[0] + sID[1];
    
            String sType = "";
            if (type == 1) {
                String time = String.valueOf(cal.get(Calendar.MINUTE)) + String.valueOf(cal.get(Calendar.SECOND));
    
                sType = "start-" + sID[0] + sID[1] + time;  //sID is a String table
                file = new File(taskFolderPath, sType + ".jpg");
    
    
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
    
                OutputStream stream = null;
                stream = new FileOutputStream(file);
    
                bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream); //0 - min, 100 - max quality, true if success
                stream.flush();
                stream.close();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多