HDL_Widget Android和iOS精简版的库,去掉高德SDK,和iOS裁剪方法
JLChen
2021-01-08 07a4e46efd0d180f881a9761c6f737e5d1c47848
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package com.hdl.widget.cropimage;
 
 
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.Window;
import android.view.WindowManager;
import com.hdl.widget.HDLUtlisXM;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
 
 
 
 
public class HDLCropImageActivity extends CheckPermissionsCropImageActivity {
 
 
    private static final int ACTION_TYPE_PHOTO = 0;
    private final int CAMERA = 101;
    private final int ALBUM = 102;
    private final int CUPREQUEST = 103;
 
    private String mPicturePath = "hdl_headPicture";
    private File mOutImage;
    private Uri mImageUri;
    private Uri mUritempFile;
//    private Bitmap imageBitmap;
    private String mCropPicturePath;
    private String mPictureName = "hdl_headPicture";
    private int mRATIO_X = 1;
    private int mRATIO_Y = 1;
    private int mOutputY = 200;
 
 
    public interface OnCropImageeCallback {
        void OnSaveCallback(String picturePath);
    }
    /**
     * 2.接口实现回调
     */
    public static OnCropImageeCallback mOnCropImageeCallback;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        setContentView(R.layout.hdl_widget_activity_crop_image);
 
//        Bundle mExtras = getIntent().getExtras();
//        if(mExtras != null) {
//            CropImageBean mCropImageBean =  (CropImageBean) getIntent().getSerializableExtra("CropImageBean");
//            if(mCropImageBean != null){
//                type = mCropImageBean.getTypeID();
//                String mmPictureName =  mCropImageBean.getPictureName();
//                if(!TextUtils.isEmpty(mmPictureName)){
//                    mPictureName = mmPictureName;
//                }
//                mRATIO_X  = mCropImageBean.getRATIO_X();
//                mRATIO_Y  = mCropImageBean.getRATIO_Y();
//                mOutputY =   mCropImageBean.getOutputY();
//                if(mRATIO_X <= 0){
//                    mRATIO_X = 1;
//                }
//                if(mRATIO_Y <= 0){
//                    mRATIO_Y = 1;
//                }
//                if(mOutputY <= 0 || mOutputY > 400){
//                    mRATIO_Y = 300;
//                }
//
//            }
//        }
 
 
 
