mobile_skt/lib/util/media_util.dart

251 lines
7.5 KiB
Dart

import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart' as dio_package;
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:sk_base_mobile/apis/api.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/config.dart';
import 'package:sk_base_mobile/models/upload_result.model.dart';
import 'package:sk_base_mobile/router/router.util.dart';
import 'package:sk_base_mobile/services/service.dart';
class MediaUtil {
/// 选择获取图片的方式,并返回路径
showPicker({Function(String?)? callback, String title = '请选择上传方式'}) async {
await showCupertinoModalPopup(
context: Get.overlayContext!,
builder: (BuildContext ctx) {
return CupertinoActionSheet(
title: Text(title),
cancelButton: CupertinoActionSheetAction(
onPressed: () {
RouterUtil.back();
},
child: const Text(
'取消',
style: TextStyle(color: Color(0xffcdcdcd)),
)),
actions: ['拍照', '相册']
.map((item) => CupertinoActionSheetAction(
onPressed: () async {
await RouterUtil.back();
XFile? pickedFile = item == '拍照'
? await MediaUtil().getImageFromCamera()
: await MediaUtil().getImageFromGallery();
if (pickedFile != null) {
if (callback != null) {
callback(pickedFile.path);
}
}
},
child: Text(
item,
style: const TextStyle(color: AppTheme.primaryColor),
)))
.toList(),
);
});
}
static String getMediaUrl(String? url) {
if ((url ?? '').isEmpty) {
return '';
} else {
return '${GloablConfig.OSS_URL}$url';
}
}
//拍照
Future<XFile?> getImageFromCamera(
{double? maxWidth, bool isFront = false}) async {
XFile? pickedFile;
try {
if (AppInfoService.to.isCameraing.value) {
return null;
}
AppInfoService.to.isCameraing.value = true;
pickedFile = await ImagePicker().pickImage(
imageQuality: 40,
source: ImageSource.camera,
maxWidth: maxWidth ?? 2000,
preferredCameraDevice:
isFront ? CameraDevice.front : CameraDevice.rear);
AppInfoService.to.isCameraing.value = false;
} catch (e) {
AppInfoService.to.isCameraing.value = false;
}
return pickedFile;
}
//相册选择 单张
Future<XFile?> getImageFromGallery() async {
if (AppInfoService.to.isCameraing.value) {
return null;
}
AppInfoService.to.isCameraing.value = true;
XFile? pickedFile = await ImagePicker()
.pickImage(source: ImageSource.gallery, imageQuality: 40);
AppInfoService.to.isCameraing.value = false;
return pickedFile;
}
Future<UploadResultModel?> uploadImg(File imgfile,
{int? bussinessRecordId, String? bussinessModule}) async {
dio_package.Response response = await Api.uploadImg(imgfile);
if (response.data != null && response.data['filename'] != null) {
return UploadResultModel.fromJson(response.data["filename"]);
}
return null;
}
// 保存到相册
Future saveImageToPhotoLib({required String imgUrl, String? filename}) async {
var response = await DioService.dio
.get(imgUrl, options: Options(responseType: ResponseType.bytes));
final result = await ImageGallerySaver.saveImage(
Uint8List.fromList(response.data),
quality: 60);
return result;
}
// // 上传一张照片
// Future<String> uploadMediaWithProgress(
// File imgfile, Function onProgress) async {
// Response response = await Api.uploadMediaWithProgress(imgfile, onProgress);
// if (response.data != null && response.data['code'] == 200) {
// return response.data['data']['url'];
// } else {
// throw Exception('上传照片失败');
// }
// }
// // 上传多张照片
// Future<List<String>> uploadMultiImgs(List<File> imgfiles) async {
// Response response = await Api.uploadMultiImgs(imgfiles);
// List<String> urlList = [];
// if (response.data != null && response.data['code'] == 200) {
// String url = response.data['data']['url'];
// urlList = url.split(',');
// return urlList;
// } else {
// throw Exception('上传照片失败');
// }
// }
// ///选取视频
// Future<XFile?> getVideoFromGallery() async {
// if (AppInfoModel().isCameraing) {
// return null;
// }
// XFile? pickedFile =
// await ImagePicker().pickVideo(source: ImageSource.gallery);
// if (pickedFile != null) {
// var path = pickedFile.path;
// if (Platform.isAndroid) {
// var newPath = path.replaceAll('.jpg', '.mp4');
// File(path).renameSync(newPath);
// return XFile(newPath);
// }
// }
// return pickedFile;
// }
// /*拍摄视频*/
// Future takeVideoFromCamera() async {
// var image = await ImagePicker().getVideo(source: ImageSource.camera);
// print('拍摄视频:' + image.toString());
// }
// /// 生成视频缩略图
// Future<String> generateLogoUrl(String videoUrl) async {
// File file = await generateLogoFile(videoUrl: videoUrl);
// return await MediaUtil().uploadImg(file);
// }
// /// 生成视频缩略图
// Future<File> generateLogoFile({String? videoUrl, String? videoPath}) async {
// Directory fileDic = await getApplicationDocumentsDirectory();
// String? path = await VideoThumbnail.thumbnailFile(
// video: videoUrl ?? videoPath!,
// imageFormat: ImageFormat.JPEG,
// thumbnailPath: fileDic.path,
// // maxWidth: 200,
// // 64, // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
// quality: 100,
// );
// return File(path!);
// }
// /// 获取文件类型Video/audio/image
// MediaTypeEnum getMediaTypeBySuffix(String? url) {
// if (url == null || url == '') {
// return MediaTypeEnum.IMAGE;
// }
// String suffix = url.split('.')[url.split('.').length - 1].toLowerCase();
// if (videoSuffix.contains(suffix)) {
// return MediaTypeEnum.VIDEO;
// } else if (audioSuffix.contains(suffix)) {
// return MediaTypeEnum.AUDIO;
// }
// return MediaTypeEnum.IMAGE;
// }
// List<String> videoSuffix = [
// 'avi',
// 'wmv',
// 'mpg',
// 'mpeg',
// 'mov',
// 'rm',
// 'ram',
// 'swf',
// 'flv',
// 'mp4'
// ];
// List<String> audioSuffix = [
// 'aac',
// 'mp3',
// 'cda',
// 'wav',
// 'wma',
// 'ra',
// 'rma',
// 'ape',
// 'asf',
// 'mid',
// 'midi',
// 'rmi',
// 'xmi',
// 'ogg',
// 'ape',
// 'aiff',
// 'au'
// ];
// List<String> imageSuffix = [
// 'webp',
// 'bmp',
// 'pcx',
// 'tif',
// 'gif',
// 'jpeg',
// 'tga',
// 'exif',
// 'fpx',
// 'svg',
// 'psd',
// 'cdr',
// 'png',
// 'ogg',
// 'ape',
// 'aiff',
// 'au',
// 'jpg'
// ];
}