如何使用户单击5张图片并在Android中的不同图像视图中显示它 [英] how to make user click 5 pics and display it in different image view in android

查看:121
本文介绍了如何使用户单击5张图片并在Android中的不同图像视图中显示它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在申请相机 在这里单击按钮,它会打开一个摄像头,但我希望我应该能够单击5次并将其保存在5种不同的图像视图中,并且在单击图库按钮时,它应该打开一个图库,并让我仅选择5张照片/图像并将其存储在5个不同的图像视图中.

I am Making an application of camera here on click of button it opens a camera but i want that i should be able to click 5 times and save it on 5 different image view and also on click of gallery button it should open a gallery and let me select only 5 pics/images and store it in the 5 different image view.

感谢您的帮助.这是我的代码.

thank you for helping. Here is my code.

我的XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.test.faultexample.MainActivity">



<Button
        android:id="@+id/camerabutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/Edit2"
        android:text="Camera" />

    <LinearLayout
        android:id="@+id/image_linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/camerabutton"
        android:orientation="horizontal"
        android:weightSum="10">

        <ImageView
            android:id="@+id/imageview1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

        <ImageView
            android:id="@+id/imageview2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

        <ImageView
            android:id="@+id/imageview3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

        <ImageView
            android:id="@+id/imageview4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

        <ImageView
            android:id="@+id/imageview5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/image_textview_linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/image_linear"
        android:orientation="horizontal"
        android:weightSum="10">

        <TextView
            android:id="@+id/textview_imagename1"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="" />

        <TextView
            android:id="@+id/textview_imagename2"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="" />

        <TextView
            android:id="@+id/textview_imagename3"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="" />

        <TextView
            android:id="@+id/textview_imagename4"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="" />

        <TextView
            android:id="@+id/textview_imagename5"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="" />

    </LinearLayout>

<Button
        android:id="@+id/btn_select_image_frmgallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/image_textview_linear"
        android:text="select Image" />

    <Button
        android:id="@+id/btnupload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_select_image_frmgallery"
        android:paddingTop="10dp"
        android:text="UPLOAD" />

</RelativeLayout>

MainActivity.java:

MainActivity.java:

public class MainActivity extends AppCompatActivity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText Et = (EditText) findViewById(R.id.Edit1);
        final EditText Et1 = (EditText) findViewById(R.id.Edit2);
        //Et.getText().toString();
        textview_imagename1 = (TextView) findViewById(R.id.textview_imagename1);
        textview_imagename2 = (TextView) findViewById(R.id.textview_imagename2);
        textview_imagename3 = (TextView) findViewById(R.id.textview_imagename3);
        textview_imagename4 = (TextView) findViewById(R.id.textview_imagename4);
        textview_imagename5 = (TextView) findViewById(R.id.textview_imagename5);

        imageView1 = (ImageView) findViewById(R.id.imageview1);
        imageView2 = (ImageView) findViewById(R.id.imageview2);
        imageView3 = (ImageView) findViewById(R.id.imageview3);
        imageView4 = (ImageView) findViewById(R.id.imageview4);
        imageView5 = (ImageView) findViewById(R.id.imageview5);

        //Button Upload Binding
        buttonUploaad = (Button) findViewById(R.id.btnupload);
        buttonUploaad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photo1 = ((BitmapDrawable) imageView1.getDrawable()).getBitmap();
                photo2 = ((BitmapDrawable) imageView2.getDrawable()).getBitmap();
                photo3 = ((BitmapDrawable) imageView3.getDrawable()).getBitmap();
                photo4 = ((BitmapDrawable) imageView4.getDrawable()).getBitmap();
                photo5 = ((BitmapDrawable) imageView5.getDrawable()).getBitmap();
                //Toast.makeText(getApplicationContext(),"Uploaded Succesfully",Toast.LENGTH_LONG).show();
                new UploadImage().execute();
            }
        });

        camerabutton = (Button) findViewById(R.id.camerabutton);
        camerabutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        });

        btnselect = (Button) findViewById(R.id.btn_select_image_frmgallery);
        btnselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_PICTURE);
            }
        });
}

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICK_PICTURE:
                if(requestCode== PICK_PICTURE)
                {
                    if(resultCode==RESULT_OK){
                        //data.getParcelableArrayExtra(name);
                        //If Single image selected then it will fetch from Gallery
                        if(data.getData()!=null){
                            Uri mImageUri=data.getData();
                        }else{
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                if(data.getClipData()!=null){
                                    ClipData mClipData=data.getClipData();
                                    ArrayList<Uri> mArrayUri=new ArrayList<Uri>();
                                    for(int i=0;i<mClipData.getItemCount();i++){
                                        ClipData.Item item = mClipData.getItemAt(i);
                                        Uri uri = item.getUri();
                                        mArrayUri.add(uri);
                                    }
                                    Log.v("LOG_TAG", "Selected Images"+ mArrayUri.size());
                                }
                            }
                        }
                    }
                }
                super.onActivityResult(requestCode, resultCode, data);
            case CAMERA_REQUEST:
                TextView textView = (TextView) findViewById(R.id.textview_imagename1);
                textView.getText();
                if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
                    photo1 = (Bitmap) data.getExtras().get("data");
                    imageView1.setImageBitmap(photo1);
                    SaveImage(photo1);
                }
        }
    }

    private void SaveImage(Bitmap finalBitmap) {
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_images");
        myDir.mkdirs();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        fname = "Image-" + timeStamp + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            textview_imagename1.setText(fname);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

private class UploadImage extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MainActivity.this, "Please Wait !!!", "Please wait", true);
        }

        @Override
        protected String doInBackground(Void... params) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Must compress the Image to reduce image size to make upload easy
            photo1.compress(Bitmap.CompressFormat.PNG, 50, stream);

            byte[] byte_arr = stream.toByteArray();
            String encodedImage = Base64.encodeToString(byte_arr, Base64.DEFAULT);
