Android使用相机拍摄多张照片

4
我已经编写了一段代码,可以使用设备内置相机捕获图像并将其存档在数据库服务器中。每次捕获并查看图像时,都会动态创建另一个 ImageView 布局(例如,图像为 ic_launcher)。
当点击 ic_launcher 图像时,它将通过 intent 转到 MainActivity.java 页面,以拍摄另一张图像。
我的问题是,如何在 uploadActivity.java 中查看所有捕获的图像/存档图像?
注意:图像在 uploadactivity.java 中查看。
 private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}



/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            launchUploadActivity(true);


        } else if (resultCode == RESULT_CANCELED) {

            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    }
}

private void launchUploadActivity(boolean isImage){
    Intent i = new Intent(MainActivity.this, UploadActivity.class);
    i.putExtra("filePath", fileUri.getPath());
    i.putExtra("isImage", isImage);
    startActivity(i);
}

/**
 * ------------ Helper Methods ---------------------- 
 * */


public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}


private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                  .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");


    return mediaFile;
}

UploadActivity.java

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    txtPercentage = (TextView) findViewById(R.id.txtPercentage);
    btnUpload = (Button) findViewById(R.id.btnUpload);      
    Button  btnTaking = (Button)findViewById(R.id.btntake);
    layout2 = (LinearLayout) findViewById(R.id.ly2);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    vidPreview = (VideoView) findViewById(R.id.videoPreview);


    // Changing action bar background color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor(getResources().getString(
                    R.color.action_bar))));

    // Receiving the data from previous activity
    Intent intent = getIntent();

    // image or video path that is captured in previous activity
    filePath = intent.getStringExtra("filePath");


    ArrayList<String> yourFilePaths = new ArrayList<>();// Create ArrayList

    // first you have to check if you've saved filepaths
    SharedPreferences prefs = getSharedPreferences("SavedFilePaths",
            Context.MODE_PRIVATE);
    String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
            "");
    if (!myJSONArrayString.isEmpty()) {
        JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray(myJSONArrayString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                yourFilePaths.add(jsonArray.get(i).toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    // add the last photo you've taken
    yourFilePaths.add(filePath);
    // Save the new ArrayList in SharedPreferences:
    JSONArray mJSONArray = new JSONArray(yourFilePaths);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("SavedFilePathsJSONArray", mJSONArray.toString());

    // Show images by filePaths
    File imgFile;
    for (int i = 0; i < yourFilePaths.size(); ++i) {
        imgFile = new File(yourFilePaths.get(i));
        if (imgFile.exists()) {
              final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 8;

               Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);

            ImageView myImage = new ImageView(this);

            myImage.setImageBitmap(myBitmap);// In this step you've to
                                                // create dynamic imageViews
                                                // to see more than one
                                                // picture
            layout2.addView(myImage);// Then add your dynamic imageviews to
                                    // your layout

        }
    }

    btnTaking.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        Intent intent = new Intent(UploadActivity.this, MainActivity.class);
        startActivity(intent);
        }
    });

    btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server
            new UploadFileToServer().execute();
        }
    });

}

Activity_Upload

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/view_background"
android:orientation="vertical"
android:padding="10dp" >

<!-- To display picture taken -->


<LinearLayout
    android:id="@+id/ly2"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:orientation="vertical" >

</LinearLayout>

<TextView
    android:id="@+id/txtPercentage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="15dp"
    android:layout_marginTop="15dp"
    android:textColor="@color/txt_font"
    android:textSize="30dp" />

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="20dp"
    android:layout_marginBottom="35dp"
    android:visibility="gone" />

<Button
    android:id="@+id/btnUpload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:background="@color/btn_bg"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="@string/btnUploadToServer"
    android:textColor="@color/white"
    android:visibility="gone"
     />
<TextView 
    android:id="@+id/idt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    />

<Button
    android:id="@+id/btntake"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:background="@color/btn_bg"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Take Another Picture"
    android:textColor="@color/white" />

输出

在此输入图像描述

注意: 我从androidhive获取了这段代码。


所以你想在MaintActivity中查看UploadActivity拍摄的图片? - Fabio Venturi Pastor
实际上,MainActivity 只是用于访问相机以拍摄图像。UploadActivity 用于查看所有图像并上传。如果我想再拍一张照片,我会点击 ImageView(使用 Intent)返回 MainActivity 进行拍摄。在 uploadactivity.java 中,我只能查看一个图像。那么,我该如何查看我拍摄的所有图像呢?谢谢 @FabioVenturiPastor - arvin
请拍摄3张照片,然后在 String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray", ""); 后执行 System.out.println(myJSONArrayString);,并在 yourFilePaths.add(filePath); 后执行 for (int j = 0; j < images.size(); ++j) { System.out.println(yourFilePaths.get(i)); },告诉我你得到了什么。 - Fabio Venturi Pastor
System.out.println(yourFilePaths.get(i)); 的结果是 "/storage/.../imagename.jpg"。但是 System.out.println(myJSONArrayString); 没有结果。我已经拍了3张照片,它显示了不同的图像名称结果。 - arvin
好的,现在我在工作中,回家后我会在我的电脑上尝试你的代码,并向你展示结果。 - Fabio Venturi Pastor
1个回答

