创建进度条与对话框,上传照片,格式化时间,相册拍照获取照片

创建进度条加载数据 对话框

 /**
     * 创建mProgressDialog
    */
    private void createProgressDialogTitle(String title) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
        }
        mProgressDialog.setTitle(title);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

隐藏进度条 对话框

    /**
     * 隐藏选择图片对话框
     */
    private void dismissmChooseIconDialog() {
        if (mChoosePicDialog != null) {
            mChoosePicDialog.dismiss();
        }
    }

显示Dialog的method

 /**
     *  显示Dialog的method
     *  */
    private void showDialog(String mess) {
        new AlertDialog.Builder(getActivity()).setTitle("Message").setMessage(mess)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }

隐藏Dialog的method

    /**
     * 隐藏mProgressDialog
     */
    private void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

创建需要的文件夹

  /**
     * 创建存储所需uri的文件夹
     *
     * @param uri
     */
    private void mkdirs(Uri uri) {
        String path = uri.getPath();
        File file = new File(path.substring(0, path.lastIndexOf("/")));
        if (!file.exists()) {
            boolean success = file.mkdirs();
            LogHelper.i(TAG,"---创建存储照片的文件夹success = " + success);
        }

    }

开启相册选择照片

点击进入

private void selectPicFromAlbum() {
  
        Intent intent = new Intent(Intent.ACTION_PICK, null);//从列表中选择某项并返回所有数据
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,//得到系统所有的图片
                "image/*");//图片的类型,image/*为所有类型图片
        startActivityForResult(intent, 0);
    }

接受相册返回的数据

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            if (requestCode == 0) {//相册返回

                Bitmap thumbnail;
                //返回选择相片的Uri
                Uri fullPhotoUri = data.getData();//content://media/external/images/media/3844 

        //getRealFilePath()这个方法将Uri转换成绝对路径String
                String realFilePath = BitmapUtils.getRealFilePath(getActivity(), fullPhotoUri);
                ProsItem item = mProsItems.get(mProsItems.size() - 1);
          
          //图片路径的修改与命名
                 mCurFromCamare = Uri.parse("file://" + Constants.BZ_CAM_PATH + "/"
                                + "bzzbz_" + "o" + ((RwxqActivity) getActivity()).mOrderId + "_s" + item.getServiceId()//+ item.getOrderId()
                                + "_e" + uid + "_f" + item.getFlowId() + "_t" + System.currentTimeMillis() + "_g" + ".jpg");


                String path = mCurFromCamare.getPath();
                //对图片进行压缩命名存储到指定的路径path
                String ImageUrl = BitmapUtils.compressImage(realFilePath, path, 50);
    
                //-fullPhotoUri----content://media/external/images/media/3844------>>>>>/storage/emulated/0/Pictures/Screenshots/S61101-153152.jpg
                // ------>>>>>/storage/emulated/0/ServerHelp/bzbz/camera/bzzbz_o48_s139_e4_f1_t1479002629947_g.jpg
           
                        thumbnail = BitmapHelper.getThumbnail(getActivity(), fullPhotoUri,
                                60 * (int) Constants.DENSITY, 60 * (int) Constants.DENSITY);
                       imagView.setBackgroundDrawable(new BitmapDrawable(thumbnail));
             
                        progressAdapter.notifyDataSetChanged();

            }
        }

对图片进行压缩命名存储到指定的路径path

/**
     * 对图片进行压缩命名存储到指定的路径targetPath
     * @param filePath
     * @param targetPath
     * @param quality
     * @return
     */
    public static String compressImage(String filePath, String targetPath, int quality)  {
        Bitmap bm = getSmallBitmap(filePath);//获取一定尺寸的图片
        int degree = readPictureDegree(filePath);//获取相片拍摄角度
        if(degree!=0){//旋转照片角度,防止头像横着显示
            bm=rotateBitmap(bm,degree);
        }
        File outputFile=new File(targetPath);
        try {
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
                //outputFile.createNewFile();
            }else{
                outputFile.delete();
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
        }catch (Exception e){}
        return outputFile.getPath();
    }

