为了账号安全,请及时绑定邮箱和手机立即绑定

如何从图库中导入图像并替换图像视图中的图像?

如何从图库中导入图像并替换图像视图中的图像?

慕标5832272 2022-12-28 13:59:35
我构建了这个应用程序,我希望我可以从图库中选择一个图像来替换顶部的图像视图。就像 facebook 上的个人资料等...我试过上面的代码:public class MainActivity extends Activity {private static int RESULT_LOAD_IMAGE = 1;Uri myPicture = null;Button buttonLoadImage;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    //getting View    buttonLoadImage =(Button) findViewById(R.id.regButton);    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);        }    });}@Overrideprotected 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]);        String picturePath = cursor.getString(columnIndex);        cursor.close();        ImageView imageView = (ImageView) findViewById(R.id.regUserPhoto);        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));    }}在我的 android 4.4.4 手机中:我可以选择图像,但是当我按下 ok 时,应用程序崩溃了。在模拟器 android 5.1.1 中:当我按下图像时,应用程序崩溃
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

使用 startActivityForResult 使您的按钮在此处调用活动工具: https ://www.youtube.com/watch?v=w06OnGwhh4I&feature=youtu.be


此活动从相机、画廊、谷歌驱动器等中挑选图像。裁剪图像并将其旋转到。代码Java:


import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.support.annotation.Nullable;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.ImageButton;

import android.widget.ImageView;

import android.widget.Toast;


import com.example.android.controledevendas.R;

import com.theartofdev.edmodo.cropper.CropImage;

import com.theartofdev.edmodo.cropper.CropImageView;


public class Image_Cropper_Activity extends AppCompatActivity {


    private ImageButton btn_browse;

    private ImageButton btn_reset;

    private ImageView imageView;

    private Uri uriPass = null;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_image__cropper_);


        btn_browse = findViewById(R.id.image_cropper_btn_add_picture);

        btn_reset = findViewById(R.id.image_cropper_btn_reset);

        imageView = findViewById(R.id.cropper_image);


        btn_browse.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                CropImage.startPickImageActivity(Image_Cropper_Activity.this);                      

            }

        });


        btn_reset.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                imageView.setImageBitmap(null);

                uriPass = null;

            }

        });

    }


    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.add_cliente_fornecedor, menu);

        return true;

    }


    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {


            case (android.R.id.home):

                setResult(RESULT_OK);

                finish();

                return true;


            case (R.id.save_client_fornecedor):

                saveImage();

                return true;


            default:

                return super.onOptionsItemSelected(item);

        }


    }



    @Override

    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if(requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK){

            Uri imageUri = CropImage.getPickImageResultUri(this, data);

            if(CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)){

            }

            else {

                startCrop(imageUri);

            }

        }


        if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){

            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if(resultCode == RESULT_OK){

                imageView.setImageURI(result.getUri());

                uriPass = result.getUri();

                //Toast.makeText(this, "Imagem Atualizada Com Sucesso!", Toast.LENGTH_SHORT).show();

            }

        }

    }


    private void startCrop(Uri imageUri) {

        CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON).setMultiTouchEnabled(true).start(this);

    }


    private void saveImage() {

        if (uriPass==null){

            Toast.makeText(this, "Por favor, insira uma imagem.", Toast.LENGTH_SHORT).show();

            return;

        }


        Intent dataForAddEditScreen = new Intent();

        dataForAddEditScreen.setData(uriPass);                                                      

        setResult(RESULT_OK, dataForAddEditScreen);

        finish();

    }

}

代码:


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

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:gravity="center"

    android:padding="10dp"

    tools:context=".Activities.Image_Cropper_Activity">


    <ImageView

        android:id="@+id/cropper_image"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="1" />


    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:gravity="center"

        android:orientation="horizontal"

        android:padding="20dp">


        <ImageButton

            android:id="@+id/image_cropper_btn_add_picture"

            android:layout_width="80dp"

            android:layout_height="80dp"

            android:background="@drawable/bg_round"

            app:srcCompat="@drawable/ic_image_sample_50x50_white" />


        <Space

            android:layout_width="20dp"

            android:layout_height="wrap_content" />


        <Space

            android:layout_width="20dp"

            android:layout_height="wrap_content" />


        <ImageButton

            android:id="@+id/image_cropper_btn_reset"

            android:layout_width="80dp"

            android:layout_height="80dp"

            android:background="@drawable/bg_round"

            app:srcCompat="@drawable/ic_refresh_50x50_white" />


    </LinearLayout>

</LinearLayout>

返回图片 Uri 后:


private ImageView imageProduto;


protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_add__edit__produto_);


imageProduto = findViewById(R.id.image_produto_detail);

}

...


@Override

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

    super.onActivityResult(requestCode, resultCode, data);


    if(requestCode == Constantes.REQUEST_CODE_ADD_PICTURE && resultCode == RESULT_OK && data!= null){


            Uri imageUri = data.getData();

            imageProduto.setImageURI(imageUri);

            Toast.makeText(this, "Image Update Successfully!", Toast.LENGTH_SHORT).show();


    }else {

        Toast.makeText(this, "Image Not Updated!", Toast.LENGTH_SHORT).show();

    }


}


查看完整回答
反对 回复 2022-12-28
  • 1 回答
  • 0 关注
  • 63 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信