首页 > 解决方案 > Flutter:如何使用 Image 插件调整图像大小

问题描述

我正在尝试使用颤振插件“图像” https://pub.dartlang.org/packages/image调整图像大小

我按照说明使用的方法

  File resizeMyImage(File resizeThisFile) {
    // decodeImage will identify the format of the image and use the appropriate
    // decoder.
    File myCompressedFile;
    Image image = decodeImage(resizeThisFile.readAsBytesSync());

    // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
    Image thumbnail = copyResize(image, 120);

    // Save the thumbnail as a PNG.
    myCompressedFile = new Io.File('thumbnail.png')..writeAsBytesSync(encodePng(thumbnail));

   return myCompressedFile;
  }

我得到的错误

E/flutter (22897): FileSystemException: Cannot open file, path = 'thumbnail.png' (OS Error: Read-only file system, errno = 30)

非常感谢任何帮助 - 谢谢。

工作调整大小类看起来像这样。希望它可以帮助某人。

import 'dart:async';
import 'dart:io' as Io;
import 'dart:io';
import 'package:image/image.dart';
import 'package:path_provider/path_provider.dart';

class ResizeImage {

  String tempPath;

  Future main() async {
  }


  Future<Io.File> resizeMyImage(File resizeThisFile) async {
    Directory tempDir = await getTemporaryDirectory();
    tempPath = tempDir.path;

    // decodeImage will identify the format of the image and use the appropriate
    // decoder.
    File myCompressedFile;
    Image image = decodeImage(resizeThisFile.readAsBytesSync());

    // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
    Image thumbnail = copyResize(image, 120);

    // Save the thumbnail as a PNG.
    print('resizeMyImage............tempPath: '+tempPath);
    myCompressedFile = new Io.File(tempPath+'thumbnail.png')..writeAsBytesSync(encodePng(thumbnail));

   return myCompressedFile;
  }
}

标签: dartflutter

解决方案


您不能在当前目录中创建文件,因为错误消息指出它是只读的。

https://pub.dartlang.org/packages/path_provider允许您获取有效目录的路径

Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;

Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;

推荐阅读