compressImage method

void compressImage(
  1. String imagePath
)

Implementation

void compressImage(String imagePath) {
  final file = File(imagePath);

  final bytes = file.readAsBytesSync();

  // 取得圖片格式
  final imageFormat = ImageFormatDetector.detect(bytes);

  final input = ImageFile(
    rawBytes: file.readAsBytesSync(),
    filePath: file.path,
  );

  // print('檢測檔案格式($imageFormat): $imagesPath');

  switch (imageFormat) {
    case ImageFormat.jpg:
      final output = compress(
        ImageFileConfiguration(
          input: input,
          config: Configuration(outputType: OutputType.jpg),
        ),
      );
      File(imagePath).writeAsBytesSync(output.rawBytes);
      // print('壓縮前: ${input.rawBytes.length} 壓縮後: ${output.rawBytes.length}');
      break;
    case ImageFormat.png:
      final output = compress(
        ImageFileConfiguration(
          input: input,
          config: Configuration(outputType: OutputType.png),
        ),
      );
      File(imagePath).writeAsBytesSync(output.rawBytes);
      // print('壓縮前: ${input.rawBytes.length} 壓縮後: ${output.rawBytes.length}');
      break;
    case ImageFormat.apng:
    // apng壓縮完反而變大了, 不處理
      break;
    default:
    // 其餘不壓縮
      break;
  }
}