Android拍照或从图库选择图片并裁剪

一、 拍照选择图片

1、使用隐式Intent启动相机

//构建隐式Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//调用系统相机
startActivityForResult(intent, 1);
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

2、处理相机拍照返回的结果

//用户点击了取消
if(data == null){
    return;
}else{
    Bundle extras = data.getExtras();
    if (extras != null){
        //获得拍的照片
        Bitmap bm = extras.getParcelable("data");
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
二、 从图库选择图片

1、构建内容选择隐式Intent

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
 
 
  • 1
  • 1

2、设置内容类型为图片

intent.setType("image/*");
 
 
  • 1
  • 1

3、启动图片选择

startActivityForResult(intent, 2);
 
 
  • 1
  • 1

4、处理图片选择结果

if (data == null){
    return;
}else{
    //用户从图库选择图片后会返回所选图片的Uri
    Uri uri;
    //获取到用户所选图片的Uri
    uri = data.getData();
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
三、 裁剪选择的图片

从相机拍照得到的是Bitmap类型,所以我们需要先将其转化为文件Uri以供裁剪。同时我们还要顺便将相机拍的照片保存到本地。

/**
 * 将Bitmap写入SD卡中的一个文件中,并返回写入文件的Uri
 * @param bm
 * @param dirPath
 * @return
 */
private Uri saveBitmap(Bitmap bm, String dirPath) {
    //新建文件夹用于存放裁剪后的图片
    File tmpDir = new File(Environment.getExternalStorageDirectory() + "/" + dirPath);
    if (!tmpDir.exists()){
        tmpDir.mkdir();
    }

    //新建文件存储裁剪后的图片
    File img = new File(tmpDir.getAbsolutePath() + "/avator.png");
    try {
        //打开文件输出流
        FileOutputStream fos = new FileOutputStream(img);
        //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
        bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
        //刷新输出流
        fos.flush();
        //关闭输出流
        fos.close();
        //返回File类型的Uri
        return Uri.fromFile(img);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
 
  • 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
  • 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

从图库选择的图片返回的是content类型的Uri,我们需要转化为文件类型的Uri才能进行裁剪。

/**
* 将content类型的Uri转化为文件类型的Uri
* @param uri
* @return
*/
private Uri convertUri(Uri uri){
   InputStream is;
   try {
       //Uri ----> InputStream
       is = getContentResolver().openInputStream(uri);
       //InputStream ----> Bitmap
       Bitmap bm = BitmapFactory.decodeStream(is);
       //关闭流
       is.close();
       return saveBitmap(bm, "temp");
   } catch (FileNotFoundException e) {
       e.printStackTrace();
       return null;
   } catch (IOException e) {
       e.printStackTrace();
       return null;
   }

}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

下面便是设置裁剪的参数,用隐式Intent方式启动裁剪程序

/**
 * 通过Uri传递图像信息以供裁剪
 * @param uri
 */
private void startImageZoom(Uri uri){
    //构建隐式Intent来启动裁剪程序
    Intent intent = new Intent("com.android.camera.action.CROP");
    //设置数据uri和类型为图片类型
    intent.setDataAndType(uri, "image/*");
    //显示View为可裁剪的
    intent.putExtra("crop", true);
    //裁剪的宽高的比例为1:1
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    //输出图片的宽高均为150
    intent.putExtra("outputX", 150);
    intent.putExtra("outputY", 150);
    //裁剪之后的数据是通过Intent返回
    intent.putExtra("return-data", true);
    startActivityForResult(intent, CROP_CODE);
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

下面是完整的布局文件和Java文件


activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/show_image"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>
    <Button
        android:id="@+id/choose_camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="摄像头"/>
    <Button
        android:id="@+id/choose_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="相册"/>
</LinearLayout>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

MainActivity.java文件

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //用于展示选择的图片
    private ImageView mImageView;

    private static final int CAMERA_CODE = 1;
    private static final int GALLERY_CODE = 2;
    private static final int CROP_CODE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        mImageView = (ImageView) findViewById(R.id.show_image);
        Button chooseCamera = (Button) findViewById(R.id.choose_camera);
        chooseCamera.setOnClickListener(this);
        Button chooseGallery = (Button) findViewById(R.id.choose_gallery);
        chooseGallery.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.choose_camera:
                //拍照选择
                chooseFromCamera();
                break;
            case R.id.choose_gallery:
                //从相册选取
                chooseFromGallery();
                break;
            default:
                break;
        }
    }

    /**
     * 拍照选择图片
     */
    private void chooseFromCamera() {
        //构建隐式Intent
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //调用系统相机
        startActivityForResult(intent, CAMERA_CODE);
    }

    /**
     * 从相册选择图片
     */
    private void chooseFromGallery() {
        //构建一个内容选择的Intent
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //设置选择类型为图片类型
        intent.setType("image/*");
        //打开图片选择
        startActivityForResult(intent, GALLERY_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case CAMERA_CODE:
                //用户点击了取消
                if(data == null){
                    return;
                }else{
                    Bundle extras = data.getExtras();
                    if (extras != null){
                        //获得拍的照片
                        Bitmap bm = extras.getParcelable("data");
                        //将Bitmap转化为uri
                        Uri uri = saveBitmap(bm, "temp");
                        //启动图像裁剪
                        startImageZoom(uri);
                    }
                }
                break;
            case GALLERY_CODE:
                if (data == null){
                    return;
                }else{
                    //用户从图库选择图片后会返回所选图片的Uri
                    Uri uri;
                    //获取到用户所选图片的Uri
                    uri = data.getData();
                    //返回的Uri为content类型的Uri,不能进行复制等操作,需要转换为文件Uri
                    uri = convertUri(uri);
                    startImageZoom(uri);
                }
                break;
            case CROP_CODE:
                if (data == null){
                    return;
                }else{
                    Bundle extras = data.getExtras();
                    if (extras != null){
                        //获取到裁剪后的图像
                        Bitmap bm = extras.getParcelable("data");
                        mImageView.setImageBitmap(bm);
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 将content类型的Uri转化为文件类型的Uri
     * @param uri
     * @return
     */
    private Uri convertUri(Uri uri){
        InputStream is;
        try {
            //Uri ----> InputStream
            is = getContentResolver().openInputStream(uri);
            //InputStream ----> Bitmap
            Bitmap bm = BitmapFactory.decodeStream(is);
            //关闭流
            is.close();
            return saveBitmap(bm, "temp");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将Bitmap写入SD卡中的一个文件中,并返回写入文件的Uri
     * @param bm
     * @param dirPath
     * @return
     */
    private Uri saveBitmap(Bitmap bm, String dirPath) {
        //新建文件夹用于存放裁剪后的图片
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/" + dirPath);
        if (!tmpDir.exists()){
            tmpDir.mkdir();
        }

        //新建文件存储裁剪后的图片
        File img = new File(tmpDir.getAbsolutePath() + "/avator.png");
        try {
            //打开文件输出流
            FileOutputStream fos = new FileOutputStream(img);
            //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            //刷新输出流
            fos.flush();
            //关闭输出流
            fos.close();
            //返回File类型的Uri
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 通过Uri传递图像信息以供裁剪
     * @param uri
     */
    private void startImageZoom(Uri uri){
        //构建隐式Intent来启动裁剪程序
        Intent intent = new Intent("com.android.camera.action.CROP");
        //设置数据uri和类型为图片类型
        intent.setDataAndType(uri, "image/*");
        //显示View为可裁剪的
        intent.putExtra("crop", true);
        //裁剪的宽高的比例为1:1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //输出图片的宽高均为150
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        //裁剪之后的数据是通过Intent返回
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_CODE);
    }
}
 
 
  • 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
  • 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

注:最后还需要在AndroidManifest文件中加入存储卡读写权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现拍照裁剪图片功能需要以下步骤: 1. 添加权限 在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ``` 2. 创建布局文件 创建一个布局文件camera_preview.xml,并添加一个SurfaceView和一个Button,用于显示和拍照。 ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/camera_preview" android:layout_width="match_parent" android:layout_height="match_parent"> <SurfaceView android:id="@+id/surface_view" android:layout_width="match_parent" android:layout_height="match_parent"/> <Button android:id="@+id/button_capture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="拍照" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"/> </RelativeLayout> ``` 3. 实现拍照功能 在Activity中,获取Camera实例,并在SurfaceView上显示预览像。当用户点击拍照按钮时,调用Camera.takePicture()方法拍照拍照成功后,保存照片并显示裁剪界面。 ```java public class CameraActivity extends Activity implements SurfaceHolder.Callback { private Camera mCamera; private SurfaceView mSurfaceView; private SurfaceHolder mSurfaceHolder; private Button mButtonCapture; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.camera_preview); // 获取SurfaceView和Button实例 mSurfaceView = findViewById(R.id.surface_view); mButtonCapture = findViewById(R.id.button_capture); // 监听Button点击事件 mButtonCapture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 拍照 mCamera.takePicture(null, null, mPictureCallback); } }); // 获取SurfaceHolder实例,并添加回调监听 mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder holder) { // 打开摄像头并设置预览 mCamera = Camera.open(); try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d("CameraTest", "Error setting camera preview: " + e.getMessage()); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 在SurfaceView上显示预览像 if (mSurfaceHolder.getSurface() == null) { return; } try { mCamera.stopPreview(); } catch (Exception e) { Log.d("CameraTest", "Error stopping camera preview: " + e.getMessage()); } try { mCamera.setPreviewDisplay(mSurfaceHolder); mCamera.startPreview(); } catch (Exception e) { Log.d("CameraTest", "Error starting camera preview: " + e.getMessage()); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // 释放摄像头资源 mCamera.stopPreview(); mCamera.release(); mCamera = null; } private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // 保存照片 File pictureFile = getOutputMediaFile(); if (pictureFile == null) { Log.d("CameraTest", "Error creating media file, check storage permissions"); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.d("CameraTest", "File not found: " + e.getMessage()); } catch (IOException e) { Log.d("CameraTest", "Error accessing file: " + e.getMessage()); } // 显示裁剪界面 Intent intent = new Intent(CameraActivity.this, CropActivity.class); intent.putExtra("image_path", pictureFile.getPath()); startActivity(intent); } }; private File getOutputMediaFile() { // 创建目录 File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCameraApp"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("CameraTest", "failed to create directory"); return null; } } // 创建文件 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); return mediaFile; } } ``` 4. 实现裁剪功能 创建一个布局文件crop.xml,添加一个ImageView和一个Button,用于显示图片和保存裁剪后的图片。 ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/crop_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitCenter"/> <Button android:id="@+id/button_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"/> </RelativeLayout> ``` 在CropActivity中,获取传递过来的图片路径,并将图片显示在ImageView上。当用户点击保存按钮时,调用Bitmap.createBitmap()方法裁剪图片,并保存到相册。 ```java public class CropActivity extends Activity { private ImageView mImageView; private Button mButtonSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.crop); // 获取ImageView和Button实例 mImageView = findViewById(R.id.image_view); mButtonSave = findViewById(R.id.button_save); // 获取传递过来的图片路径 Intent intent = getIntent(); String imagePath = intent.getStringExtra("image_path"); // 将图片显示在ImageView上 Bitmap bitmap = BitmapFactory.decodeFile(imagePath); mImageView.setImageBitmap(bitmap); // 监听Button点击事件 mButtonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 裁剪并保存图片 Bitmap croppedBitmap = getCroppedBitmap(bitmap); saveBitmapToGallery(croppedBitmap); Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show(); finish(); } }); } private Bitmap getCroppedBitmap(Bitmap bitmap) { // 获取ImageView的尺寸 int viewWidth = mImageView.getWidth(); int viewHeight = mImageView.getHeight(); // 获取图片的尺寸 int imageWidth = bitmap.getWidth(); int imageHeight = bitmap.getHeight(); // 计算缩放比例 float scale = Math.min((float) viewWidth / imageWidth, (float) viewHeight / imageHeight); // 计算裁剪区域 int cropWidth = (int) (viewWidth / scale); int cropHeight = (int) (viewHeight / scale); int x = (imageWidth - cropWidth) / 2; int y = (imageHeight - cropHeight) / 2; // 裁剪图片 Bitmap croppedBitmap = Bitmap.createBitmap(bitmap, x, y, cropWidth, cropHeight); return croppedBitmap; } private void saveBitmapToGallery(Bitmap bitmap) { // 创建目录 File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCameraApp"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("CameraTest", "failed to create directory"); return; } } // 保存图片 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imagePath = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"; File imageFile = new File(imagePath); try { FileOutputStream fos = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (IOException e) { Log.d("CameraTest", "Error accessing file: " + e.getMessage()); } // 通知相册更新 MediaScannerConnection.scanFile(this, new String[]{imagePath}, null, null); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值