flutter 上传图片并裁剪

用flutter实现上传图片并裁剪的功能:
效果如下:
flutter 上传图片并裁剪_第1张图片

需要先把APP的相册权限开一下,否则会闪退,ios是在xcode中配置,安卓在AndroidManifest.xml配置。
添加如下扩展,放入pubspec.yaml文件dependencies下:

image_picker: ^0.8.7+5 #选择相册
image_cropper: ^4.0.1 #裁剪

如下为代码

import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
class CoverPage extends StatefulWidget {
  const CoverPage({super.key});

  
  State<CoverPage> createState() => _CoverPageState();
}

class _CoverPageState extends State<CoverPage> with SingleTickerProviderStateMixin {
  final ImagePicker _imagePicker = ImagePicker();
  String cover = "";
  
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: (){
          //选择相册图片
          selectImage();
        },
        child: const Text(
          "更换封面",
          style: TextStyle(
            color: Colors.red,
            fontSize: 14
          ),
        )
      )
    );
  }
  selectImage() async {
    //选择单图上传
    final image = await _imagePicker.pickImage(source: ImageSource.gallery); //返回的是XFile对象
    if(image != null) {
      CroppedFile? croppedImage = await ImageCropper().cropImage(
        sourcePath: image.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;
        print("filepath-----$filepath");
      }
    }
  }
}

你可能感兴趣的:(flutter,技术开发,flutter)