Android實現上傳圖片功能

本文實例為大傢分享瞭Android實現上傳圖片功能的具體代碼,供大傢參考,具體內容如下

設定拍照返回的圖片路徑

 /**
     * 設定拍照返回的圖片路徑
     * @param image 圖片路徑
     * @param i 約定值
     */
    protected void image(String image, int i) {
        //創建file對象,用於存儲拍照後的圖片,這也是拍照成功後的照片路徑
        outputImage = new File(getExternalCacheDir(),image);
        try {
            //判斷文件是否存在,存在刪除,不存在創建
            if (outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //相機拍照返回圖片路徑
        Uri photoUri;
        //判斷當前Android版本
        if(Build.VERSION.SDK_INT>=24){
            photoUri = FileProvider.getUriForFile(TextActivity.this,"包名.FileProvider",outputImage);
        }else {
            photoUri = Uri.fromFile(outputImage);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, i);
    }

調用系統相機拍照接受返回的圖片路徑

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == IMAGE_Y) {
                getImageView(binding.imageY,"0");
            }
            if (requestCode == IMAGE_Q) {
                getImageView(binding.imageQ,"1");
            }
        }

    }

上傳圖片

 /**
     * 上傳圖片
     * @param view 圖片展示 view
     */
    protected void getImageView(@NotNull ImageView view, String type) {
        Bitmap photo = BitmapFactory.decodeFile(outputImage.getAbsolutePath());
        view.setImageBitmap(photo);
        int direction = 0;
        try {
            ExifInterface exif = new ExifInterface(String.valueOf(outputImage));
            direction = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Matrix matrix = new Matrix();
        Uri uri = Uri.fromFile(outputImage);
        String f = uri.getPath();
        Bitmap b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
        switch (direction) {
            case 1:
                Log.d("圖片方向","頂部,左側(水平/正常)");
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
                break;
            case 2:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),0);
                Log.d("圖片方向","頂部,右側(水平鏡像)");
                break;
            case 3:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),180);
                Log.d("圖片方向","底部,右側(旋轉180)");
                break;
            case 4:
                matrix.postScale(1, -1);
                b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
                Log.d("圖片方向","底部,左側(垂直鏡像)");
                break;
            case 5:
                matrix.postScale(-1, 1);
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);
                b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
                Log.d("圖片方向","左側,頂部(水平鏡像並順時針旋轉270)");
                break;
            case 6:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);
                Log.d("圖片方向","右側,頂部(順時針旋轉90)");
                break;
            case 7:
                matrix.postScale(-1, 1);
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),90);
                b = Bitmap.createBitmap(b,0,0,900,1200,matrix,true);
                Log.d("圖片方向","右側,底部(水平鏡像,順時針旋轉90度)");
                break;
            case 8:
                b = rotateBitmap(getBitmapFromUrl(f,900,1200),270);
                Log.d("圖片方向","左側,底部(順時針旋轉270)");
                break;
            default:
                break;
        }
        try {
            File files = new File(new URI(uri.toString()));
            saveBitmap(b,files);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        try {
            String file = uploadImage(networkApi.getFormal() + "setImage", uri.getPath(), code, userId);
            TextBase.FileInfo fileInfo = new TextBase.FileInfo();
            fileInfo.setFilePath(file);
            mFileInfos.add(fileInfo);
            model.load(file,type);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }
 /**
     * 上傳圖片
     * @param url 上傳接口路徑
     * @param imagePath 圖片路徑
     * @param code 唯一標識
     * @return 服務器圖片的路徑
     * @throws IOException
     * @throws JSONException
     */
    public static String uploadImage(String url, String imagePath, String code, String userId) throws IOException, JSONException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Log.d("imagePath", imagePath);
        File file = new File(imagePath);
        RequestBody image = RequestBody.create(MediaType.parse("image/jpg"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", imagePath, image)
                .addFormDataPart("fileOid", code)
                .addFormDataPart("userId", userId)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization",令牌)
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        JSONObject jsonObject = new JSONObject(response.body().string());
        return jsonObject.optString("msg");
}

其他工具類

/**
     * 壓縮圖片的方法
     * @param url
     * @param width
     * @param height
     * @return
 */
    public static Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 設置瞭此屬性一定要記得將值設置為false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 防止OOM發生
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;
        // 按照固定寬高進行縮放
        if(mWidth <= mHeight) {
            scaleWidth = (float) (width/mWidth);
            scaleHeight = (float) (height/mHeight);
        } else {
            scaleWidth = (float) (height/mWidth);
            scaleHeight = (float) (width/mHeight);
        }
        // 按照固定大小對圖片進行縮放
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 用完瞭記得回收
        bitmap.recycle();
        return newBitmap;
    }

    /**
     * Android保存Bitmap到文件
     * @param bitmap
     * @param file
     * @return
     */
    public static boolean saveBitmap(Bitmap bitmap, File file) {
        if (bitmap == null)
            return false;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 旋轉圖片
     * @param bitmap 圖片
     * @param rotate 角度
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
        if (bitmap == null)
            return null;

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix mtx = new Matrix();
        mtx.postRotate(rotate);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: