Android 如何将手机摄像头拍摄的图像从一个活动移动到另一个活动的图像视图?

Android 如何将手机摄像头拍摄的图像从一个活动移动到另一个活动的图像视图?,android,android-camera,sharedpreferences,android-camera-intent,android-capture,Android,Android Camera,Sharedpreferences,Android Camera Intent,Android Capture,第一个活动有一个按钮,单击该按钮可打开内置摄像头。现在,当拍摄照片时,一个新的活动将打开,其中包含在imageView中捕获的图像以及下一个活动中的共享按钮。我已将活动设置为在拍摄图像后打开,但是我无法在活动之间传输捕获的图像。我需要帮助或是朝正确的方向轻推 拍摄图片的第一个活动是Takepicture.java: import android.app.Activity; import android.content.Intent; import android.content.SharedPr

第一个活动有一个按钮,单击该按钮可打开内置摄像头。现在,当拍摄照片时,一个新的活动将打开,其中包含在
imageView
中捕获的图像以及下一个活动中的共享按钮。我已将活动设置为在拍摄图像后打开,但是我无法在活动之间传输捕获的图像。我需要帮助或是朝正确的方向轻推

拍摄图片的第一个活动是
Takepicture.java

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import java.io.File;
import java.util.Date;

public class TakePicture extends Activity {
Button camerabutton;
Intent intent;
int requestCode;
int resultCode;
static int REQUEST_IMAGE_CAPTURE = 1;
SharedPreferences imagepreferences;
SharedPreferences.Editor imageeditor;
private String imgPath;
Uri setImageUri;
File file;
Uri imgUri;
public String getImagePath;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.takepicture);
    camerabutton = (Button) findViewById(R.id.button6);
    imagepreferences=getSharedPreferences("image", MODE_PRIVATE);
    imageeditor=imagepreferences.edit();
    camerabutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getPackageManager()) != null)
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        startActivity(new Intent(TakePicture.this, Aftertakepicture.class));
    }
}
}
package com.example.kesandunwokolo.febclasstest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;

public class Aftertakepicture extends Activity {
Button camerabutton;
ImageView saveimage;
Button sharebutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aftertakepicture);
    camerabutton=(Button)findViewById(R.id.button6);
    saveimage=(ImageView)findViewById(R.id.imageView2);
    sharebutton=(Button)findViewById(R.id.button7);
}
}
第二个活动,
AfterMakePicture.java

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import java.io.File;
import java.util.Date;

public class TakePicture extends Activity {
Button camerabutton;
Intent intent;
int requestCode;
int resultCode;
static int REQUEST_IMAGE_CAPTURE = 1;
SharedPreferences imagepreferences;
SharedPreferences.Editor imageeditor;
private String imgPath;
Uri setImageUri;
File file;
Uri imgUri;
public String getImagePath;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.takepicture);
    camerabutton = (Button) findViewById(R.id.button6);
    imagepreferences=getSharedPreferences("image", MODE_PRIVATE);
    imageeditor=imagepreferences.edit();
    camerabutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getPackageManager()) != null)
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        startActivity(new Intent(TakePicture.this, Aftertakepicture.class));
    }
}
}
package com.example.kesandunwokolo.febclasstest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;

public class Aftertakepicture extends Activity {
Button camerabutton;
ImageView saveimage;
Button sharebutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aftertakepicture);
    camerabutton=(Button)findViewById(R.id.button6);
    saveimage=(ImageView)findViewById(R.id.imageView2);
    sharebutton=(Button)findViewById(R.id.button7);
}
}
第一个活动的
takepicture.xml

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>



如果您有任何帮助,我们将不胜感激

有几种方法可以实现这一点,通过在
Intent
不推荐)中发送
位图本身,或者将图像保存到存储器中,并在
Intent
中发送其路径,而
Intent推荐的。
首先将图像保存到
SD卡
,然后在
intent
中传递图像

Intent intent = new Intent(this,MyClass.class);
Bundle bundle = new Bundle();
bundle.putString("IMAGE_PATH",imageFile);
intent.putExtras(bundle);
startActivity(intent);
然后在其他活动中,你可以使用

String path = getIntent().getExtras().getString("IMAGE_PATH");
Bitmap bmp = BitmapFactory.decodeFile(path);
myImage.setImageBitmap(bmp);

参考这个。您应该将图像保存在一个文件中,并获取该图像的文件路径。然后,您可以将映像路径传递到第二个活动。

这是我的解决方案,我已经在我的环境中进行了测试。希望这有帮助

如果使用emulator进行测试,请确保像这样支持摄像头

使用完整源代码更新(新项目):

MainActivity.java:

