1. 程式人生 > >已解決: Android 解決相機拍照後或者選擇相簿翻轉的問題

已解決: Android 解決相機拍照後或者選擇相簿翻轉的問題

老規矩,先上效果圖(雖然說不是很形象吧):

1.首先我們獲取一下相機拍照後翻轉的角度

/**
     * 讀取照片exif資訊中的旋轉角度
     * @param path 照片路徑
     * @return角度
     */
    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;
    }

2.上面方法返回的就是旋轉的角度,然後我們將他按照角度在重新翻轉回來,返回的是Bitmap物件

    //旋將旋轉後的圖片翻轉
    public static Bitmap toturn(String path, int degree){
        Bitmap img = BitmapFactory.decodeFile(path);
        Matrix matrix = new Matrix();
        matrix.postRotate(degree); /*翻轉90度*/
        int width = img.getWidth();
        int height =img.getHeight();
        img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
        return img;
    }

3.我們要定義兩個變數為本地儲存的路徑

    private static final String SD_PATH = "/sdcard/dskqxt/pic/";
    private static final String IN_PATH = "/dskqxt/pic/";

4.然後隨機去獲取檔名字

/**
     * 隨機生產檔名
     * @return
     */
    private static String generateFileName() {
        return UUID.randomUUID().toString();
    }

5.最後將Biamap傳入這個方法,返回的就是本地儲存的路徑

    //將bitmap物件寫到本地路徑
    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }

6.現在我們直接就可以拿5返回的String型別的圖片路徑去操作就可以了