安卓图像处理(三)从相册选择图片

0 代码

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

	// One Button
	Button BSelectImage;

	// One Preview Image
	ImageView IVPreviewImage;

	// constant to compare
	// the activity result code
	int SELECT_PICTURE = 200;

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

		// register the UI widgets with their appropriate IDs
		BSelectImage = findViewById(R.id.BSelectImage);
		IVPreviewImage = findViewById(R.id.IVPreviewImage);

		// handle the Choose Image button to trigger
		// the image chooser function
		BSelectImage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				imageChooser();
			}
		});
	}

	// this function is triggered when
	// the Select Image Button is clicked
	void imageChooser() {

		// create an instance of the
		// intent of the type image
		Intent i = new Intent();
		i.setType("image/*");
		i.setAction(Intent.ACTION_GET_CONTENT);

		// pass the constant to compare it
		// with the returned requestCode
		startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE);
	}

	// this function is triggered when user
	// selects the image from the imageChooser
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {

			// compare the resultCode with the
			// SELECT_PICTURE constant
			if (requestCode == SELECT_PICTURE) {
				// Get the url of the image from data
				Uri selectedImageUri = data.getData();
				if (null != selectedImageUri) {
					// update the preview image in the layout
					IVPreviewImage.setImageURI(selectedImageUri);
				}
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值