package com.example.photocapture;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends Activity {

    private Uri mFileUri;
    private final Context mContext = this;

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

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        mFileUri = getOutputMediaFileUri(1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

        // start the image capture Intent
        startActivityForResult(intent, 100);
    }

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

        if (resultCode == RESULT_OK) {
            if (mFileUri != null) {
                String mFilePath = mFileUri.toString();
                if (mFilePath != null) {
                    Intent intent = new Intent(mContext, SecondActivity.class);
                    intent.putExtra("filepath", mFilePath);
                    startActivity(intent);
                }
            }
        }               
    }

    @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);
    }

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

    // Return image / video
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == 1) { // image
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        } else if (type == 2) { // video
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
}
package com.example.photocapture;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import java.io.File;

public class SecondActivity extends Activity {

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

        Intent intent = getIntent();
        String filepath = intent.getStringExtra("filepath");
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
        filepath = filepath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
        File imgFile = new File(filepath);
        if (imgFile.exists()) {
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
            imageView.setImageBitmap(bitmap);
        }
    }

    @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_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();

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

        return super.onOptionsItemSelected(item);
    }
}
SecondActivity.java:

package com.example.photocapture;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends Activity {

    private Uri mFileUri;
    private final Context mContext = this;

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

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        mFileUri = getOutputMediaFileUri(1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

        // start the image capture Intent
        startActivityForResult(intent, 100);
    }

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

        if (resultCode == RESULT_OK) {
            if (mFileUri != null) {
                String mFilePath = mFileUri.toString();
                if (mFilePath != null) {
                    Intent intent = new Intent(mContext, SecondActivity.class);
                    intent.putExtra("filepath", mFilePath);
                    startActivity(intent);
                }
            }
        }               
    }

    @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);
    }

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

    // Return image / video
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == 1) { // image
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        } else if (type == 2) { // video
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
}
package com.example.photocapture;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import java.io.File;

public class SecondActivity extends Activity {

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

        Intent intent = getIntent();
        String filepath = intent.getStringExtra("filepath");
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
        filepath = filepath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
        File imgFile = new File(filepath);
        if (imgFile.exists()) {
            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
            imageView.setImageBitmap(bitmap);
        }
    }

    @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_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();

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

        return super.onOptionsItemSelected(item);
    }
}
activity_main.xml:

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

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
第二项活动:

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

        super.addContentView(R.layout.activity_second);

        Intent intent = getIntent();
        mFilePath = intent.getStringExtra("filepath");
        previewMedia();
        ...
    }

    private void previewMedia() {              
            BitmapFactory.Options options = new BitmapFactory.Options();            
            options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
            mFilePath = mFilePath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
            File imgFile = new File(mFilePath);
            if (imgFile.exists()) {
                final Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
                mImagePreview.setImageBitmap(bitmap);
            }
        }

传入捕获图像的图像路径如何?如果(resultCode==RESULT_OK){if(mFileUri!=null){mFilePath=mFileUri.toString();…intent.putExtra(“filepath”,mFilePath);startActivity(intent);…}}
这是在onCreate下还是在onAcivityResult下?它什么也没做,它只返回了第一个活动,没有图像,您需要
Intent Intent=new Intent(mContext,SecondActivity.class)我已经测试过了。此外,在SecondActivity中,您应该处理
Intent-Intent=getIntent();字符串filepath=intent.getStringExtra(“文件路径”)
onCreate第一部分,我是否将其添加到onCreate或onActivityResult下?用户单击按钮或图像本身后添加的第一部分,而不是onCreate,第二部分是,您将其添加到其他活动的onCreate中。如果答案是你想要的,请接受它,这样人们在将来可以从中受益。当然会的,1-确保你先保存图像,2-确保你通过了正确的路径。3-始终检查空值。那么如何将其保存在应用程序中?我不想从手机的照片库中检索新方法,我是将它们放在onActivityResult()之前还是之后?都可以。让我在FirstActivity中添加按钮点击代码以获得更清晰的信息OK我已经能够使我的代码与您的类似,但我是否要导入“MEDIA_TYPE_IMAGE”和“MEDIA_TYPE_VIDEO”作为任何内容,因为它们都会给出错误,所以我无法运行以查看它是否工作错误:(90,32)错误:找不到符号变量MEDIA_TYPE_VIDEOomg它工作!是权限问题,我忘了加上。非常感谢你。我非常感激!
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        super.addContentView(R.layout.activity_second);

        Intent intent = getIntent();
        mFilePath = intent.getStringExtra("filepath");
        previewMedia();
        ...
    }

    private void previewMedia() {              
            BitmapFactory.Options options = new BitmapFactory.Options();            
            options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
            mFilePath = mFilePath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return null
            File imgFile = new File(mFilePath);
            if (imgFile.exists()) {
                final Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
                mImagePreview.setImageBitmap(bitmap);
            }
        }