flutter 上传图片并裁剪

在这里插入图片描述

1.首先在pubspec.yaml文件中新增依赖pub.dev

image_picker: ^0.8.7+5
image_cropper: ^4.0.1

2.在Android的AndroidManifest.xml文件里面添加权限

<activity
    android:name="com.yalantis.ucrop.UCropActivity"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

3.在ios的Info.plist文件里面添加权限 项目根目录

    <key>NSCameraUsageDescription</key>
    <string>这是你的自拍照</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>用于音频插件</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>用于相册选择插件</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
    </array>

4.代码实现

​​​​​​​_checkAvatar() {
  if (!kIsWeb) {
 
    loading(() async {
      final picker = ImagePicker();
      final pickerFile = await picker.pickImage(source: ImageSource.gallery);
      if (pickerFile != null) {
        CroppedFile? croppedImage = await ImageCropper().cropImage(
            sourcePath: pickerFile.path, //图片资源
            aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1), 
            //裁剪框比例
            uiSettings: [
              AndroidUiSettings(
                  toolbarTitle: '裁剪',
                  lockAspectRatio: true //锁定图片纵横比
              ),
              IOSUiSettings(
                  title: '裁剪',
                  resetButtonHidden: true, //不显示重置按钮
                  aspectRatioLockEnabled: true, //锁定图片纵横比
                  aspectRatioPickerButtonHidden: true, //隐藏切换纵横比按钮
                  doneButtonTitle: "完成", //confirm按钮文字
                  cancelButtonTitle: "取消" //cancel按钮文字
              )
            ]
        );//根据XFile对象的路径获得图片进行裁剪
        //裁剪完成
 
        if(croppedImage != null) {
 
          //裁剪后图片的路径
          String filepath = croppedImage.path;
          final res = await Api.getInstance().uploadAvatar(Provider.memberId, filepath);//pickerFile.path
          if (res['code'] == 0) {
            setState(() {
              ThemeSnackBar.show(context, res['msg']);
              _getUserInfo();
              _user['profilePhoto'] = res['data']['url'];
            });
          } else {
            ThemeSnackBar.show(context, res['msg']);
          }
          print("filepath-----$filepath");
        }
      }
 
 
    });
  } else {
    final uploadInputElement = html.FileUploadInputElement();
    uploadInputElement.multiple = false;
    uploadInputElement.draggable = true;
    uploadInputElement.click();
    uploadInputElement.onChange.listen((event) {
      final file = uploadInputElement.files?.first;
      if (file != null) {
        loading(() async {
          final formData = html.FormData();
          formData.appendBlob("avatarfile", file.slice(), file.name);
          formData.append("memberId", Provider.memberId);
          Api.getInstance().uploadAvatarFromHtml(formData, (e) {
            if (e['code'] == 0) {
              setState(() {
                _user['profilePhoto'] = e['data']['url'];
              });
            } else {
              ThemeSnackBar.show(context, e['msg']);
            }
          });
        });
      }
    });
  }