return encodedImage;


        }

        @Override
        protected void onPostExecute(String encodedString) {
            if (dialog.isShowing()) {
                dialog.dismiss();
                Toast.makeText(getApplicationContext(), encodedString, Toast.LENGTH_LONG).show();
            }
        }
    }
}

推荐答案

根据我的经验,没有简单的解决方案可以解决您的问题.使用和意向访问相机应用程序,您有两个与问题相关的选择:

It is my experience that there is no easy solution to your problem. Using and Intent to access a camera app, you have two choices related to your issue:

  1. 通过意图请求允许用户仅拍摄一张照片.在这种情况下,您可以提供用于存储图片的文件URI.要使用此方法拍摄多张照片,应用必须多次启动意图.每次用户拍照时,相机应用程序都会退出并将用户返回到您的应用程序.这可能不是您想要的体验.

  1. Request, via the intent, to allow the user to take just one picture. In this case, you can provide the file URI where the picture will be stored. To take multiple pictures using this method, the app will have to start the intent multiple times. Each time the user takes a picture, the camera app will exit and return the user to your app. This is probably not the experience you want.

通过意图请求无限期调用相机.在这种模式下,用户可以在不退出相机的情况下拍摄多张照片.但是,您的应用无法指定图片的位置.取而代之的是,它们会在相机应用决定存储它们的任何地方移动.然后,您可以找到这些图片文件并在您的应用程序中使用它们.我将在下面提供有关如何实现此功能的草图.

Request, via the intent, to invoke the camera indefinitely. In this mode, the user can take multiple pictures without exiting the camera. However, your app cannot specify where the pictures go. Instead, they will go wherever the camera app decides to store them. You can then find those picture files and use them in your app. I will provide a sketch of how to implement this, below.

正如Neo回答的那样,您可以说还有第三种选择,然后编写自己的相机应用程序.如果您需要各种控件(例如亮度,缩放等),那肯定是很多工作!

You could say there's a third choice, as Neo answered, and write your own camera app. That would certainly be a lot of work if you want the various controls, such as brightness, zoom, etc.!

背景:

首先,您需要了解MediaStore.这是一家Android提供程序,可跟踪您设备上可用的所有照片(以及许多其他媒体文件和流).相机应用程序每次拍摄照片时,都会将其引用添加到MediaStore.因此,对于上面的选项2,当用户使用相机应用程序拍摄多张照片时,每张照片都将记录在MediaStore中.尽管我不知道有任何文档可以支持这种情况,但这种情况似乎会立即发生. (因此,可能会有一个相机应用程序,它推迟了对MediaStore的更新,直到拍照后的一段时间为止.不过,可能不是.)

