Android拍照或從本地選擇圖片上傳

彈出popueWindow選擇上傳方式

IMG_3546.JPG

彈出popueWindow的方法

private void showPopueWindow(){
        View popView = View.inflate(this,R.layout.popupwindow_camera_need,null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //獲取屏幕寬高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels*1/3;

        final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
        popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.setFocusable(true);
        //點擊外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takeCamera(RESULT_CAMERA_IMAGE);
                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕變?yōu)椴煌该?        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出現(xiàn)屏幕變?yōu)榘胪该?        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);

    }

popueWindow的布局文件

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout
        android:layout_margin="10dp"
        android:paddingBottom="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >

        <Button
            android:id="@+id/btn_pop_album"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:text="本地相冊"
            android:background="#ffff"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_pop_camera"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:text="相機拍攝"
            android:background="#ffff"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_pop_cancel"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_marginTop="10dp"
            android:background="#ffff"
            android:text="取消"
            android:textSize="18sp" />
    </LinearLayout>


</RelativeLayout>

調(diào)起照相機的方法

private void takeCamera(int num) {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            photoFile = createImageFile();
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
            }
        }

        startActivityForResult(takePictureIntent, num);//跳轉(zhuǎn)界面?zhèn)骰嘏恼账脭?shù)據(jù)
    }
private File createImageFile() {
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File image = null;
        try {
            image = File.createTempFile(
                    generateFileName(),  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

 public static String generateFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }

接收Intent傳遞回來的消息

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK ) {
            if (requestCode == RESULT_LOAD_IMAGE && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                final String picturePath = cursor.getString(columnIndex);
                upload(picturePath);
                cursor.close();
            }else if (requestCode == RESULT_CAMERA_IMAGE){

                SimpleTarget target = new SimpleTarget<Bitmap>() {

                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        upload(saveMyBitmap(resource).getAbsolutePath());
                    }

                    @Override
                    public void onLoadStarted(Drawable placeholder) {
                        super.onLoadStarted(placeholder);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);

                    }
                };

                Glide.with(RegisterUIActivity.this).load(mCurrentPhotoPath)
                        .asBitmap()
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .override(1080, 1920)//圖片壓縮
                        .centerCrop()
                        .dontAnimate()
                        .into(target);


            }
        }
    }


//將bitmap轉(zhuǎn)化為png格式
    public File saveMyBitmap(Bitmap mBitmap){
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File file = null;
        try {
            file = File.createTempFile(
                    UploadAccess.generateFileName(),  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );

            FileOutputStream out=new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  file;
    }

圖片上傳方法

 private void upload(String picturePath) {
        final ProgressDialog pb= new ProgressDialog(this);

        pb.setMessage("正在上傳");
        pb.setCancelable(false);
        pb.show();

        imageUpLoad(picturePath, new Response<FileUpload>() {

            @Override
            public void onSuccess(FileUpload response) {
                super.onSuccess(response);
                if (response.success) {
                    myFileId = response.fileID;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showShortToast("上傳成功");
                            pb.dismiss();
                        }
                    });
                }
            }

            @Override
            public void onFaile(String e) {
                super.onFaile(e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pb.dismiss();
                        ToastUtils.showShortToast("上傳失敗");
                    }
                });
            }
        });
    }

  public static void imageUpLoad(String localPath, final Response<FileUpload> callBack) {
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        OkHttpClient client = new OkHttpClient();


        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        File f = new File(localPath);
        builder.addFormDataPart("file", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));

        final MultipartBody requestBody = builder.build();
        //構(gòu)建請求
        final Request request = new Request.Builder()
                .url("http://  ")//地址
                .post(requestBody)//添加請求體
                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                callBack.onFaile(e.getMessage());
                System.out.println("上傳失敗:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                FileUpload resultBean = new Gson().fromJson(response.body().string(), FileUpload.class);
                callBack.onSuccess(resultBean);
            }
        });

    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末任岸,一起剝皮案震驚了整個濱河市再榄,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌享潜,老刑警劉巖困鸥,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異剑按,居然都是意外死亡疾就,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進(jìn)店門艺蝴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來猬腰,“玉大人,你說我怎么就攤上這事猜敢」煤桑” “怎么了癣亚?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵胜榔,是天一觀的道長。 經(jīng)常有香客問我趴拧,道長胯盯,這世上最難降的妖魔是什么懈费? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮博脑,結(jié)果婚禮上楞捂,老公的妹妹穿的比我還像新娘。我一直安慰自己趋厉,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布胶坠。 她就那樣靜靜地躺著君账,像睡著了一般。 火紅的嫁衣襯著肌膚如雪沈善。 梳的紋絲不亂的頭發(fā)上乡数,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天椭蹄,我揣著相機與錄音,去河邊找鬼净赴。 笑死绳矩,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的玖翅。 我是一名探鬼主播翼馆,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼金度!你這毒婦竟也來了应媚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤猜极,失蹤者是張志新(化名)和其女友劉穎中姜,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體跟伏,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡丢胚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了受扳。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片携龟。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖辞色,靈堂內(nèi)的尸體忽然破棺而出骨宠,到底是詐尸還是另有隱情,我是刑警寧澤相满,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布层亿,位于F島的核電站,受9級特大地震影響立美,放射性物質(zhì)發(fā)生泄漏匿又。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一建蹄、第九天 我趴在偏房一處隱蔽的房頂上張望碌更。 院中可真熱鬧,春花似錦洞慎、人聲如沸痛单。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽旭绒。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間挥吵,已是汗流浹背重父。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留忽匈,地道東北人房午。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像丹允,于是被迫代替她去往敵國和親郭厌。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容