Skip to content

图片文件转成 base64

包含 FileCroppedFile 两种类型

file_to_base64.dart

dart
import 'dart:convert';
import 'dart:io';
import 'package:image_cropper/image_cropper.dart';

Future<String> croppedFileToBase64(CroppedFile croppedFile) async {
  // 通过CroppedFile对象获取File对象
  File file = File(croppedFile.path);

  // 读取文件内容
  List<int> bytes = await file.readAsBytes();

  // 将文件内容进行 base64 编码
  String base64String = base64Encode(bytes);

  return base64String;
}

Future<String> fileToBase64(File file) async {
  // 读取文件内容
  List<int> bytes = await file.readAsBytes();

  // 将文件内容进行 base64 编码
  String base64String = base64Encode(bytes);

  return base64String;
}

file_to_base64_web.dart

dart
import 'dart:async';
import 'dart:html';
import 'package:image_cropper/image_cropper.dart';

Future<String> croppedFileToBase64(CroppedFile croppedFile) async {
  final reader = FileReader();
  final completer = Completer<String>();

  reader.onLoad.listen((event) {
    final result = reader.result;
    if (result is String) {
      final base64String = result.split(',').last;
      completer.complete(base64String);
    } else {
      completer.completeError('Failed to read file as base64.');
    }
  });

  reader.onError.listen((event) {
    completer.completeError('Error reading file: ${reader.error}');
  });

  reader.readAsDataUrl(Blob([await croppedFile.readAsBytes()]));

  return completer.future;
}

Future<String?> fileToBase64(File file) async {
  final reader = FileReader();
  final completer = Completer<String?>();

  reader.onLoad.listen((event) {
    final result = reader.result;
    if (result is String) {
      final base64String = result.split(',').last;
      completer.complete(base64String);
    } else {
      completer.completeError('Failed to read file as base64.');
    }
  });

  reader.onError.listen((event) {
    completer.completeError('Error reading file: ${reader.error}');
  });

  reader.readAsDataUrl(file);

  return completer.future;
}

使用

引入方式

dart
import 'package:pc28/utils/file_to_base64.dart' if (dart.library.html) 'package:pc28/utils/file_to_base64_web.dart';

点击选择图片并进行裁剪后,把 CroppedFile 转成 base64

dart
showCustomBottomSheet(context, ImgPicker(
  onChanged: (value) async {
    Navigator.of(context).pop();
    var croppedFile = await cropImage(value['pickfile'], context);
    if (croppedFile == null) {
      return;
    }
    String base64Str = '';
    base64Str = await croppedFileToBase64(croppedFile);
    var params = {'base64_data': 'data:image/png;base64,$base64Str'};
    uploadImg(params);
  },
));