Android网页H5 Input选择相机和系统相册
需求:
网页h5的input选择相机和系统相册,并且返回压缩的图片到h5。
代码:
1、WebView代码
packagecom.zql.sdk; importandroid.app.Activity; importandroid.content.Context; importandroid.content.Intent; importandroid.content.pm.PackageManager; importandroid.net.Uri; importandroid.os.Build; importandroid.os.Bundle; importandroid.support.annotation.RequiresApi; importandroid.util.Log; importandroid.view.KeyEvent; importandroid.view.View; importandroid.view.Window; importandroid.webkit.JavascriptInterface; importandroid.webkit.ValueCallback; importandroid.webkit.WebChromeClient; importandroid.webkit.WebView; importandroid.webkit.WebViewClient; importandroid.widget.ImageView; importandroid.widget.TextView; importandroid.widget.Toast; importjava.io.IOException; /** *浏览器组件 *Createdbyzston2018/5/16. */ publicclassWebViewActivityextendsActivityimplementsView.OnClickListener{ publicstaticfinalStringINTENT_URL="intent_url";//请求连接 publicstaticfinalStringINTENT_PARAMS_STRING="intent_params_string";//请求参数字符串 publicstaticfinalStringINTENT_REQUEST_WAY="intent_request_way";//请求方式(POST/GET) privateWebViewwvShow; privateTextViewtv_back_title; privateTextViewtv_title; privateImageViewiv_back; privateTextViewtv_right; publicValueCallbackuploadMessage; privateValueCallback mUploadMessage; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 setContentView(R.layout.activity_web_view); tv_back_title=(TextView)findViewById(R.id.tv_back_title); tv_title=(TextView)findViewById(R.id.tv_title); iv_back=(ImageView)findViewById(R.id.iv_back); tv_right=(TextView)findViewById(R.id.tv_right); iv_back.setOnClickListener(this); tv_back_title.setOnClickListener(this); tv_right.setOnClickListener(this); initView(); initData(); } privatevoidinitData(){ StringintentUrl=getIntent().getStringExtra(INTENT_URL); StringintentParams=getIntent().getStringExtra(INTENT_PARAMS_STRING); StringintentRequestWay=getIntent().getStringExtra(INTENT_REQUEST_WAY); Log.e("WebView请求","连接:"+intentUrl+"....."+"参数:"+intentParams); if(intentRequestWay.equals("GET")){ wvShow.loadUrl(intentUrl+"?"+intentParams);//get请求 }elseif(intentRequestWay.equals("POST")){ wvShow.postUrl(intentUrl,intentParams.getBytes());//post请求 }else{ Toast.makeText(WebViewActivity.this,"请求方式参数错误",Toast.LENGTH_SHORT).show(); } ////wvShow.loadUrl("http://qas-gw.baofoo.com/merchant_page?CODE=6d8950fc495c2a63106ce45d2647e21aec04001b53b3d7aac2f8af3b3d24f84a6c51c92843814b270eb28ead11820178fad5a20a7278f042");//get请求 // //StringhtmlData="\n"+ //"\n"+ //"\n"+ //" \n"+ //" \n"+ //" \n"+ //" \n"+ //" 修改资料 \n"+ //"\n"+ //"\n"+ //"\n"+ //"\n"+ //" \n"+ //" \n"+ //" \n"+ //"
2、ImgUtil.java工具类
1)、选择相机方法(选择相机的方法还有额外的代码,具体点击这里)
2)、选择相册方法
3)、压缩图片方法
packagecom.zql.sdk; importandroid.Manifest; importandroid.app.Activity; importandroid.app.ActivityManager; importandroid.app.AlertDialog; importandroid.content.ContentResolver; importandroid.content.Context; importandroid.content.DialogInterface; importandroid.content.Intent; importandroid.content.pm.PackageManager; importandroid.database.Cursor; importandroid.graphics.Bitmap; importandroid.graphics.BitmapFactory; importandroid.net.Uri; importandroid.os.Build; importandroid.provider.MediaStore; importandroid.support.annotation.RequiresApi; importandroid.support.v4.app.ActivityCompat; importandroid.support.v4.content.ContextCompat; importandroid.support.v4.content.FileProvider; importandroid.util.Log; importandroid.widget.Toast; importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.File; importjava.io.FileNotFoundException; importjava.io.IOException; importjava.io.InputStream; importjava.util.ArrayList; importjava.util.List; /** *图片工具类 *Createdbyxiaoshuaion2018/8/17. */ publicclassImgUtil{ publicstaticfinalintTAKE_PHOTO=1;//拍照 publicstaticfinalintCHOOSE_PHOTO=2;//选择相册 publicstaticfinalintREQUEST_CODE_CAMERA=3;//相机权限请求 publicstaticfinalintREQUEST_CODE_ALBUM=4;//相册权限请求 publicstaticUriimageUri;//相机拍照图片保存地址 /** *选择图片,从图库、相机 * *@paramactivity上下文 */ publicstaticvoidchoicePhoto(finalActivityactivity){ //采用的是系统Dialog作为选择弹框 newAlertDialog.Builder(activity).setTitle("上传头像")//设置对话框标题 .setPositiveButton("拍照",newDialogInterface.OnClickListener(){//添加确定按钮 @RequiresApi(api=Build.VERSION_CODES.M) @Override publicvoidonClick(DialogInterfacedialog,intwhich){ ArrayListpermissions=newArrayList<>(); if(activity.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){ permissions.add(Manifest.permission.CAMERA); } if(permissions.size()==0){//有权限,跳转 //打开相机-兼容7.0 ImgUtil.openCamera(activity); }else{ activity.requestPermissions(permissions.toArray(newString[permissions.size()]),REQUEST_CODE_CAMERA); } //if(Build.VERSION.SDK_INT>=23){//检查相机权限 //ArrayList permissions=newArrayList<>(); //if(activity.checkSelfPermission(Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){ //permissions.add(Manifest.permission.CAMERA); //} // //if(permissions.size()==0){//有权限,跳转 ////打开相机-兼容7.0 //openCamera(activity); //}else{ //activity.requestPermissions(permissions.toArray(newString[permissions.size()]),REQUEST_CODE_CAMERA); //} //}else{ ////打开相机-兼容7.0 //openCamera(activity); //} } }). setNegativeButton("系统相册",newDialogInterface.OnClickListener(){ @Override publicvoidonClick(DialogInterfacedialog,intwhich){ //如果有权限申请,请在Activity中onRequestPermissionsResult权限返回里面重新调用openAlbum() if(ContextCompat.checkSelfPermission(activity,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(activity,newString[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE_ALBUM); }else{ openAlbum(activity); } } }).show();//在按键响应事件中显示此对话框 } /** *打开相机 *兼容7.0 * *@paramactivity */ publicstaticvoidopenCamera(Activityactivity){ //创建File对象,用于存储拍照后的图片 FileoutputImage=newFile(activity.getExternalCacheDir(),"output_image.jpg"); try{ if(outputImage.exists()){ outputImage.delete(); } outputImage.createNewFile(); }catch(IOExceptione){ e.printStackTrace(); } if(Build.VERSION.SDK_INT<24){ imageUri=Uri.fromFile(outputImage); }else{ //Android7.0系统开始使用本地真实的Uri路径不安全,使用FileProvider封装共享Uri //参数二:fileprovider绝对路径com.dyb.testcamerademo:项目包名 imageUri=FileProvider.getUriForFile(activity,"com.zql.sdk.fileprovider",outputImage); } //启动相机程序 Intentintent=newIntent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri); activity.startActivityForResult(intent,TAKE_PHOTO); } /** *打开图库 *@paramactivity */ publicstaticvoidopenAlbum(Activityactivity){ //调用系统图库的意图 IntentchoosePicIntent=newIntent(Intent.ACTION_PICK,null); choosePicIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*"); activity.startActivityForResult(choosePicIntent,CHOOSE_PHOTO); //打开系统默认的软件 //Intentintent=newIntent("android.intent.action.GET_CONTENT"); //intent.setType("image/*"); //activity.startActivityForResult(intent,CHOOSE_PHOTO);//打开相册 } /** *通过uri获取路径filepath *@paramcontext *@paramuri *@return */ publicstaticStringgetFilePath(finalContextcontext,finalUriuri){ if(null==uri)returnnull; finalStringscheme=uri.getScheme(); Stringdata=null; if(scheme==null) data=uri.getPath(); elseif(ContentResolver.SCHEME_FILE.equals(scheme)){ data=uri.getPath(); }elseif(ContentResolver.SCHEME_CONTENT.equals(scheme)){ Cursorcursor=context.getContentResolver().query(uri,newString[]{MediaStore.Images.ImageColumns.DATA},null,null,null); if(null!=cursor){ if(cursor.moveToFirst()){ intindex=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if(index>-1){ data=cursor.getString(index); } } cursor.close(); } } returndata; } /** *得到byte[] *LeanCloud上传文件是需要byte[]数组的 *这里对传入的图片Uri压缩,并转换为byte[]后返回 * *@paramactivity上下文 *@paramuri传入图片的Uri *@returnbyte[] */ publicstaticbyte[]getImgByteFromUri(Activityactivity,Uriuri)throwsIOException{ //先进行尺寸压缩 Bitmapbitmap=getBitmapFormUri(activity,uri); //再进行质量压缩 ByteArrayOutputStreamout=newByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100,out);//100表示不压缩,直接放到out里面 intoptions=90;//压缩比例 while(out.toByteArray().length/1024>200){//循环判断如果压缩后图片是否大于100kb,大于继续压缩 out.reset();//重置baos即清空baos bitmap.compress(Bitmap.CompressFormat.JPEG,options,out);//这里压缩options%,把压缩后的数据存放到baos中 options-=10;//每次都减少10 } Log.e("压缩-提交",out.toByteArray().length+""); byte[]bs=out.toByteArray();//转换为byte提交 returnbs; } publicstaticUrigetCompressUri(Activityactivity,Uriuri)throwsIOException{ //先进行尺寸压缩 Bitmapbitmap=getBitmapFormUri(activity,uri); UriuriCompress=Uri.parse(MediaStore.Images.Media.insertImage(activity.getContentResolver(),bitmap,null,null)); ////再进行质量压缩 //ByteArrayOutputStreamout=newByteArrayOutputStream(); //bitmap.compress(Bitmap.CompressFormat.PNG,100,out);//100表示不压缩,直接放到out里面 //intoptions=90;//压缩比例 //while(out.toByteArray().length/1024>200){//循环判断如果压缩后图片是否大于100kb,大于继续压缩 //out.reset();//重置baos即清空baos //bitmap.compress(Bitmap.CompressFormat.JPEG,options,out);//这里压缩options%,把压缩后的数据存放到baos中 //options-=10;//每次都减少10 //} //Log.e("压缩-提交",out.toByteArray().length+""); // //byte[]bs=out.toByteArray();//转换为byte提交 returnuriCompress; } /** *图片尺寸压缩 * *宽度高度不一样:依靠规定的高或宽其一最大值来做界限 *高度宽度一样:依照规定的宽度压缩 * *@paramuri */ publicstaticBitmapgetBitmapFormUri(Activityac,Uriuri)throwsFileNotFoundException,IOException{ InputStreaminput=ac.getContentResolver().openInputStream(uri); BitmapFactory.OptionsonlyBoundsOptions=newBitmapFactory.Options(); onlyBoundsOptions.inJustDecodeBounds=true; onlyBoundsOptions.inDither=true;//optional onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional BitmapFactory.decodeStream(input,null,onlyBoundsOptions); input.close(); intoriginalWidth=onlyBoundsOptions.outWidth; intoriginalHeight=onlyBoundsOptions.outHeight; if((originalWidth==-1)||(originalHeight==-1)) returnnull; //图片分辨率以750x450为标准 floathh=800f;//这里设置高度为750f floatww=800f;//这里设置宽度为450f floatsq=800f;//这里设置正方形为300f //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 Log.e("缩放",originalWidth+"..."+originalHeight); intbe=1;//be=1表示不缩放 if(originalWidth>originalHeight&&originalWidth>ww){//如果宽度大,根据宽度固定大小缩放 be=(int)(originalWidth/ww); }elseif(originalWidth hh){//如果高度高,根据宽度固定大小缩放 be=(int)(originalHeight/hh); }elseif(originalWidth==originalHeight&&originalWidth>sq){//如果高度和宽度一样,根据任意一边大小缩放 //be=(int)(originalHeight/sq); be=(int)(originalWidth/sq); } if(be<=0){//如果缩放比比1小,那么保持原图不缩放 be=1; } Log.e("缩放",be+""); //比例压缩 BitmapFactory.OptionsbitmapOptions=newBitmapFactory.Options(); bitmapOptions.inSampleSize=be;//设置缩放比例 bitmapOptions.inDither=true;//optional bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional input=ac.getContentResolver().openInputStream(uri); Bitmapbitmap=BitmapFactory.decodeStream(input,null,bitmapOptions); input.close(); returnbitmap;//再进行质量压缩 } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。