        Bundle extras = getIntent().getExtras();
        int type = 0;
        if(extras != null){
            type = extras.getInt(HDLUtlisXM.CROP_TYPE_KEY);
            String mmPictureName =  extras.getString(HDLUtlisXM.CROP_NAME_KEY);
            if(!TextUtils.isEmpty(mmPictureName)){
                mPictureName = mmPictureName;
            }
            mRATIO_X  = extras.getInt(HDLUtlisXM.CROP_RATIO_X_KEY);
            mRATIO_Y  = extras.getInt(HDLUtlisXM.CROP_RATIO_Y_KEY);
            mOutputY =  extras.getInt(HDLUtlisXM.CROP_OUTPUT_Y_KEY);
            if(mRATIO_X <= 0){
                mRATIO_X = 1;
            }
            if(mRATIO_Y <= 0){
                mRATIO_Y = 1;
            }
            if(mOutputY <= 0 || mOutputY > 200){
                mOutputY = 200;
            }
 
        }
 
 
 
 
        if(type == CAMERA){
            setMobilePhones();
        }else {
            setLocalPhoto();
        }
 
 
 
    }
 
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mOnCropImageeCallback) {
            mOnCropImageeCallback = null;
        }
    }
    
    /**
     * 相册
     */
    private void setLocalPhoto() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, ALBUM);
    }
 
    /**
     * 拍照
     */
    private void setMobilePhones() {
        //获得项目缓存路径
        String sdPath = getExternalCacheDir().getPath();
        //根据时间随机生成图片名
        String photoName = new DateFormat().format("yyyyMMddhhmmss",
                Calendar.getInstance(Locale.CHINA)) + ".jpg";
        mPicturePath = sdPath + "/" + photoName;
        mOutImage = new File(mPicturePath);
        //如果是7.0以上 那么就把uir包装
        if (Build.VERSION.SDK_INT >= 24) {
            mImageUri = FileProvider.getUriForFile(this, HDLUtlisXM.MAuthority_NAME , mOutImage);
        } else {
            //否则就用老系统的默认模式
            mImageUri = Uri.fromFile(mOutImage);
        }
        //启动相机
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        startActivityForResult(intent, CAMERA);
    }
 
 
    /**
     * 选择图片后的回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            finishActivity();
            return;
        }
        switch (requestCode) {
 
            // 裁剪相机照片
            case CAMERA:
                setCropPhoto();
                break;
            //裁剪本地相册
            case ALBUM:
                Uri data1 = data.getData();
                if (data1 != null) {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        mPicturePath = data1.toString();
                    } else {
                        mPicturePath = data1.getPath();
                    }
                    // Uri --> Path
                    if (mPicturePath.contains("content://")) {
                        mPicturePath = getFilePathFromContentUri(data1, getContentResolver());
                    }
                    mOutImage = new File(mPicturePath);
                    setCropPhoto();
                }else {
                    finishActivity();
                }
                break;
 
            //裁剪完成
            case CUPREQUEST:
                if (data == null) {
                    finishActivity();
                    return;
                }
                Bundle extras = data.getExtras();
 
                if (Build.MANUFACTURER.contains("Xiaomi")) {
                    if (mUritempFile != null) {
                        mCropPicturePath = mUritempFile.getPath();
                    } else {
                        mCropPicturePath = "";
                    }
                } else {
                    if (extras != null) {
                        Bitmap photo = extras.getParcelable("data");
                        mCropPicturePath = saveImage(mPictureName ,photo);
                    } else {
                        mCropPicturePath = "";
                    }
                }
 
                finishActivity();
//                if (!TextUtils.isEmpty(mCropPicturePath)) {
//                    imageBitmap = BitmapFactory.decodeFile(s);
//                }
                break;
            default:
                finishActivity();
                break;
        }
    }
 
    private void setCropPhoto() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //如果是7.0剪裁图片 同理 需要把uri包装
            //通过FileProvider创建一个content类型的Uri
            Uri inputUri = FileProvider.getUriForFile(this,
                    HDLUtlisXM.MAuthority_NAME , mOutImage);
 
            startPhotoZoom(inputUri);//设置输入类型
        } else {
            Uri inputUri = Uri.fromFile(mOutImage);
            startPhotoZoom(inputUri);
        }
    }
 
    //裁剪
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //sdk>=24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //去除默认的人脸识别,否则和剪裁匡重叠
            intent.putExtra("noFaceDetection", false);
 
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 
        }
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 宽高的比例
        //华为特殊处理 不然会显示圆
        if (Build.MANUFACTURER.contains("HUAWEI")) {
            if(mRATIO_X == mRATIO_Y) {
                intent.putExtra("aspectX", 9998);
                intent.putExtra("aspectY", 9999);
            }else {
                intent.putExtra("aspectX", mRATIO_X);
                intent.putExtra("aspectY", mRATIO_Y);
            }
        } else {
            intent.putExtra("aspectX", mRATIO_X);
            intent.putExtra("aspectY", mRATIO_Y);
        }
        // outputX outputY 是裁剪图片宽高
        float mRATIO = ((float)mRATIO_X) /((float)mRATIO_Y);
        int outputX = (int)((float)mOutputY * mRATIO);
        intent.putExtra("outputX",outputX);
        intent.putExtra("outputY", mOutputY);
        //miui系统 特殊处理 return-data的方式只适用于小图。
        if (Build.MANUFACTURER.contains("Xiaomi")) { //裁剪后的图片Uri路径,mUritempFile为Uri类变量
            mUritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + mPictureName + ".jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUritempFile);
        } else {
            intent.putExtra("return-data", true);
        }
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, CUPREQUEST);
 
 
//
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        intent.putExtra("crop", "true");
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        intent.putExtra("outputX", 300);
//        intent.putExtra("outputY", 300);
//        intent.putExtra("scale", true);
//        //        intent.putExtra("return-data", false);
//        intent.putExtra("return-data", true);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUritempFile);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        intent.putExtra("noFaceDetection", true); // no face detection
//        startActivityForResult(intent, CROP_REQUEST_CODE);
    }
 
    /**
     * Gets the corresponding path to a file from the given content:// URI
     * @param selectedVideoUri The content:// URI to find the file path from
     * @param contentResolver The content resolver to use to perform the query.
     * @return the file path as a string
     */
    public static String getFilePathFromContentUri(Uri selectedVideoUri,
                                                   ContentResolver contentResolver) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};
 
        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
//      也可用下面的方法拿到cursor
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);
 
        cursor.moveToFirst();
 
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }
 
 
    public String saveImage(String name, Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath());
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name + ".png";
        File file = new File(appDir, fileName);
//        uploadHeadPic(file);
 
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
 
//            uploadHeadPic(file);
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
 
 
    private void finishActivity(){
        if (null != mOnCropImageeCallback) {
            mOnCropImageeCallback.OnSaveCallback(mCropPicturePath);
        }
        finish();
    }
 
}