第二次从相机拍摄时无法加载图像

Posted

技术标签:

【中文标题】第二次从相机拍摄时无法加载图像【英文标题】:Not able to load image when captured from Camera second time 【发布时间】:2016-04-18 18:36:06 【问题描述】:

我一直在使用 Camera Intent 来捕捉图像。这是它第一次完美运行,我能够捕获图像并在 ImageView 中显示。但是当我第二次尝试捕捉不同的图像时,它仍然显示相同的旧图像。

这是我的 Camera Intent 和 onActivityResult() 代码

       Uri selectedImage;
        private Uri imageUri;


         private void activeTakePhoto() 

                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photo));
                            imageUri = Uri.fromFile(photo);
                            startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
                        


      @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) 
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) 
                case RESULT_LOAD_IMAGE:
                    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) 
                        selectedImage = data.getData();
                        imageView.setImageURI(selectedImage);
                    

                    break;

                case REQUEST_IMAGE_CAPTURE:
                    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) 
                        try 
                            selectedImage = imageUri;
                            getContentResolver().notifyChange(selectedImage, null);
                            imageView.setImageURI(imageUri);
                         catch (Exception e) 
                            Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                                    .show();
                            Log.e("Camera", e.toString());
                        
                        Log.e("A", "AAA");
                    
            
        


   submit.setOnClickListener(new View.OnClickListener()  // back to Activity A listView
            @Override
            public void onClick(View v) 
                Intent returnIntent = new Intent();
                amount = Amount.getText().toString();
                description = Description.getText().toString();
                type = spinnerType.getSelectedItem().toString();
                returnIntent.putExtra("type", type);
                returnIntent.putExtra("description", description);
                returnIntent.putExtra("amount", amount);
                if(selectedImage!=null) 
                    returnIntent.putExtra("img_uri", selectedImage.toString());
                
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            
        );

活动 A

 listview.setOnItemClickListener(new AdapterView.OnItemClickListener()  // if listView is clicked
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id)  // if list is clicked
                mClickedPosition = position;
                Object o = listview.getItemAtPosition(position);
                ImageAndText image = (ImageAndText) o;
                String type = image.getType();
                String amount = image.getAmount();
                String description = image.getDescription();
                Uri photo = image.getImage();
                String[] type1 = type.split(":");
                String[] amount1 = amount.split(":");
                String[] description1 = description.split(":");
                Intent i = new Intent(getApplication(), AddMoreClaims.class);
                i.putExtra("type", type1[1].toString().trim());
                i.putExtra("amount", amount1[1].toString().trim());
                i.putExtra("description", description1[1].toString().trim());
                i.putExtra("photo", photo);
                startActivityForResult(i, PROJECT_REQUEST_CODE);
            
        );

已编辑(添加时间戳)

 private void activeTakePhoto() 
        String filename = "Pic_" + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(photo,filename));
        imageUri = Uri.fromFile(photo,filename);
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    

【问题讨论】:

【参考方案1】:

如果我们查看ImageView 的来源,setImageURI() 方法以if 检查开始,类似于:

public void setImageURI(@Nullable Uri uri) 
    if (mResource != 0 ||
            (mUri != uri &&
             (uri == null || mUri == null || !uri.equals(mUri)))) 

        // Drawable resolution and update code
    

!uri.equals(mUri) 可以看出,如果Uri 传递给已经设置的方法equals()ImageView 将不会自行刷新。您的代码每次都保存到同一个文件中,因此Uris 总是相同的。

只需在调用imageView.setImageURI(imageUri); 之前调用imageView.setImageURI(null);。或者,您可以每次保存到不同的文件;例如,通过在文件名中添加时间戳

【讨论】:

【参考方案2】:

问题可能是 ImageView 不刷新内容。 您应该在更改内容后尝试调用 invalidate 方法。

imageView.setImageURI(imageUri);
imageView.invalidate();

【讨论】:

【参考方案3】:
>To display image which is captured by camera on second time, Simply **update** the first element from database after completing the operation .   

公共类 MainActivity 扩展 AppCompatActivity

private static final int CAMERA_REQUEST = 1;
private static final int GALLERY_IMAGE = 2;
private static final String TAG = "";
Button captureImage;
ImageView imageView;
ImageDatabase database;
Bitmap b,theImage;
MainActivity CameraActivity = null;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CameraActivity = this;

    imageView = (ImageView) findViewById(R.id.image_view);
    database = new ImageDatabase(this);

    //Set OnClick Listener to button view
    captureImage = (Button) findViewById(R.id.capture_image);
    captureImage.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 

            isStoragePermissionGranted();
        
    );

    //long press on image
    imageView.setOnLongClickListener(new View.OnLongClickListener() 
        @Override
        public boolean onLongClick(View v) 
            isStoragePermissionGranted();
            return true;
        
    );


private void startDialog() 
    AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
            CameraActivity);
    myAlertDialog.setTitle("Upload Pictures Option");
    myAlertDialog.setMessage("How do you want to set your picture?");

    myAlertDialog.setPositiveButton("Gallery",
            new DialogInterface.OnClickListener() 
                public void onClick(DialogInterface arg0, int arg1) 
                    Intent i = new Intent();
                    i.setType("image/*");
                    i.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(i.createChooser(i, "Result load Image")
                            , GALLERY_IMAGE);
                
            );

    myAlertDialog.setNegativeButton("Camera",
            new DialogInterface.OnClickListener() 
                public void onClick(DialogInterface arg0, int arg1) 

                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                
            );
    myAlertDialog.show();


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) 
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) 

        theImage = (Bitmap) data.getExtras().get("data");

    

    if (requestCode == GALLERY_IMAGE && resultCode == RESULT_OK) 
        try 
            Uri imageUri = data.getData();
            InputStream imageStream = getContentResolver().openInputStream(imageUri);
            theImage = BitmapFactory.decodeStream(imageStream);

         catch (FileNotFoundException e) 
            e.printStackTrace();
        

    
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        theImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        SQLiteDatabase db = database.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ImageDatabase.KEY_IMG_URL, byteArray);
        db.insert(ImageDatabase.TABLE_NAME, null, values);
        db.update(ImageDatabase.TABLE_NAME, values, null, null);
        db.close();



public void getTheImage() 

    SQLiteDatabase db = database.getReadableDatabase();

    Cursor cursor = (Cursor) db.rawQuery(" SELECT * FROM " + ImageDatabase.TABLE_NAME,
            null, null);
    if (cursor.moveToFirst()) 
        byte[] imgByte = cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY_IMG_URL));
        cursor.close();
        b = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);

    
    if (cursor != null && !cursor.isClosed()) 
        cursor.close();
    
    imageView.setImageBitmap(b);



//Storage permission
public boolean isStoragePermissionGranted() 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) 
            Log.v(TAG, "Permission is granted");
            startDialog();
            return true;
         else 

            Log.v(TAG, "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, 1);
            return false;
        
     else  //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG, "Permission is granted");
        startDialog();
        return true;
    


@Override
protected void onStart() 
    super.onStart();
    getTheImage();

【讨论】:

以上是关于第二次从相机拍摄时无法加载图像的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 第二次加载后 Tableview 无法正确重新加载

Android Lollipop 问题 - 无法将图像从相机加载到 ImageView

Android相机第二次拍摄失败

无法加载资产颤振(不是资产是保存的文件)

相机拍摄的图像不想在 ImageView 中显示

第二次从内部查询中选择