将图片路径Uri所表示的图片转换成指定大小的照片显示出来

 /**
     * Creates a thumbnail of requested size by doing a first sampled decoding of the bitmap to optimize memory
     * 将图片路径Uri所表示的图片转换成指定大小的照片显示出来
     */
    public static Bitmap getThumbnail(Context mContext, Uri uri, int reqWidth, int reqHeight) {
        Bitmap srcBmp = BitmapUtils.decodeSampledFromUri(mContext, uri, reqWidth, reqHeight);
        // If picture is smaller than required thumbnail
        Bitmap dstBmp;
        if (srcBmp.getWidth() < reqWidth && srcBmp.getHeight() < reqHeight) {
            dstBmp = ThumbnailUtils.extractThumbnail(srcBmp, reqWidth, reqHeight);
            // Otherwise the ratio between measures is calculated to fit requested thumbnail's one
        } else {
            int x = 0, y = 0, width = srcBmp.getWidth(), height = srcBmp.getHeight();
            float ratio = ((float) reqWidth / (float) reqHeight) * ((float) srcBmp.getHeight() / (float) srcBmp.getWidth());
            if (ratio < 1) {
                x = (int) (srcBmp.getWidth() - srcBmp.getWidth() * ratio) / 2;
                width = (int) (srcBmp.getWidth() * ratio);
            } else {
                y = (int) (srcBmp.getHeight() - srcBmp.getHeight() / ratio) / 2;
                height = (int) (srcBmp.getHeight() / ratio);
            }
            dstBmp = Bitmap.createBitmap(srcBmp, x, y, width, height);
        }
        return dstBmp;
    }

知道图片路径 Uri 转换为 String 路径

/**
     * Try to return the absolute file path from the given Uri
     *
     * @param context   知道图片路径 Uri 转换为 String 路径            TODO
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath( final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

调用相机拍照

点击拍照

mCurFromCamare = Uri.parse("file://" + Constants.BZ_PIC_PATH + "/"
+ "bzzbz_" + "o" + ((RwxqActivity) getActivity()).mOrderId + "_s" + item.getServiceId()//+ item.getOrderId()
+ "_e" + uid + "_f" + item.getFlowId() + "_t" + System.currentTimeMillis() + "_g" + ".jpg");
getPhotoFromCamera(mCurFromCamare, 2);

 /**
     * 调用相机拍照
     *
     * @param uri //照片需要储存的路径
     * @param requestCode
     */
    private void getPhotoFromCamera(Uri uri, int requestCode) {
        mkdirs(uri);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        LogHelper.i(TAG, "-------调用相机拍照-----------");
        startActivityForResult(intent, requestCode);//or TAKE_SMALL_PICTURE
    }

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
      if (requestCode == 2) {      //照相
                Bitmap thumbnail;
                mTempStrURL = mCurFromCamare.getPath();

                LogHelper.i(TAG, "--------照相返回------" + mTempStrURL + "-----");//string   /storage/emulated/0/ServerHelp/bzbz/img/bzzbz_o29_s114_e4_f1_t1478759682811.jpg
              
                        //mTempBitmap = BitmapFactory.decodeFile(imgPath);
                        thumbnail = BitmapHelper.getThumbnail(getActivity(), mCurFromCamare,
                                60 * (int) Constants.DENSITY, 60 * (int) Constants.DENSITY);

                        long bitmapsize = BitmapHelper.getBitmapsize(thumbnail);
                        int byteCount = thumbnail.getByteCount();
                        LogHelper.i(TAG, "-----" + byteCount);
                    


                        LogHelper.i(TAG, "-----" + bitmapsize + "-----" + byteCount);
          imageView.setBackgroundDrawable(new BitmapDrawable(thumbnail));
          }
  }
 }

