如何将捕获的图像发送到第二个活动?

时间:2015-07-21 05:57:55

标签: android android-intent android-activity

我在MainActivity上有两个按钮。一个用于从Gallery中选择图像,另一个用于相机图像捕获。我想将这些图像发送到第二个活动。当我尝试使用Gallery图像时,我获得了成功。但是,现在我想将捕获的图像传递给第二个活动。我尝试了很多代码但却无法得到满意的结果。

以下是我的代码......

MainActivity.java

package com.MyFirstApp.myfirstapp;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    Button btn_choose_from_gallery, btn_go_to_camera;

    int REQUEST_GALLERY = 1;
    int REQUEST_CAMERA = 100;

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

        btn_choose_from_gallery = (Button) findViewById(R.id.btn_choose_from_gallery);
        btn_go_to_camera = (Button) findViewById(R.id.btn_go_to_camera);

        btn_choose_from_gallery.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_GALLERY);
            }
        });

        btn_go_to_camera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent_camera = new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent_camera, REQUEST_CAMERA);
            }
        });
    }

    /* Choose Image from Gallery & Camera onActivityResult */
    @Override
    protected void onActivityResult(int reqCode, int resCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(reqCode, resCode, data);

        if (resCode == RESULT_OK) {
            if (reqCode == REQUEST_CAMERA) {
                if (data != null) {
                    Uri CapturedImgUri = data.getData();
                    /* Passing ImageURI to the Second Activity */
                    Intent IntentCamera = new Intent(this, Second.class);
                    IntentCamera.putExtra("CapturedImgUri", CapturedImgUri);
                    startActivity(IntentCamera);
                }
            } else if (reqCode == REQUEST_GALLERY) {
                if (data != null) {
                    Uri selectedImgUri = data.getData();
                    /* Passing ImageURI to the Second Activity */
                    Intent IntentGallery = new Intent(this, Second.class);
                    IntentGallery.setData(selectedImgUri);
                    startActivity(IntentGallery);
                }
            }
        }
    }

    /* Choose Image from Gallery onActivityResult */// This code works fine when
                                                    // I just want to choose
                                                    // image only from Gallery//
    // @Override
    // protected void onActivityResult(int reqCode, int resCode, Intent data) {
    // // TODO Auto-generated method stub
    // super.onActivityResult(reqCode, resCode, data);
    //
    // if (reqCode == REQUEST_GALLERY && resCode == RESULT_OK && data != null) {
    // Uri selectedImgUri = data.getData();
    //
    // /* Passing ImageURI to the Second Activity */
    // Intent img_pass = new Intent(this, Second.class);
    // img_pass.setData(selectedImgUri);
    // startActivity(img_pass);
    // }
    // }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Second.java

package com.MyFirstApp.myfirstapp;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.devsmart.android.ui.HorizontalListView;

public class Second extends Activity {

    TouchImageView img_to_be_zoomed, img_to_be_zoomed_second;
    ImageView img_back;
    HorizontalListView HListView, HListViewFirst;

    Bitmap bitmap_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        img_to_be_zoomed = (TouchImageView) findViewById(R.id.img_to_be_zoomed);
        img_to_be_zoomed_second = (TouchImageView) findViewById(R.id.img_to_be_zoomed_second);
        img_back = (ImageView) findViewById(R.id.img_back_icon);
        HListView = (HorizontalListView) findViewById(R.id.horizontal_list_view);
        HListViewFirst = (HorizontalListView) findViewById(R.id.horizontal_list_view_first);