First, you need to know about the MediaStore. This is an Android provider that keeps track of all photos (and many other media files and streams) available on your device. Each time the camera app takes a picture, it adds a reference of it to the MediaStore. So, for option 2 above, when the user takes several pictures using the camera app, each picture will be recorded in the MediaStore. This appears to happen immediately, though I don't know of any documentation that supports that. (Thus, there could be a camera app that defers updating MediaStore until some period of time after a picture is taken. Probably not, though.)

除其他外,MediaStore记录

Among other things, the MediaStore records the

方法

首先,记下当前时间.您将需要此,如下所示.

First, note the current time. You will need this, as you will see below.

long invokeTime = System.currentTimeMillis ();

注册观察者以查看MediaStore的更改.创建ContentObserver的子类,并使用此代码在MediaStore中注册它.

Register an observer for changes to the MediaStore. Create a subclass of ContentObserver and use this code to register it with MediaStore.

Uri IMAGES_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
getContentResolver().registerContentObserver (IMAGES_URI, true, this);

您的观察者子类将需要重写onChange()方法:

Your observers subclass will need will need to override the onChange() methods:

@Override public void onChange (boolean selfChage)
{
  onChange (selfChage, null);
}

@Override public void onChange (boolean selfChange, Uri uri)
{
  listener.onContentChange (selfChange, uri);
}

而且,正如您在上面看到的那样,当发生onChange()时,您将需要一个侦听器或对应用程序的某种回调.

And, as you can see above, you will need a listener, or some kind of call back to your app, to do something when an onChange() occurs.

在我的侦听器中,将新图像的URI保存在ArrayList中.这是困难的部分.每次拍摄照片时都会调用onChange().还将要求对MediaStore进行任何其他更改,因此您仅在保存新图片时注意.查询最新图片的时间和文件路径:

In my listener, I save the URIs for the new images in my ArrayList. This is the hard part. onChange() will be called each time a picture is taken. It will be called for any other change to MediaStore as well, so you pay attention only when a new picture was saved. Query the time and file path for the most recent picture:

String[] projection = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED };
String selection = null;
String[] selectionArgs = null;
order = MediaStore.Images.ImageColumns.DATE_ADDED + " DESC limit 1";
Cursor cursor = context.getContentResolver().query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        projection,
        selection,
        selectionArgs,
        order);

然后获取第一行

if (cursor.moveToNext())
{
  int dateColumn = cursor.getColumnIndex (MediaStore.Images.Media.DATE_ADDED);
  int pathColumn = cursor.getColumnIndex (MediaStore.Images.Media.DATA);
  dateAddedMillis = cursor.getLong (dateColumn) * 1000;
  path = new File (cursor.getString (pathColumn));
}
cursor.close();

如果是最新图片(如上图所示):

If the latest image, as fetched above:

  • 具有"dateAddedMillis"> invokeTime,并且
  • 尚未在captureImageArray中,并且
  • 其文件存在(可能是删除文件的通知)

然后将其放在ImageView中,或将其放置在您想使用的任何东西中.

then put it in your ImageView, or whatever you may wish to do with it.

create bitmap from image stored at "path";

最后,准备好所有这些后,调用相机:

Finally, once all this is prepared, invoke the camera:

static private int ACTIVITY_REQUEST_CAMERA = 2;
...
Intent intent = new Intent();
intent.setAction (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA););
startActivityForResult (intent, ACTIVITY_REQUEST_CAMERA);

当用户退出相机时,请确保注销观察者的注册.否则,它将继续从用户碰巧使用的任何其他应用中获取对MediaStore的更改.

When the user exits the camera, be sure to unregister your observer. Otherwise, it will continue to pick up changes to MediaStore from any other app the user happens to use.

以上方法旨在说明此过程的核心.此外,您将需要获得READ_EXTERNAL_STORAGE权限.另外,如果用户有SD卡,则可能需要确保已安装SD卡.可能还有其他考虑因素.

The above method is meant to explain the core of this process. In addition, you will need to get the READ_EXTERNAL_STORAGE permission. Also, if the user has an SD card, you may need to ensure that it is mounted. There are probably other considerations.

它也不是失败安全的.它工作得很好,但是用户可以调用其他创建图像的应用程序,您也可以捕获"这些应用程序.您可能还可以想象其他失败案例.

Nor is it fail safe. It works very well but the user may invoke other apps which create images and you will "capture" those, too. You can probably imagine other failure cases, too.

这篇关于如何使用户单击5张图片并在Android中的不同图像视图中显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