import 'dart:io' ;
import 'dart:typed_data' ;
import 'package:cached_network_image/cached_network_image.dart' ;
import 'package:flutter/services.dart' ;
import 'package:flutter_cache_manager/flutter_cache_manager.dart' ;
import 'package:image_gallery_saver/image_gallery_saver.dart' ;
import 'package:permission_handler/permission_handler.dart' ; class ImageUtil { static Future < bool> saveImage ( String imageUrl, { bool isAsset: false } ) async { try { if ( imageUrl == null ) throw '保存失败,图片不存在!' ; PermissionStatus storageStatus = await Permission . storage. status; if ( storageStatus != PermissionStatus . granted) { storageStatus = await Permission . storage. request ( ) ; if ( storageStatus != PermissionStatus . granted) { throw '无法存储图片,请先授权!' ; } } Uint8List imageBytes; if ( isAsset == true ) { ByteData bytes = await rootBundle. load ( imageUrl) ; imageBytes = bytes. buffer. asUint8List ( ) ; } else { CachedNetworkImage image = CachedNetworkImage ( imageUrl: imageUrl) ; DefaultCacheManager manager = image. cacheManager ? ? DefaultCacheManager ( ) ; Map < String , String > headers = image. httpHeaders; File file = await manager. getSingleFile ( image. imageUrl, headers: headers, ) ; imageBytes = await file. readAsBytes ( ) ; } final result = await ImageGallerySaver . saveImage ( imageBytes) ; if ( result == null || result == '' ) throw '图片保存失败' ; return true ; } catch ( e) { return false ; } } static getOssImageThumbUrl ( String url, { double width = 350.0 , double height, int quality = 80 } ) { if ( url. contains ( '?Size=' ) || url. contains ( '?size=' ) ) { List < String > strList = url. contains ( '?Size=' ) ? url. split ( '?Size=' ) : url. split ( '?size=' ) ; url = strList. first; if ( height == null ) { String sizeStr = strList. last; List < String > sizeList = sizeStr. split ( 'x' ) ; double oldImgWid = double. parse ( sizeList. first) ; double oldImgHei = double. parse ( sizeList. last) ; double newImgWid = width; double proportion = oldImgHei / oldImgWid; if ( proportion > 1 ) { proportion = 4 / 3 ; } else { proportion = 3 / 4 ; } double newImgHei = proportion * newImgWid; url += '?x-oss-process=image/resize,m_fill,w_ ${ newImgWid. floor ( ) } ,h_ ${ newImgHei. floor ( ) } /quality,q_ $ quality ' ; } else { url += '?x-oss-process=image/resize,m_fill,w_ ${ width. floor ( ) } ,h_ ${ height. floor ( ) } /quality,q_ $ quality ' ; } } else { if ( height != null ) { url += '?x-oss-process=image/resize,m_fill,w_ ${ width. floor ( ) } ,h_ ${ height. floor ( ) } /quality,q_ $ quality ' ; } } return url; }
}