
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:image/image.dart' as img;
import 'dart:convert' show json;

class ImageUtils {

  static ImageProvider getAssetImage(String name, {String format: 'png'}){
    return AssetImage(getImgPath(name, format: format));
  }

  static String getImgPath(String name, {String format: 'png'}) {
    return 'assets/images/$name.$format';
  }

  static ImageProvider getImageProvider(String imageUrl, {String holderImg: "none"}){
    if (TextUtil.isEmpty(imageUrl)){
      return AssetImage(getImgPath(holderImg));
    }
    return CachedNetworkImageProvider(imageUrl);
  }

  ///image保存临时文件夹下
  saveCacheImageFile( imageByte,name,{fileName="signImg"}) async{
    final image = img.decodeImage(imageByte);
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path; // 临时文件夹
    Directory dir = Directory(tempPath + "/$fileName");
    if (!dir.existsSync()) {
      dir.createSync();
    }
    final imageFile = File(path.join(dir.path, '${name}.png')); // 保存在应用文件夹内
//    if(imageFile.existsSync()){
//      imageFile.deleteSync();
//    }
    await imageFile.writeAsBytes(img.encodePng(image)); // 需要使用与图片格式对应的encode方法
    return imageFile.path;
  }
}

