webview 调用照相机,图库上传文件

       写给自己看

            public static final int FILECHOOSER_RESULTCODE = 1;
  private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE+1;
  private static final int REQ_CHOOSE = REQ_CAMERA+1;
  ValueCallback<Uri[]> mFilePathCallback;
  private class MyWebChromeClient extends WebChromeClient {

     public boolean onShowFileChooser(
           WebView webView, ValueCallback<Uri[]> filePathCallback,
           WebChromeClient.FileChooserParams fileChooserParams) {
        if (mFilePathCallback != null) return true;
        mFilePathCallback = filePathCallback;
        selectImage();
        return true;
     }
     // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {  
              if (mUploadMessage != null) return;
              mUploadMessage = uploadMsg;   
              selectImage();
//               Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//               i.addCategory(Intent.CATEGORY_OPENABLE);
//               i.setType("*/*");
//                   startActivityForResult( Intent.createChooser( i, "File Chooser" ), FILECHOOSER_RESULTCODE );
          }
           // For Android < 3.0
         public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                 openFileChooser( uploadMsg, "" );
         }
          // For Android  > 4.1.1
         public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooser(uploadMsg, acceptType);
         }

  }
  
  /**
   * 检查SD卡是否存在
   * 
   * @return
   */
  public final boolean checkSDcard() {
     boolean flag = Environment.getExternalStorageState().equals(
           Environment.MEDIA_MOUNTED);
     if (!flag) {
        Toast.makeText(this, "请插入手机存储卡再使用本功能",Toast.LENGTH_SHORT).show();
     }
     return flag;
  }
  String compressPath = "";
  
  protected final void selectImage() {
     if (!checkSDcard())
        return;
     String[] selectPicTypeStr = { "相机","图库" };
     AlertDialog alertDialog = new AlertDialog.Builder(this)
           .setItems(selectPicTypeStr,
                 new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                   int which) {
                       switch (which) {
                          // 相机拍摄
                          case 0:
                             openCarcme();
                             break;
                          // 手机相册
                          case 1:
                             chosePic();
                             break;
                          default:
                             break;
                       }
                       compressPath = Environment
                             .getExternalStorageDirectory()
                             .getPath()
                             + "/fuiou_wmp/temp";
                       new File(compressPath).mkdirs();
                       compressPath = compressPath + File.separator
                             + "compress.jpg";
                    }
                 }).setOnCancelListener(new DialogInterface.OnCancelListener() {
              @Override
              public void onCancel(DialogInterface dialogInterface) {
                 if(mFilePathCallback != null){
                    Uri[] uris = new Uri[1];
                    uris[0] = Uri.parse("");
                    mFilePathCallback.onReceiveValue(uris);
                    mFilePathCallback=null;
                 }else {
                    mUploadMessage.onReceiveValue(Uri.parse(""));
                    mUploadMessage=null;
                 }
              }
           }).show();
  }
  
  String imagePaths;
  Uri  cameraUri;
  /**
   * 打开照相机
   */
  private void openCarcme() {
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

     imagePaths = Environment.getExternalStorageDirectory().getPath()
           + "/fuiou_wmp/temp/"
           + (System.currentTimeMillis() + ".jpg");
     // 必须确保文件夹路径存在,否则拍照后无法完成回调
     File vFile = new File(imagePaths);
     if (!vFile.exists()) {
        File vDirPath = vFile.getParentFile();
        vDirPath.mkdirs();
     } else {
        if (vFile.exists()) {
           vFile.delete();
        }
     }
     cameraUri = Uri.fromFile(vFile);
     intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
     startActivityForResult(intent, REQ_CAMERA);
  }

  /**
   * 拍照结束后
   */
  private void afterOpenCamera() {
     File f = new File(imagePaths);
     addImageGallery(f);
  }

  /** 解决拍照后在相册中找不到的问题 */
  private void addImageGallery(File file) {
     ContentValues values = new ContentValues();
     values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
     values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
     getContentResolver().insert(
           MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
  }

  /**
   * 本地相册选择图片
   */
  private void chosePic() {
  //删除文件
    // FileUtils.delFile(compressPath);
   /*  Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
     String IMAGE_UNSPECIFIED = "image/*";
     innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
     Intent wrapperIntent = Intent.createChooser(innerIntent, null);
     startActivityForResult(wrapperIntent, REQ_CHOOSE);*/
     Intent intent  = new Intent(MywebviewTestActivity.this,TukuActivity.class);
     startActivityForResult(intent, REQ_CHOOSE);
  }

  /**
   * 选择照片后结束
   * 
   * @param data
   */
  private Uri[] afterChosePic(Intent data) {

     // 获取图片的路径:
    // String[] proj = { MediaStore.Images.Media.DATA };
     // 好像是android多媒体数据库的封装接口,具体的看Android文档
    // Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
    /* if(cursor == null ){
        Toast.makeText(this, "上传的图片仅支持png或jpg格式",Toast.LENGTH_SHORT).show();
        return null;
     }*/
     // 按我个人理解 这个是获得用户选择的图片的索引值
    // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     // 将光标移至开头 ,这个很重要,不小心很容易引起越界
    // cursor.moveToFirst();
     // 最后根据索引值获取图片路径
  //这个是 吧图片路径才分出来
     String Mypath = data.getStringExtra("result");
     String[] Path = Mypath.split("%26");
     Uri[] iMUri=new Uri[Path.length];
   
     for(int i =0;i<Path.length;i++){
     File newFile = FileUtils.compressFile(Path[i],Environment
                      .getExternalStorageDirectory()
                      .getPath()
                      + "/fuiou_wmp/temp" + File.separator+"compress"+i+".jpg");
     
     iMUri[i]=Uri.fromFile(newFile);
     }
     
    // if(path != null && (path.endsWith(".png")||path.endsWith(".PNG")||path.endsWith(".jpg")||path.endsWith(".JPG"))){
    // File newFile=new  File(path);
    //把它做成文件组
     
        return iMUri;
  }





  /**
   * 返回文件选择      
   */
  @Override
  protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
   if (requestCode == FILECHOOSER_RESULTCODE) {
      if (null == mUploadMessage)
         return;
      Uri result = intent == null || resultCode != RESULT_OK ? null
            : intent.getData();
      mUploadMessage.onReceiveValue(result);
      mUploadMessage = null;
   }

     if (null == mUploadMessage && mFilePathCallback == null)
        return;
     Uri uri = null;
     File file=null;
     Uri[] myUris=null;
if(cameraUri!=null){
     file = new File(cameraUri.getPath());
     if(!file.exists()){
        cameraUri = Uri.parse("");
     }
     } 
    
    
     if(requestCode == REQ_CAMERA &&mFilePathCallback != null){
        afterOpenCamera();
        uri = cameraUri;
        Uri[] uris = new Uri[1];
        uris[0] = uri;
        mFilePathCallback.onReceiveValue(uris);
     }else if(requestCode == REQ_CHOOSE && mFilePathCallback != null){
     
     myUris = afterChosePic(intent);
     mFilePathCallback.onReceiveValue(myUris);
     }
     /*if(){
     }else {
        mUploadMessage.onReceiveValue(uri);
     }*/
     mFilePathCallback = null;
     mUploadMessage = null;
     super.onActivityResult(requestCode, resultCode, intent);
  }
  
  public boolean onKeyDown(int keyCode, KeyEvent event) {
     if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {  
        mWebView.goBack();  
        return true;  
     }else{
             finish();
     }
     return super.onKeyDown(keyCode, event);  
     }