3

现在我认为我理解了您的问题。

要理解我的代码,请查看:

什么是sharedPreferences?

如何在Android中从文件路径中显示ImageView?

在循环内动态创建ImageViews

最后编辑: 添加commit()解决问题

我们将尝试将文件路径保存在ArrayList中,并将此数组保存在SharedPreferences中:

layout_example.xml <-- 在您的xml上创建一个布局以添加imageView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:padding="5dp">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/myLinearLayout"></LinearLayout>
</RelativeLayout>

UploadActivity.java

     Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);//add the LinearLayout of the layout_example.xml

    txtPercentage = (TextView) findViewById(R.id.txtPercentage);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    layout = (LinearLayout) findViewById(R.id.ly1);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    imgPreview = (ImageView) findViewById(R.id.imgPreview);

    addImageView(layout);

    // Changing action bar background color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor(getResources().getString(
                    R.color.action_bar))));

    // Receiving the data from previous activity
    Intent i = getIntent();

    // image or video path that is captured in previous activity
    filePath = i.getStringExtra("filePath");

   LinearLayour ly_myLayout = (LinearLayout)findViewById(R.id.myLinearLayout);
   ArrayList<String> yourFilePaths = new ArrayList<>();//Create ArrayList

    //first you have to check if you've saved filepaths
    SharedPreferences prefs = getSharedPreferences("SavedFilePaths",   Context.MODE_PRIVATE);
    String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray", "");
    if(!myJSONArrayString.isEmpty()){
    JSONArray jsonArray = new JSONArray(myJSONArrayString);
      for (int i=0;i<jsonArray.length();i++){ 
        yourFilePaths.add(jsonArray.get(i).toString());
       } 
    }
    //add the last photo you've taken
     yourFilePaths.add(filePath);

    //Save the new ArrayList in SharedPreferences:
     JSONArray mJSONArray = new JSONArray(yourFilePaths);
     SharedPreferences.Editor editor = prefs.edit();
     editor.putString("SavedFilePathsJSONArray",mJSONArray.toString()).commit(); // add commit

    //Show images by filePaths             
    File imgFile;
      for (int i = 0; i < yourFilePaths.size(); ++i) {
        imgFile = new  File(yourFilePaths.get(i));
        if(imgFile.exists()){

        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

        ImageView myImage = new ImageView(this);

        myImage.setImageBitmap(myBitmap);// In this step you've to create dynamic imageViews to see more than one picture

        ly_myLayout.addView(myImage);//Then add your dynamic imageviews to your layout

        }
      }

    btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server
            new UploadFileToServer().execute();
        }
    });

}

/**
 * Displaying captured image/video on the screen
 * */
private void previewMedia(boolean isImage) {
    // Checking whether captured media is image or video
    if (isImage) {
        imgPreview.setVisibility(View.VISIBLE);
        vidPreview.setVisibility(View.GONE);
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // down sizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        imgPreview.setImageBitmap(bitmap);

    } 
}

    private void addImageView(LinearLayout layout) {
    i = 0;
    ImageView imageView = new ImageView(this);
    imageView.setImageResource(R.drawable.ic_launcher);
    imageView.setId(i);
    layout.addView(imageView);
    imageView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(UploadActivity.this,
                    MainActivity.class);
            startActivity(intent);
        }
    });
}

在此输入图片描述 解决了您的问题吗?


抱歉,我还是新手。但我认为“yourfilepath.length()”对于ArrayList来说是未定义的。我尝试使用“yourfilepath.size()”,但仍然无法工作。我已经捕获了大约10张图像,但它仍然只显示我捕获的最后一张图像。所以你能帮我解决这个问题吗?我也在我的项目中输入了你的代码,但我想知道它是否仍然无法工作或者我在输入代码时犯了错误。谢谢。 - arvin
好的,等一下我会把我的代码插入到你的项目中,请稍等。 - Fabio Venturi Pastor
已完成,请检查新的答案。抱歉,应该使用 yourfilepath.size() 而不是 yourfilepath.length()。 - Fabio Venturi Pastor
我已经放置了代码,但仍然没有变化。循环ArrayList没有起作用。另外,ImageView动态也没有制作。它仍然显示我拍摄的最后一张图片。我已经编辑了UploadActivity.java和Activity_Upload代码。请检查是否有错误。谢谢。 - arvin
将ly2更改为android:layout_width="match_parent" android:layout_height="wrap_content",然后在yourFilePaths.add(filePath);之后循环yourFilePaths并检查您获得了多少个文件路径。 - Fabio Venturi Pastor
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接