简体   繁体   English

想要将图像从一个活动转移到另一个活动

[英]want to transfer the image from one activity to another

Here, I have two Activity .In the first activity, I want to pick an image from gallery and transfer that image onto the second activity and set on image view of that activity. 在这里,我有两个Activity 。在第一个活动中,我想从图库中选择一个图像并将该图像传输到第二个活动并设置该活动的图像视图。

I am transferring the path of image to another activity by intent but it does not work for all images. 我通过意图将图像的路径转移到另一个活动,但它不适用于所有图像。 I am able to get some images from gallery only and for some it will close my app or show nothing and get back to first activity. 我只能从图库中获取一些图像,对于某些图像,它将关闭我的应用程序或显示任何内容并返回第一个活动。

How can i improve my code to work for all images. 如何改进我的代码以适用于所有图像。 I check so many times, I think the problem is in transferring the file path and get it into another activity. 我检查了很多次,我认为问题在于传输文件路径并将其转换为另一个活动。

My First activity: 我的第一项活动:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button choose;
    private Bitmap bitmap;

    private int PICK_IMAGE_REQUEST = 1;

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

        choose = (Button) findViewById(R.id.choose);
        choose.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (view == choose) {
            showFileChooser();
        }
    }

    private void showFileChooser() {


        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();


            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                Intent i = new Intent(getApplicationContext(), SecondActivity.class);
                i.putExtra("picture", bitmap);
                startActivity(i);
                } 
            catch (IOException e) {
                e.printStackTrace();


            }
        }

    }
}

my second activity 我的第二项活动

public class SecondActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView image;
    Button upload;

    Bitmap bitmap;

    SharedPreferences sp;
    String rollno;

    private String UPLOAD_URL ="http://aptronnoida.com/applock/image_insert.php";


        private String KEY_Rollno = "rollno";
        private String KEY_IMAGE = "image";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
         image=(ImageView)findViewById(R.id.image);

         bitmap= getIntent().getParcelableExtra("picture") ;
         image.setImageBitmap(bitmap);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(this);
        sp=getSharedPreferences("rajput",MODE_PRIVATE);
        rollno=sp.getString("rollno",null);
    }



    @Override
    public void onClick(View view) {
        if(view == upload){
          uploadImage();
         }
    }

      public String getStringImage(Bitmap bmp){
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
       }

    private void uploadImage() {

        final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
    @Override
            public void onResponse(String s) {
                 //Disimissing the progress dialog
                      loading.dismiss();
                       //Showing toast message of the response
                      Toast.makeText(SecondActivity.this, s , Toast.LENGTH_LONG).show();
                      }
                    },
                    new Response.ErrorListener() {
                       @Override
                      public void onErrorResponse(VolleyError volleyError) {
                          //Dismissing the progress dialog
                   loading.dismiss();

                        //Showing toast
                         Toast.makeText(SecondActivity.this, "Error", Toast.LENGTH_LONG).show();
            }
             }){
              @Override
               protected Map<String, String> getParams() throws AuthFailureError {
                  //Converting Bitmap to String
                  String image = getStringImage(bitmap);

                //Creating parameters
                  Map<String,String> params = new Hashtable<String, String>();

              //Adding parameters
                  /*params.put(KEY_Rollno,rollno);*/
                  params.put(KEY_IMAGE, image);


                  //returning parameters
                     return params;
                    }
};

          //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

          //Adding request to the queue
          requestQueue.add(stringRequest);
    }


    @Override
    public boolean onSupportNavigateUp(){
        onBackPressed();
        return true;
    }
    public void onBackPressed(){

        super.finish();
    }


}

You can pass the image path instead of the whole image to the second activity and load it in second activity when it is initialized. 您可以将图像路径而不是整个图像传递给second activity ,并在初始化时将其加载到第二个活动中。 You can use glide or picasso library for loading image if library usage is not an issue for you. 如果库使用不是您的问题,您可以使用glidepicasso库来加载图像。

Steps: 脚步:

  1. get the path of image 得到图像的路径
  2. save it in String variable 将其保存在String变量中
  3. create a Bundle object, put the path string in the bundle. 创建一个Bundle对象,将路径字符串放在bundle中。
  4. start the second activity with that bundle. 用该捆绑包启动第二个活动。
  5. Fetch the path value from the bundle in the second activity. 从第二个活动中的包中获取路径值。 Finally, 最后,
  6. Load image with glide or picasso. 用滑翔或毕加索加载图像。

In your first MainActivity inside bitmap declare "public static" as below code: 在你的第一个MainActivity里面位图声明“public static”如下代码:

class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button choose;
    public static Bitmap bitmap;

    private int PICK_IMAGE_REQUEST = 1;

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

        choose = (Button) findViewById(R.id.choose);
        choose.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (view == choose) {
            showFileChooser();
        }
    }

    private void showFileChooser() {


        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();


            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                startActivity(new Intent(getApplicationContext(), SecondActivity.class));
                } 
            catch (IOException e) {
                e.printStackTrace();


            }
        }

    }
}

And SecondActivity access code: 和SecondActivity访问代码:

public class SecondActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView image;
    Button upload;

    Bitmap bitmap;

    SharedPreferences sp;
    String rollno;

    private String UPLOAD_URL ="http://aptronnoida.com/applock/image_insert.php";


        private String KEY_Rollno = "rollno";
        private String KEY_IMAGE = "image";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
         image=(ImageView)findViewById(R.id.image);

         bitmap= MainActivity.bitmap ;
         image.setImageBitmap(bitmap);
    }
}

You can pass it as a byte array and build the bitmap for display on the next screen.visit this links: 您可以将其作为字节数组传递并构建位图以在下一个屏幕上显示。请访问以下链接:

how to pass images through intent? 如何通过意图传递图像?

send Bitmap using intent Android 使用intent Android发送位图

For small size images it's Ok( by Bitmap), but for large size you need to do some more work... follow this documentation, it was written in documentation. 对于小尺寸图像,它是好的(通过位图),但是对于大尺寸,你需要做更多的工作......按照这个文档,它是用文档编写的。 https://developer.android.com/training/camera/photobasics.html https://developer.android.com/training/camera/photobasics.html

而不是传递位图,将filePath传递给下一个活动,并在第二个活动中生成位图并进行设置。

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

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