        /* Top Back Icon */
        img_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });

        /* Left Image Touch Event */
        img_to_be_zoomed
                .setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {

                    @Override
                    public void onMove() {
                        img_to_be_zoomed_second.setZoom(img_to_be_zoomed);

                        PointF pointF_img1 = new PointF();
                        pointF_img1 = img_to_be_zoomed.getScrollPosition();
                        img_to_be_zoomed_second.setScrollPosition(
                                1 - pointF_img1.x, pointF_img1.y);
                    }
                });
        /* Right Image touch event */
        img_to_be_zoomed_second
                .setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {

                    @Override
                    public void onMove() {
                        img_to_be_zoomed.setZoom(img_to_be_zoomed_second);

                        PointF pointF_img1 = new PointF();
                        pointF_img1 = img_to_be_zoomed_second
                                .getScrollPosition();
                        img_to_be_zoomed.setScrollPosition(1 - pointF_img1.x,
                                pointF_img1.y);
                    }
                });

        int[] HorizontalListImages = new int[] { R.drawable.icon_grid,
                R.drawable.icon_text, R.drawable.icon_clip_art };
        final int[] HorizontalListImagesFirst = new int[] {
                R.drawable.icon_go_back, R.drawable.icon_horizontal_grid,
                R.drawable.icon_vertical_grid };

        /* Animation References */
        final Animation slideUp = AnimationUtils.loadAnimation(
                getApplicationContext(), R.anim.slide_up);
        final Animation slideDown = AnimationUtils.loadAnimation(
                getApplicationContext(), R.anim.slide_down);

        /* Setting Adapter for Horizontal List Views */
        HorizontalListViewAdapter horizontalListViewAdapter = new HorizontalListViewAdapter(
                Second.this, HorizontalListImages);
        HListView.setAdapter(horizontalListViewAdapter);

        /* Horizontal List View Item Click Listener */
        HListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                switch (position) {
                case 0:
                    HorizontalListViewAdapterFirst horizontalListViewAdapterFirst = new HorizontalListViewAdapterFirst(
                            Second.this, HorizontalListImagesFirst);
                    HListViewFirst.setAdapter(horizontalListViewAdapterFirst);

                    HListView.startAnimation(slideDown);
                    HListView.setVisibility(View.GONE);
                    HListViewFirst.startAnimation(slideUp);
                    HListViewFirst.setVisibility(View.VISIBLE);
                    break;

                default:
                    break;
                }
            }
        });

        HListViewFirst.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                switch (position) {
                case 0:
                    HListViewFirst.startAnimation(slideDown);
                    HListViewFirst.setVisibility(View.GONE);
                    HListView.startAnimation(slideUp);
                    HListView.setVisibility(View.VISIBLE);
                    break;

                case 1:
                    DisplayMetrics displaymetrics = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(
                            displaymetrics);
                    int height = displaymetrics.heightPixels;
                    int width = displaymetrics.widthPixels;

                    /* Setting Center Layout For Both Images */
                    RelativeLayout.LayoutParams ImagelayoutParams = new RelativeLayout.LayoutParams(
                            width, width);
                    ImagelayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                    ((RelativeLayout) findViewById(R.id.imagelayout))
                            .setLayoutParams(ImagelayoutParams);

                    RelativeLayout.LayoutParams layoutParamsLeft = new RelativeLayout.LayoutParams(
                            width / 2, width);
                    layoutParamsLeft.setMargins(0, 0, 0, 0);
                    img_to_be_zoomed.setLayoutParams(layoutParamsLeft);

                    bitmap_img = ((BitmapDrawable) img_to_be_zoomed
                            .getDrawable()).getBitmap();
                    bitmap_img = flipImage(bitmap_img, 2);
                    img_to_be_zoomed_second.setImageBitmap(bitmap_img);

                    RelativeLayout.LayoutParams layoutParamsRight = new RelativeLayout.LayoutParams(
                            width / 2, width);
                    layoutParamsRight.setMargins(width / 2, 0, 0, 0);
                    img_to_be_zoomed_second.setLayoutParams(layoutParamsRight);
                    // img_to_be_zoomed.invalidate();
                    img_to_be_zoomed_second.setVisibility(view.VISIBLE);
                    break;

                default:
                    break;
                }
            }
        });

        /* Getting ImageURI from Gallery from Main Activity */
        Uri selectedImgUri = getIntent().getData();
        String[] selectedImgPath = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImgUri,
                selectedImgPath, null, null, null);
        cursor.moveToFirst();

        int indexCol = cursor.getColumnIndex(selectedImgPath[0]);
        String imgPath = cursor.getString(indexCol);
        cursor.close();
        img_to_be_zoomed.setImageBitmap(BitmapFactory.decodeFile(imgPath));

        /* Getting Image from Camera from Main Activity */
        Uri CapturedImgUri = getIntent().getParcelableExtra("CapturedImgUri");
        Log.e("URI", "" + CapturedImgUri);
        img_to_be_zoomed.setImageURI(CapturedImgUri);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /* Flip Image Class */
    public Bitmap flipImage(Bitmap src, int type) {
        Matrix matrix = new Matrix();
        /* Flip vertically */
        if (type == 1) {
            matrix.preScale(1.0f, -1.0f);
            /* Flip horizontally */
        } else if (type == 2) {
            matrix.preScale(-1.0f, 1.0f);
        } else {
            return null;
        }
        return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
                matrix, true);
    }
}

的Manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.MyFirstApp.myfirstapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <!-- Required Permissions -->
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Second"
            android:label="@string/title_activity_second" >
        </activity>
    </application>

</manifest>

我收到如下错误....

01-05 04:39:21.055: E/AndroidRuntime(7471): FATAL EXCEPTION: main
01-05 04:39:21.055: E/AndroidRuntime(7471): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.MyFirstApp.myfirstapp/com.MyFirstApp.myfirstapp.Second}: java.lang.NullPointerException
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.os.Looper.loop(Looper.java:137)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.ActivityThread.main(ActivityThread.java:4424)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at java.lang.reflect.Method.invokeNative(Native Method)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at java.lang.reflect.Method.invoke(Method.java:511)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at dalvik.system.NativeStart.main(Native Method)
01-05 04:39:21.055: E/AndroidRuntime(7471): Caused by: java.lang.NullPointerException
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.content.ContentResolver.acquireProvider(ContentResolver.java:913)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.content.ContentResolver.query(ContentResolver.java:305)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at com.MyFirstApp.myfirstapp.Second.onCreate(Second.java:185)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.Activity.performCreate(Activity.java:4492)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-05 04:39:21.055: E/AndroidRuntime(7471):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-05 04:39:21.055: E/AndroidRuntime(7471):     ... 11 more

提前致谢....

2 个答案:

答案 0 :(得分:4)

我已经建立了解决方案,不是我想要的方式,但方式略有不同......

更改MainActivity.java的代码

/* Choose Image from Gallery & Camera onActivityResult */
@Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(reqCode, resCode, data);

    if (resCode == RESULT_OK) {
        if (reqCode == REQUEST_CAMERA) {
            if (data != null) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                /* Passing BITMAP to the Second Activity */
                Intent IntentCamera = new Intent(this, Second.class);
                IntentCamera.putExtra("BitmapImage", photo);
                startActivity(IntentCamera);
            }
        } else if (reqCode == REQUEST_GALLERY) {
            if (data != null) {
                Uri selectedImgUri = data.getData();
                /* Passing ImageURI to the Second Activity */
                Intent IntentGallery = new Intent(this, Second.class);
                IntentGallery.setData(selectedImgUri);
                startActivity(IntentGallery);
            }
        }
    }
}

更改Second.java的代码

/* Getting ImageURI from Gallery from Main Activity */
    Uri selectedImgUri = getIntent().getData();
    if (selectedImgUri != null) {
        Log.e("Gallery ImageURI", "" + selectedImgUri);
        String[] selectedImgPath = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImgUri,
                selectedImgPath, null, null, null);
        cursor.moveToFirst();

        int indexCol = cursor.getColumnIndex(selectedImgPath[0]);
        String imgPath = cursor.getString(indexCol);
        cursor.close();
        img_to_be_zoomed.setImageBitmap(BitmapFactory.decodeFile(imgPath));
    }

    /* Getting ImageBitmap from Camera from Main Activity */
    Intent intent_camera = getIntent();
    Bitmap camera_img_bitmap = (Bitmap) intent_camera
            .getParcelableExtra("BitmapImage");
    if (camera_img_bitmap != null) {
        img_to_be_zoomed.setImageBitmap(camera_img_bitmap);
    }
}

希望这能有所帮助......

答案 1 :(得分:0)

嘿,您使用Gallery Intent传递数据,并在Camera Intent中传递String。在第二个活动中,您将检索getIntent()。getData()。这是

替换此行

Uri CapturedImgUri = data.getData();
                /* Passing ImageURI to the Second Activity */
                Intent IntentCamera = new Intent(this, Second.class);
                IntentCamera.putExtra("CapturedImgUri", CapturedImgUri);
                startActivity(IntentCamera);

Uri CapturedImgUri = data.getData();
                /* Passing ImageURI to the Second Activity */
                Intent IntentCamera = new Intent(this, Second.class);
                IntentCamera.putData("CapturedImgUri", CapturedImgUri);
                startActivity(IntentCamera);

在onActivityResult方法的第一个活动中。

希望这会有效......