这个地方我就不做 图库了 写这个项目 是用的EC  如果是AS的话  图库的效果  更炫  自己去依赖第三方就可以了,其实主要的方法 就是把路径放到uri 里面去就可以了

下边是压缩文件工具类:
public class FileUtils {
/** 
     * 把图片压缩到200K 
     *  
     * @param oldpath 
     *            压缩前的图片路径 
     * @param newPath 
     *            压缩后的图片路径 
     * @return 
     */  
    /** 
     * 把图片压缩到200K 
     *  
     * @param oldpath 
     *            压缩前的图片路径 
     * @param newPath 
     *            压缩后的图片路径 
     * @return 
     */  
    public static File compressFile(String oldpath, String newPath) {  
        Bitmap compressBitmap = FileUtils.decodeFile(oldpath);  
        Bitmap newBitmap = ratingImage(oldpath, compressBitmap);  
        ByteArrayOutputStream os = new ByteArrayOutputStream();  
        newBitmap.compress(CompressFormat.PNG, 100, os);  
        byte[] bytes = os.toByteArray();  
          
        File file = null ;  
        try {  
            file = FileUtils.getFileFromBytes(bytes, newPath);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            if(newBitmap != null ){  
                if(!newBitmap.isRecycled()){  
                    newBitmap.recycle();  
                }  
                newBitmap  = null;  
            }  
            if(compressBitmap != null ){  
                if(!compressBitmap.isRecycled()){  
                    compressBitmap.recycle();  
                }  
                compressBitmap  = null;  
            }  
        }  
        return file;  
    }  
      