上传照片到服务器

//上传照片至Server的方法picPath 图片真实路径
    private boolean uploadPicFile(String picPath) {

        String fName = picPath.trim();
        String newName = fName.substring(fName.lastIndexOf("/") + 1);
        LogHelper.i(TAG, "---" + newName);
        if (!newName.substring(0, 6).equals("bzzbz_")) {
            newName = mTempStrT;
        }
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            URL url = new URL(VolleyHelpApi.BZ_PIC_UPLOAD_Url);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
          /* 允许Input、Output,不使用Cache */
            con.setReadTimeout(10 * 10000000);
            con.setConnectTimeout(10 * 10000000);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
          /* 设置传送的method=POST */
            con.setRequestMethod("POST");
          /* setRequestProperty */
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
          /* 设置DataOutputStream */
            DataOutputStream ds =
                    new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " +
                    "name=\"img\";filename=\"" +
                    newName + "\"" + end);
            ds.writeBytes("Content-Type: application/octet-stream; charset=utf-8" + end);
            ds.writeBytes(end);

          /* 取得文件的FileInputStream */

            FileInputStream fStream = new FileInputStream(picPath);

          /* 设置每次写入1024bytes */
            int bufferSize = 1024 * 1024;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
          /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1) {
            /* 将资料写入DataOutputStream中 */
                LogHelper.i(TAG, length + "");
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
          /* close streams */
            fStream.close();
            ds.flush();
          /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
          /* 将Response显示于Dialog */
            //showDialog("上传成功"+b.toString().trim());
          /* 关闭DataOutputStream */
            ds.close();
            return true;
        } catch (Exception e) {
            LogHelper.e(TAG, e.toString());
            return false;
        }
    }

异步上传图片

private class UploadPicTask extends AsyncTask {
    @Override
    protected Boolean doInBackground(String... params) {
        //   boolean temp = uploadPicFile(mTempStrURL);
        String url = params[0];
        boolean temp = uploadPicFile(url);
        LogHelper.i(TAG, "------temp-------" + url);
        LogHelper.i(TAG, "------temp" + url);
        return temp;
    }

    @Override
    protected void onPostExecute(Boolean param) {
        LogHelper.i(TAG, "-----正在上传照片");
        LogHelper.i(TAG, "------temp" + param);
        if (param) {
            dismissProgressDialog();//取消
            showDialog("上传成功");
            App.getInstance().showToast("上传成功");
            LogHelper.i(TAG, "------上传成功");
        } else {
            dismissProgressDialog();//取消
            showDialog("上传失败");
            LogHelper.i(TAG, "------上传失败");
        }
    }
}

调用异步上传:mTempStrUR1 图片绝对路径

new UploadPicTask().execute(mTempStrUR1);

多张图片一起上传:mTempStrUR1,mTempStrUR2,mTempStrUR3

new UploadPicTask().execute(mTempStrUR1,mTempStrUR2,mTempStrUR3);

异步内获取多张图片路径:

 String url1 = params[0];
 String url2 = params[1];
 String url3 = params[2];

转换时间:毫秒值---->>>年月日 时分秒

/**
     * 转换时间
     *
     * @param time
     * @return
     */
    public String getDateTime(long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return sdf.format(date);
    }

通过时间秒毫秒数判断两个时间的间隔天数

   /**
     * 通过时间秒毫秒数判断两个时间的间隔天数
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(long date1,long date2)
    {
        // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // Date date = format.parse(dateStr); // dateStr="2008-1-1 1:21:28"   dateStr;---》Data对象
        // date.getTime();  //获得毫秒值      Data对象---》毫秒值

        int days = (int) ((date2 - date1) / (1000*3600*24));
        return days;
    }

你可能感兴趣的:(创建进度条与对话框,上传照片,格式化时间,相册拍照获取照片)