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

时间:2017-08-27 11:03:10

标签: android

在这里,我有两个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();


            }
        }

    }
}

我的第二项活动

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


}

5 个答案:

答案 0 :(得分:2)

您可以将图像路径而不是整个图像传递给second activity,并在初始化时将其加载到第二个活动中。如果库使用不是您的问题,您可以使用glidepicasso库来加载图片。

步骤:

  1. get the path of image
  2. 将其保存在字符串变量
  3. 创建一个Bundle对象,将路径字符串放在bundle中。
  4. 使用该捆绑包启动第二个活动。
  5. 从第二个活动中的包中获取路径值。 最后,
  6. 用滑翔或毕加索加载图像。

答案 1 :(得分:1)

在您的第一个MainActivity里面位图声明&#34; public static&#34; ,如下代码:

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


            }
        }

    }
}

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

答案 2 :(得分:0)

您可以将其作为字节数组传递并构建位图以便在下一个屏幕上显示。请访问此链接:

how to pass images through intent?

send Bitmap using intent Android

答案 3 :(得分:0)

对于小尺寸图像,它是好的(通过Bitmap),但是对于大尺寸,你需要做更多的工作......按照这个文档,它是用文档编写的。https://developer.android.com/training/camera/photobasics.html

答案 4 :(得分:0)

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