简体   繁体   English

如何在图库中的imageView上设置图像以及在Android中由相机拍摄的图像?

[英]How to set an image on imageView from the gallery and image taken by camera in Android?

In my app I want to set an image on a ImageView from gallery and I want to set an image which is taken by the camera. 在我的应用程序中,我想在图库中的ImageView上设置图像,并且要设置相机拍摄的图像。 I have tried this code, when I load image from the gallery, it is working. 我尝试过此代码,当我从图库中加载图像时,它正在工作。 But when I try to take a picture to set on ImageView , that activity is loaded but the image is not showing in the ImageView . 但是,当我尝试拍摄要在ImageView上设置的图片时,该活动已加载,但该图像未显示在ImageView Any solution for this? 有什么解决办法吗? Here is my code: 这是我的代码:

First Activity 第一次活动

public class MainActivity extends ActionBarActivity {
    private static int RESULT_LOAD_IMAGE = 1;
    private static final int CAMERA_REQUEST = 1888;
    private ImageView imageView;
    Bitmap photo;
    String picturePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
        // this.imageView = (ImageView)this.findViewById(R.id.imgView);
        Button photoButton = (Button) this.findViewById(R.id.button2);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);

            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            int flagval = 1;
          /*  ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));*/
            sendImage(flagval);
        }
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
          /* photo = (Bitmap) data.getExtras().get("data");

            //imageView.setImageBitmap(photo);
            int flagvalt=2;
            try {
                sendImage(flagvalt);
            }
            catch (Exception e){
                Toast.makeText(MainActivity.this, "Method error", Toast.LENGTH_SHORT).show();

            }*/

            try {
                loadCamPic();
                Toast.makeText(MainActivity.this, "Method invoked", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(MainActivity.this, "Method error", Toast.LENGTH_SHORT).show();
            }
        }

    }

    public void sendImage(int flag) {

        if (flag == 1) {
            Toast.makeText(MainActivity.this, "Loc:" + picturePath, Toast.LENGTH_SHORT).show();
            Intent myIntent1 = new Intent(MainActivity.this, ImageUploadActivity.class);
            myIntent1.putExtra("key", picturePath);

            MainActivity.this.startActivity(myIntent1);
        }
        /*else if(flag==2) {
            Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
            intent.putExtra("BitmapImage", photo);
        }*/
    }

    void loadCamPic() {
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String pathName = baseDir + "/DCIM/CAMERA";
        File parentDir = new File(pathName);

        File[] files = parentDir.listFiles();
        Date lastDate = null;
        String lastFileName;
        boolean isFirstFile = true;
        for (File file : files) {
            if (isFirstFile) {
                lastDate = new Date(file.lastModified());
                isFirstFile = false;
            }
            if (file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")) {
                Date lastModDate = new Date(file.lastModified());
                if (lastModDate.after(lastDate)) {
                    lastDate = lastModDate;
                    lastFileName = file.getName();
                    String pathName2 = pathName + lastFileName;

                    // Log.e(TAG, "Method invoked");


                    Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
                    Bundle extras = new Bundle();
                    extras.putString("FILE_PATH", pathName2);
                    extras.putString("FILE_NAME", lastFileName);
                    intent.putExtras(extras);
                    MainActivity.this.startActivity(intent);


                }
            }
        }
    }
}

Second Activity 第二次活动

public class ImageUploadActivity extends ActionBarActivity {

    private Button upload;
    private Bitmap bitmap;
    private ProgressDialog dialog;
    String picturePath;
    String filename;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_upload);
        //Image from sdcard

        Intent intent1 = getIntent();
        picturePath = intent1.getExtras().getString("key");
        imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        bitmap = (BitmapFactory.decodeFile(picturePath));


        //Camera Image

          /*  Intent intent = getIntent();
            bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
            imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(bitmap);*/

        if (picturePath == null) {
            Intent intent = getIntent();
            Bundle extras = intent.getExtras();
            filename = extras.getString("FILE_NAME");
            String filepath = extras.getString("FILE_PATH");
            Toast.makeText(ImageUploadActivity.this, "Success:" + filepath, Toast.LENGTH_SHORT).show();
            imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(filepath));
            bitmap = (BitmapFactory.decodeFile(filepath));
        }
        upload = (Button) findViewById(R.id.upload);

        upload.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (bitmap == null) {
                    Toast.makeText(getApplicationContext(),
                            "Please select image", Toast.LENGTH_SHORT).show();
                } else {
                    dialog = ProgressDialog.show(ImageUploadActivity.this, "Uploading",
                            "Please wait...", true);
                    new ImageUploadTask().execute();
                }
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_image_upload, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    class ImageUploadTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... unsued) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost("http://10.10.10.15/test/upload.php");

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();


              /* entity.addPart("uploaded_file", new ByteArrayBody(data,
                        "myImage.jpg"));*/

                // String newFilename= filename.concat("file");
                // newFilename=filename+newFilename;

                entity.addPart("uploaded_file", new ByteArrayBody(data,
                        filename));
                //  Log.e(TAG, "Method invoked");
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

                StringBuilder builder = new StringBuilder();
                String aux = "";

                while ((aux = reader.readLine()) != null) {
                    builder.append(aux);
                }

                String sResponse = builder.toString();


                return sResponse;
            } catch (Exception e) {
                if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;
            }

            // (null);
        }

        @Override
        protected void onProgressUpdate(Void... unsued) {

        }

        @Override
        protected void onPostExecute(String sResponse) {
            try {
                if (dialog.isShowing())
                    dialog.dismiss();

                if (sResponse != null) {

                    Toast.makeText(getApplicationContext(),
                            "Photo uploaded successfully",
                            Toast.LENGTH_SHORT).show();


                    Log.e("Response", sResponse);
                }

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        "Exception Message",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }
    }
}

Take a look at the selected as best answer here Take photo w/ camera intent and display in imageView or textView? 在此处查看所选的最佳答案, 并使用相机意图拍照并以imageView或textView显示? and you could find out how to take a picture and set it as a background of an imageView programmatically 您可以找到如何拍摄图片并以编程方式将其设置为imageView的背景

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM