Android中獲取圖片進(jìn)行裁剪功能的細(xì)節(jié)分析

需求描述:
在很多時候煌贴,我們需要在APP中調(diào)用攝像頭拍攝相片或者選取本地相冊中的圖片進(jìn)行裁剪凳鬓,然后將裁剪后的圖片上傳至后臺服務(wù)器特咆。這方面有很多種實(shí)現(xiàn)方法影钉,所以不再羅列画髓,我只將我在這方面遇到的一些細(xì)節(jié)優(yōu)化的地方總結(jié)一下。


關(guān)于裁剪
用的是https://github.com/jdamcd/android-crop平委, above API-14奈虾。這個開源代碼將Itent封裝的比較好。

工具入口是:

public class Crop {
    public static final int REQUEST_CAPTURE = 1216;
    public static final int REQUEST_CROP = 6709;
    public static final int REQUEST_PICK = 9162;
    public static final int RESULT_ERROR = 404;

    static interface Extra {
        String ASPECT_X = "aspect_x";
        String ASPECT_Y = "aspect_y";
        String MAX_X = "max_x";
        String MAX_Y = "max_y";
        String ERROR = "error";
    }

    private Intent cropIntent;

    /**
     * Create a crop Intent builder with source and destination image Uris
     *
     * @param source Uri for image to crop
     * @param destination Uri for saving the cropped image
     */
    public static Crop of(Uri source, Uri destination) {
        return new Crop(source, destination);
    }

    private Crop(Uri source, Uri destination) {
        cropIntent = new Intent();
        cropIntent.setData(source);
        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, destination);
    }

    /**
     * Set fixed aspect ratio for crop area
     * 自定義寬高比
     * @param x Aspect X
     * @param y Aspect Y
     */
    public Crop withAspect(int x, int y) {
        cropIntent.putExtra(Extra.ASPECT_X, x);
        cropIntent.putExtra(Extra.ASPECT_Y, y);
        return this;
    }

    /**
     * Crop area with fixed 1:1 aspect ratio
     * 默認(rèn)一比一寬高比
     */
    public Crop asSquare() {
        cropIntent.putExtra(Extra.ASPECT_X, 1);
        cropIntent.putExtra(Extra.ASPECT_Y, 1);
        return this;
    }

    /**
     * Set maximum crop size
     *
     * @param width Max width
     * @param height Max height
     */
    public Crop withMaxSize(int width, int height) {
        cropIntent.putExtra(Extra.MAX_X, width);
        cropIntent.putExtra(Extra.MAX_Y, height);
        return this;
    }

    /**
     * Send the crop Intent from an Activity
     *
     * @param activity Activity to receive result
     */
    public void start(Activity activity) {
        start(activity, REQUEST_CROP);
    }

    /**
     * Send the crop Intent from an Activity with a custom requestCode
     *
     * @param activity Activity to receive result
     * @param requestCode requestCode for result
     */
    public void start(Activity activity, int requestCode) {
        activity.startActivityForResult(getIntent(activity), requestCode);
    }

    /**
     * Send the crop Intent from a Fragment
     *
     * @param context Context
     * @param fragment Fragment to receive result
     */
    public void start(Context context, Fragment fragment) {
        start(context, fragment, REQUEST_CROP);
    }

    /**
     * Send the crop Intent from a support library Fragment
     *
     * @param context Context
     * @param fragment Fragment to receive result
     */
    public void start(Context context, android.support.v4.app.Fragment fragment) {
        start(context, fragment, REQUEST_CROP);
    }

    /**
     * Send the crop Intent with a custom requestCode
     *
     * @param context Context
     * @param fragment Fragment to receive result
     * @param requestCode requestCode for result
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void start(Context context, Fragment fragment, int requestCode) {
        fragment.startActivityForResult(getIntent(context), requestCode);
    }

    /**
     * Send the crop Intent with a custom requestCode
     *
     * @param context Context
     * @param fragment Fragment to receive result
     * @param requestCode requestCode for result
     */
    public void start(Context context, android.support.v4.app.Fragment fragment, int requestCode) {
        fragment.startActivityForResult(getIntent(context), requestCode);
    }

    /**
     * Get Intent to start crop Activity
     *
     * @param context Context
     * @return Intent for CropImageActivity
     */
    public Intent getIntent(Context context) {
        cropIntent.setClass(context, CropImageActivity.class);
        return cropIntent;
    }

    /**
     * Retrieve URI for cropped image, as set in the Intent builder
     *
     * @param result Output Image URI
     */
    public static Uri getOutput(Intent result) {
        return result.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
    }

    /**
     * Retrieve error that caused crop to fail
     *
     * @param result Result Intent
     * @return Throwable handled in CropImageActivity
     */
    public static Throwable getError(Intent result) {
        return (Throwable) result.getSerializableExtra(Extra.ERROR);
    }

    /**
     * Utility to start an image picker
     *
     * @param activity Activity that will receive result
     */
    public static void pickImage(Activity activity) {
        pickImage(activity, REQUEST_PICK);
    }

    /**
     * Utility to start an image picker with request code
     *
     * @param activity Activity that will receive result
     * @param requestCode requestCode for result
     */
    public static void pickImage(Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*");
        try {
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, R.string.crop__pick_error, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 拍照獲取
     * @param activity
     * 需要在Intent中加入保存的SD卡路徑肆汹,否則onActivityResult中的得到的data圖片會壓縮很小
     */
    public static void pickCAPTURE(Activity activity, Uri path) {
        pickCAPTURE(activity, path, REQUEST_CAPTURE);
    }

    public static void pickCAPTURE(Activity activity, Uri path, int requestCode){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, path);
        try {
            activity.startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, R.string.crop__pick_error, Toast.LENGTH_SHORT).show();
        }
    }
}

當(dāng)然你也可以不用這個愚墓,用SDK本身的裁剪功能就可以了,同樣可以在onActivityResult中返回得到裁剪的圖片昂勉,而且可以自定義裁剪尺寸:

   private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 0.7);
        intent.putExtra("outputX", 1080);
        intent.putExtra("outputY", 756);
        intent.putExtra("return-data", true);
        getActivity().startActivityForResult(intent, 3);
    }

關(guān)于Uri浪册、Bitmap、以及保存路徑的轉(zhuǎn)換
提供一個工具類:

public class UtilsImageProcess {

    /**
     * 將得到的一個Bitmap保存到SD卡上岗照,得到一個URI地址
     */
    public static Uri saveBitmap(Bitmap bm) {
        //在SD卡上創(chuàng)建目錄
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/org.chenlijian.test");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }

        File img = new File(tmpDir.getAbsolutePath() + "test.png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 將得到的一個Bitmap保存到SD卡上村象,得到一個絕對路徑
     */
    public static String getPath(Bitmap bm) {
        //在SD卡上創(chuàng)建目錄
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/org.chenlijian.test");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }

        File img = new File(tmpDir.getAbsolutePath() + "/test.png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return img.getCanonicalPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 將圖庫中選取的圖片的URI轉(zhuǎn)化為URI
     */
    public static Uri convertUri(Uri uri, Context context) {
        InputStream is;
        try {
            is = context.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 在拍攝照片之前生成一個文件路徑Uri,保證拍出來的照片沒有被壓縮太小,用日期作為文件名攒至,確保唯一性
     */
    public static String getSavePath(){
        String saveDir = Environment.getExternalStorageDirectory() + "/org.chenlijian.test";
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdir();
        }
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String fileName = saveDir + "/" + formatter.format(date) + ".png";

        return fileName;
    }

    /**
     *  計(jì)算圖片的縮放值
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height/ (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     *  根據(jù)路徑獲得圖片并壓縮厚者,返回bitmap用于顯示
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        // 設(shè)置為true,畫質(zhì)更好一點(diǎn)迫吐,加載時間略長
        options.inPreferQualityOverSpeed = true;

        return BitmapFactory.decodeFile(filePath, options);
    }
}

關(guān)于拍照
通過拍照Intent库菲,然后onActivityResult得到圖片樣張,再對其進(jìn)行裁剪志膀。一般得到的圖片都很小熙宇,是因?yàn)榻?jīng)過了壓縮鳖擒,所以為了不讓其壓縮,需要在拍照Intent中加入保存的SD卡路徑烫止,然后在onActivityResult中得到的data為null蒋荚,我們直接獲取之前設(shè)置的SD卡路徑的圖片對其進(jìn)行裁剪即可。當(dāng)然不進(jìn)行壓縮圖片肯定很大馆蠕,之后我們可以根據(jù)自己的需求進(jìn)行壓縮期升。代碼上面已經(jīng)貼出來了。


示例

選擇獲取圖片方式:

        case R.id.btn_dialog_one_select_img:
            imgDialog.dismiss();
            path_name = UtilsImageProcess.getSavePath();
            Crop.pickCAPTURE(getActivity(), Uri.fromFile(new File(path_name)));
            break;

        case R.id.btn_dialog_two_select_img:
            imgDialog.dismiss();
            Crop.pickImage(getActivity());
            break;

返回處理結(jié)果:

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {

        if (requestCode == Crop.REQUEST_CAPTURE) {    //拍照得到URI

            Bitmap bitmap = UtilsImageProcess.getSmallBitmap(path_name);
            Uri source = UtilsImageProcess.saveBitmap(bitmap);
            beginCrop(source);

        } else if (requestCode == Crop.REQUEST_PICK && data != null) {    //從相冊中選取得到得到圖片

            Uri source = UtilsImageProcess.convertUri(data.getData(), getActivity());
            beginCrop(source);

        } else if (requestCode == Crop.REQUEST_CROP && data != null) {     //得到裁剪后的圖片

            handleCrop(data);
        }else {
            ((ActivityMain) getActivity()).dialogDismiss();
        }
    } 
}

//啟動裁剪Activity
private void beginCrop(Uri source) {
    Uri destination1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/org.chenlijian.test", "test_crop.png"));
    Crop.of(source, destination1).asSquare().start(getActivity());
}

//處理裁剪得到的圖片互躬,通過Volley上傳到服務(wù)器
private void handleCrop(Intent data) {
    Uri uri = Crop.getOutput(data);

    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
        String imagePath = UtilsImageProcess.getPath(bitmap);

        uploadTask = networkModule.arrangeUploadImg("arrangeUploadImg", imagePath);
        uploadTask.setId(0);
        uploadTask.setReceiver(this);
        uploadTask.pullTrigger();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

關(guān)于自定義封裝Volley接口播赁,上傳圖片或者文件,我會在下一篇文章中進(jìn)行分析吼渡。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末行拢,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子诞吱,更是在濱河造成了極大的恐慌,老刑警劉巖竭缝,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件房维,死亡現(xiàn)場離奇詭異,居然都是意外死亡抬纸,警方通過查閱死者的電腦和手機(jī)咙俩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來湿故,“玉大人阿趁,你說我怎么就攤上這事√持恚” “怎么了脖阵?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長墅茉。 經(jīng)常有香客問我命黔,道長,這世上最難降的妖魔是什么就斤? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任悍募,我火速辦了婚禮,結(jié)果婚禮上洋机,老公的妹妹穿的比我還像新娘坠宴。我一直安慰自己,他們只是感情好绷旗,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布喜鼓。 她就那樣靜靜地躺著副砍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪颠通。 梳的紋絲不亂的頭發(fā)上址晕,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天,我揣著相機(jī)與錄音顿锰,去河邊找鬼煮落。 笑死,一個胖子當(dāng)著我的面吹牛潮售,可吹牛的內(nèi)容都是我干的请契。 我是一名探鬼主播,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼牢撼,長吁一口氣:“原來是場噩夢啊……” “哼匙隔!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起熏版,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤纷责,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后撼短,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體再膳,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年曲横,在試婚紗的時候發(fā)現(xiàn)自己被綠了喂柒。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡禾嫉,死狀恐怖灾杰,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情熙参,我是刑警寧澤艳吠,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站孽椰,受9級特大地震影響讲竿,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜弄屡,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一题禀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧膀捷,春花似錦迈嘹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽融痛。三九已至,卻和暖如春神僵,著一層夾襖步出監(jiān)牢的瞬間雁刷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工保礼, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留沛励,地道東北人。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓炮障,卻偏偏與公主長得像目派,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子胁赢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評論 2 355

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