    private static Bitmap ratingImage(String filePath,Bitmap bitmap){  
        int degree = readPictureDegree(filePath);  
        return rotaingImageView(degree, bitmap);  
    }  
      
    /** 
     *  旋转图片 
     * @param angle 
     * @param bitmap 
     * @return Bitmap 
     */  
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {  
        //旋转图片 动作  
        Matrix matrix = new Matrix();;  
        matrix.postRotate(angle);  
        System.out.println("angle2=" + angle);  
        // 创建新的图片  
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
        return resizedBitmap;  
    }  
      
    /** 
     * 读取图片属性:旋转的角度 
     * @param path 图片绝对路径 
     * @return degree旋转的角度 
     */  
    public static int readPictureDegree(String path) {  
        int degree  = 0;  
        try {  
                ExifInterface exifInterface = new ExifInterface(path);  
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);  
                switch (orientation) {  
                case ExifInterface.ORIENTATION_ROTATE_90:  
                        degree = 90;  
                        break;  
                case ExifInterface.ORIENTATION_ROTATE_180:  
                        degree = 180;  
                        break;  
                case ExifInterface.ORIENTATION_ROTATE_270:  
                        degree = 270;  
                        break;  
                }  
        } catch (IOException e) {  
                e.printStackTrace();  
        }  
        return degree;  
    }  
  
    /** 
     * 把字节数组保存为一个文件 
     *  
     * @param b 
     * @param outputFile 
     * @return 
     */  
    public static File getFileFromBytes(byte[] b, String outputFile) {  
        File ret = null;  
        BufferedOutputStream stream = null;  
        try {  
            ret = new File(outputFile);  
            FileOutputStream fstream = new FileOutputStream(ret);  
            stream = new BufferedOutputStream(fstream);  
            stream.write(b);  
        } catch (Exception e) {  
            // log.error("helper:get file from byte process error!");  
            e.printStackTrace();  
        } finally {  
            if (stream != null) {  
                try {  
                    stream.close();  
                } catch (IOException e) {  
                    // log.error("helper:get file from byte process error!");  
                    e.printStackTrace();  
                }  
            }  
        }  
        return ret;  
    }  
  
    /** 
     * 图片压缩 
     *  
     * @param fPath 
     * @return 
     */  
    public static Bitmap decodeFile(String fPath) {  
        BitmapFactory.Options opts = new BitmapFactory.Options();  
        opts.inJustDecodeBounds = true;  
        opts.inDither = false; // Disable Dithering mode  
        opts.inPurgeable = true; // Tell to gc that whether it needs free  
        opts.inInputShareable = true; // Which kind of reference will be used to  
        BitmapFactory.decodeFile(fPath, opts);  
        final int REQUIRED_SIZE = 200;  
        int scale = 1;  
        if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE) {  
            final int heightRatio = Math.round((float) opts.outHeight  
                    / (float) REQUIRED_SIZE);  
            final int widthRatio = Math.round((float) opts.outWidth  
                    / (float) REQUIRED_SIZE);  
            scale = heightRatio < widthRatio ? heightRatio : widthRatio;//  
        }  
        Log.i("scale", "scal ="+ scale);  
        opts.inJustDecodeBounds = false;  
        opts.inSampleSize = scale;  
        Bitmap bm = BitmapFactory.decodeFile(fPath, opts).copy(Config.ARGB_8888, false);  
        return bm;  
    }  
      
      
      
    /** 
     * 创建目录 
     * @param path 
     */  
    public static void setMkdir(String path)  
    {  
        File file = new File(path);  
        if(!file.exists())  
        {  
            file.mkdirs();  
            Log.e("file", "目录不存在  创建目录    ");  
        }else{  
            Log.e("file", "目录存在");  
        }  
    }  
      
    /** 
     * 获取目录名称 
     * @param url 
     * @return FileName 
     */  
    public static String getFileName(String url)  
    {  
        int lastIndexStart = url.lastIndexOf("/");  
        if(lastIndexStart!=-1)  
        {  
            return url.substring(lastIndexStart+1, url.length());  
        }else{  
            return null;  
        }  
    }  
      
    /** 
     * 删除该目录下的文件 
     *  
     * @param path 
     */  
    public static void delFile(String path) {  
        if (!TextUtils.isEmpty(path)) {  
            File file = new File(path);  
            if (file.exists()) {  
                file.delete();  
            }  
        }  
    }  
}








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值