• Android实战简易教程-第二十八枪(Uri转String型实例)


    接上一篇文章。我们能够轻易的获取所选图片的uri,那么我们考虑怎样将获取的uri转换成String型的地址呢?

    接下来我们通过实例来研究。布局文件和上篇(二十七枪)一致,我们就不再列出,直接看MainActivity.java:

    package com.example.userphoto;
    
    import java.io.File;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
    import cn.bmob.v3.Bmob;
    import cn.bmob.v3.datatype.BmobFile;
    import cn.bmob.v3.listener.UploadFileListener;
    
    public class MainActivity extends Activity implements OnClickListener {
    	private static final int IMAGE_REQUEST_CODE = 0;
    	private static final int CAMERA_REQUEST_CODE = 1;
    	private static final int RESIZE_REQUEST_CODE = 2;
    
    	private static final String IMAGE_FILE_NAME = "header.jpg";
    
    	private ImageView mImageHeader;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		Bmob.initialize(this, "8f3ffb2658d8a3366a70a0b0ca0b71b2");//初始化Bmob
    		setupViews();
    	}
    
    	private void setupViews() {
    		mImageHeader = (ImageView) findViewById(R.id.image_header);
    		final Button selectBtn1 = (Button) findViewById(R.id.btn_selectimage);
    		final Button selectBtn2 = (Button) findViewById(R.id.btn_takephoto);
    		selectBtn1.setOnClickListener(this);
    		selectBtn2.setOnClickListener(this);
    	}
    
    	@Override
    	public void onClick(View v) {
    		switch (v.getId()) {
    		case R.id.btn_selectimage:
    			Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
    			galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
    			galleryIntent.setType("image/*");//图片
    			startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
    			break;
    		case R.id.btn_takephoto:
    			if (isSdcardExisting()) {
    				Intent cameraIntent = new Intent(
    						"android.media.action.IMAGE_CAPTURE");//拍照
    				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
    				cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
    				startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
    			} else {
    				Toast.makeText(v.getContext(), "请插入sd卡", Toast.LENGTH_LONG)
    						.show();
    			}
    			break;
    		}
    	}
    
    	@Override
    	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    		if (resultCode != RESULT_OK) {
    			return;
    		} else {
    			switch (requestCode) {
    			case IMAGE_REQUEST_CODE:
    				Uri originalUri=data.getData();//获取图片uri
    				resizeImage(originalUri);
    				//以下方法将获取的uri转为String类型哦!
    				String []imgs={MediaStore.Images.Media.DATA};//将图片URI转换成存储路径  
    				Cursor cursor=this.managedQuery(originalUri, imgs, null, null, null);  
    				int index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
    				cursor.moveToFirst();  
    				String img_url=cursor.getString(index);  
    				showToast(img_url);
    				break;
    			case CAMERA_REQUEST_CODE:
    				if (isSdcardExisting()) {
    					resizeImage(getImageUri());
    					
    					/*// 上传图片
    					String imgpath = getImageUri();
    					final BmobFile icon = new BmobFile(new File(imgpath));
    					icon.upload(this, new UploadFileListener() {
    						
    						@Override
    						public void onSuccess() {
    							// TODO Auto-generated method stub
    							Person person = new Person();
    							person.setIcon(icon);
    							person.save(MainActivity.this);
    							showToast("图片上传成功");
    						}
    						
    						@Override
    						public void onProgress(Integer arg0) {
    							// TODO Auto-generated method stub
    							
    						}
    						
    						@Override
    						public void onFailure(int arg0, String arg1) {
    							// TODO Auto-generated method stub
    							showToast("图片上传失败:"+arg1);
    						}
    					});*/
    				} else {
    					Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片!

    ", Toast.LENGTH_LONG).show(); } break; case RESIZE_REQUEST_CODE: if (data != null) { showResizeImage(data); } break; } } super.onActivityResult(requestCode, resultCode, data); } private void showToast(String msg){ Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } private boolean isSdcardExisting() {//推断SD卡是否存在 final String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } public void resizeImage(Uri uri) {//重塑图片大小 Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true");//能够裁剪 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 150); intent.putExtra("outputY", 150); intent.putExtra("return-data", true); startActivityForResult(intent, RESIZE_REQUEST_CODE); } private void showResizeImage(Intent data) {//显示图片 Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); Drawable drawable = new BitmapDrawable(photo); mImageHeader.setImageDrawable(drawable); } } private Uri getImageUri() {//获取路径 return Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)); } }


    将方法单列出来即:

                                    Uri originalUri=data.getData();//获取图片uri
    				resizeImage(originalUri);
    				//以下方法将获取的uri转为String类型哦!
    				String []imgs={MediaStore.Images.Media.DATA};//将图片URI转换成存储路径  
    				Cursor cursor=this.managedQuery(originalUri, imgs, null, null, null);  
    				int index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
    				cursor.moveToFirst();  
    				String img_url=cursor.getString(index);  
    				showToast(img_url);

    执行实例会出现例如以下错误:


    不懂英文的也大概能看懂,提示权限不足,我们加入例如以下权限:


    执行实例,顺利通过:


    Toast中显示出了图片的路径,话说获取这路径有什么用?请看下篇文章(二十九枪)。



    欢迎转载、点赞、关注,多谢大家的支持!

  • 相关阅读:
    sqlitespy sqlite 开发工具
    Visual Studio Installer问题:Your machine is busy installing a program other than Visual Studio
    k8s按照创建顺序展示pod
    tmux: open terminal failed: missing or unsuitable terminal: xterm256color
    ubuntu删除源
    docker打包容器
    docker中文乱码
    OpenPAI之进入dev box容器
    apt依赖出错问题修复
    ubuntu关闭swap
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/6994426.html
Copyright © 2020-2023  润新知