Flutter 學習 之 圖片的選擇 裁切 保存

在實際任務中免不了對圖片進行裁切 文件格式轉(zhuǎn)換 圖片的選取等操作 這里做一個記錄
1. Flutter 圖片選擇工具 image_picker
2. 圖片裁切工具 image_cropper
3. 圖片保存到相冊image_gallery_saver

圖片選擇器

介紹

這里我選擇的是image_picker
優(yōu)點

  • 官方出品的插件
  • 可以直接調(diào)用相冊和相機無需提前申請權(quán)限
  • 可以多選和單選選擇豐富
    缺點
  • 多選需要長按沒有明顯的提示

使用

  1. 引用組件
  2. 封裝他的一個方法(以單選為例子)
enum ImageFrom{
  camera,
  gallery
}
  ///選擇一個圖片
  ///[from] 是相機還是圖庫
  ///可選參數(shù)
  ///[maxWidth] 寬度,
  ///[maxHeight] 高度,
  ///[imageQuality] 質(zhì)量
  static pickSinglePic(ImageFrom from,
      {double? maxWidth, double? maxHeight, int? imageQuality}) async {
    ImageSource source;
    switch (from) {
      case ImageFrom.camera:
        source = ImageSource.camera;
        break;
      case ImageFrom.gallery:
        source = ImageSource.gallery;
        break;
    }
    final pickerImages = await ImagePicker().pickImage(
      source: source,
      imageQuality: imageQuality,
      maxWidth: maxWidth,
      maxHeight: maxHeight,
    );
    return pickerImages;
  }

使用:

      final pickerImages = await ImageUtil.pickSinglePic(score);

圖片裁切

使用

  1. 引用組件
    2.在AndroidMainifest中增加一個View
       <activity
           android:name="com.yalantis.ucrop.UCropActivity"
           android:screenOrientation="portrait"
           android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
  1. 封裝成一個方法
  ///裁切圖片
  ///[image] 圖片路徑或文件
  ///[width] 寬度
  ///[height] 高度
  ///[aspectRatio] 比例
  ///[androidUiSettings]UI 參數(shù)
  ///[iOSUiSettings] ios的ui 參數(shù)
  static cropImage(
      {required image,
      required width,
      required height,
      aspectRatio,
      androidUiSettings,
      iOSUiSettings}) async {
    String imagePth = "";
    if (image is String) {
      imagePth = image;
    } else if (image is File) {
      imagePth = image.path;
    } else {
      throw ("文件路徑錯誤");
    }
    final croppedFile = await ImageCropper().cropImage(
      sourcePath: imagePth,
      maxWidth: FormatUtil.num2int(width),
      maxHeight: FormatUtil.num2int(height),
      aspectRatio: aspectRatio ??
          CropAspectRatio(
              ratioX: FormatUtil.num2double(width),
              ratioY: FormatUtil.num2double(height)),
      uiSettings: [
        androidUiSettings ??
            AndroidUiSettings(
                toolbarTitle:
                    '圖片裁切(${FormatUtil.num2int(width)}*${FormatUtil.num2int(height)})',
                toolbarColor: Colors.blue,
                toolbarWidgetColor: Colors.white,
                initAspectRatio: CropAspectRatioPreset.original,
                hideBottomControls: false,
                lockAspectRatio: true),
        iOSUiSettings ??
            IOSUiSettings(
              title: 'Cropper',
            ),
      ],
    );
    return croppedFile;
  }
  ///數(shù)字轉(zhuǎn)成Int
  ///[number] 可以是String 可以是int 可以是double 出錯了就返回0;
  static num2int(number) {
    try {
      if (number is String) {
        return int.parse(number);
      } else if (number is int) {
        return number;
      } else if (number is double) {
        return number.toInt();
      } else {
        return 0;
      }
    } catch (e) {
      return 0;
    }
  }

  ///數(shù)字轉(zhuǎn)成double
  ///[number] 可以是String 可以是int 可以是double 出錯了就返回0;
  static num2double(number) {
    try {
      if (number is String) {
        return double.parse(number);
      } else if (number is int) {
        return number.toDouble();
      } else if (number is double) {
        return number;
      } else {
        return 0.0;
      }
    } catch (e) {
      return 0.0;
    }
  }

使用

       File? _userImage = File(pickerImages.path);
      if (_userImage != null) {
        final croppedFile = await ImageUtil.cropImage(
            image: _userImage,
            width: 256,
            height: 512);
}

圖片保存

  1. 引入插件
    2.封裝組件
///保存Uint8List 到相冊
  ///[image]Uint8List 數(shù)組
  ///[quality] 質(zhì)量
  ///[name] 保存的名字
  static saveImage2Album(image, {quality = 100, name = "photo"}) async {
    final result =
        await ImageGallerySaver.saveImage(image, quality: quality, name: name);
    return result;
  }

他還有一個保存文件的方法

_saveVideo() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.mp4";
    await Dio().download("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4", savePath);
    final result = await ImageGallerySaver.saveFile(savePath);
    print(result);
 }

使用
保存前注意先申請一下存儲權(quán)限

    PermissionUtil.checkPermission(
        permissionList: [Permission.photos, Permission.storage],
        onFailed: () => {ToastUtil().showCenterToast("圖片處理錯誤")},
        onSuccess: () async {
          final result = await FileUtil.saveImage2Album(finalImgBuffer!,
              quality: 100, name: "photo");
          if (result != null) {
            ToastUtil().showCenterToast("保存成功~~~");
          } else {
            ToastUtil().showCenterToast("保存失敗~~~");
          }
        });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容