Android Studio:如何将外部文件(来自相机的照片)设置为imageview

时间:2017-05-05 23:19:30

标签: java android xml

在确定如何将imageview设置为我刚用相机拍摄的照片时遇到一些麻烦。如果有一些方法可以一次显示多个捕获的图片,那将是一个奖励。每当我点击按钮时,会出现先前捕获的图像,然后相机打开,这是不对的。我喜欢imageview为空白,我点击按钮,拍照,然后该图片显示在imageview中。我相信这条线不合适,但我不确定如何/在哪里移动它。 mimageView.setImageURI(outputFileUri);

public class cameraclass extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);
        final ImageView mimageView;
        mimageView = (ImageView) this.findViewById(R.id.image_from_camera);




        // Here, we are making a folder named picFolder to store
        // pics taken by the camera using this application.
        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();

        Button capture = (Button) findViewById(R.id.take_image_from_camera);
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Here, the counter will be incremented each time, and the
                // picture taken by camera will be stored as 1.jpg,2.jpg
                // and likewise.
                count++;
                String file = dir+count+".jpg";
                File newfile = new File(file);
                try {
                    newfile.createNewFile();
                }
                catch (IOException e)
                {
                }

                //Uri outputFileUri = Uri.fromFile(newfile);
                Uri outputFileUri = FileProvider.getUriForFile(getApplicationContext() , "com.example.android.com220finalapp.provider", newfile);

                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
                mimageView.setImageURI(outputFileUri);

            }
        });
    }

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

        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");

        }
    }
}

1 个答案:

答案 0 :(得分:1)

  

我认为这条线不合适,但我不确定如何/在哪里移动它。

startActivityForResult()是异步的。该方法返回时,您的照片将不会被拍摄。如果您收到ImageView响应,则需要将图片加载到onActivityResult()中的RESULT_OK

然而,虽然setImageURI()可能有用,但它从来都不是一个特别好的主意,因为它会在加载照片时暂停你的应用一段时间。有许多image loading libraries for Android会处理异步加载ImageView