如何在Flutter / Dart中读取(从磁盘)和调整图像大小

时间:2018-04-06 22:12:44

标签: dart flutter image-resizing

在Flutter / Dart中,我该如何执行以下3个步骤:

  1. 从磁盘读取图像
  2. 阅读其原始尺寸(宽度和高度),
  3. 调整大小。
  4. 注意:我必须能够使用常规的Flutter Image小部件显示最终结果。

    澄清:我不想保存图像,但我确实希望在内存中实际调整大小。

10 个答案:

答案 0 :(得分:11)

您可以使用image.file构造函数从磁盘读取图像。

有关更多功能,您可以使用Image library

  

Dart库提供加载,保存和操作的功能   各种不同文件格式的图像。

来自文档examples

的示例
  

加载jpeg,调整大小并将其另存为png

import 'dart:io' as Io;
import 'package:image/image.dart';
void main() {
  // Read a jpeg image from file.
  Image image = decodeImage(new Io.File('test.jpg').readAsBytesSync());

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

  // Save the thumbnail as a PNG.
  new Io.File('out/thumbnail-test.png')
        ..writeAsBytesSync(encodePng(thumbnail));
}

答案 1 :(得分:4)

要调整pubspec.yaml中定义的图像的大小,请使用“ BoxFit”:

@override
Widget build(BuildContext context) {
  return (new Container(
    width: 250.0,
    height: 250.0,
      alignment: Alignment.center,
      decoration: new BoxDecoration(

      image: DecorationImage(
          image: AssetImage('assets/Launcher_Icon.png'),
          fit: BoxFit.fill
      ),
    ),
  ));
}

另请参考如何访问图像:https://flutter.io/assets-and-images/

答案 2 :(得分:3)

这不是通过图像库调整图片大小的好方法,因为它会阻塞ui线程,并且带来非常糟糕的UX。 maxWidth库中有一个image_picker参数,您可以设置它,因此在某些情况下不需要进行这些写入文件的操作。

答案 3 :(得分:3)

使用ResizeImage图片提供程序。

如果您想使用许多功能,或者无法使用其他功能,则最好使用单独的软件包。但是,仅依靠某些东西而不是框架本身(及其底层图形引擎)可以轻松完成的工作即可...:-)

如果您现在有一个ImageProvider,则要显示内存中字节的图像:

Image(image: MemoryImage(bytes))

只需将其包装在ResizeImage中:

Image(image: ResizeImage(MemoryImage(bytes), width: 50, height: 100))

如果您想获得更多控制权,只需根据该源代码创建自己的图像提供程序即可。

答案 4 :(得分:2)

 final pickedFile = await picker.getImage(
        source: ImageSource.gallery,
        imageQuality: 25,
        maxHeight: 1024,
        maxWidth: 1024);

答案 5 :(得分:2)

有很多解决方案:

使用 ResizeImage

ResizeImage 类指示 Flutter 以指定尺寸而非原始尺寸解码图像。

用法:只需用 ResizeImage 类包装您的 ImageProvider

示例:

Image(image: ResizeImage(AssetImage('eg.png'), width: 70, height: 80)),
<块引用>

ImageProvider 包括 AssetImageNetworkImageFileImageMemoryImage

在您的 Image widget 中使用 cacheHeight cacheWidth 属性

这些属性创建一个小部件,显示从资产、网络、内存或文件中获取的 [ImageStream]。

示例:

Image.asset('assets/image.png', cacheHeight:120 , cacheWidth: 150),
<块引用>

Image.assetImage.networkImage.fileImage.memory

答案 6 :(得分:1)

您可以使用飞镖image软件包:https://pub.dartlang.org/packages/image

该软件包提供各种服务,例如调整大小,裁剪和旋转。

虽然此程序包确实有效,但很慢。

查看讨论内容:https://github.com/brendan-duncan/image/issues/55

答案 7 :(得分:1)

下面是一个示例Thumbnail小部件,该小部件可以在飞行中执行此操作

它使用Isolate来将CPU密集型工作卸载到后台线程,并且UI线程不产生乱码

import 'dart:io';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:image/image.dart' as IMG;
import 'package:path/path.dart';

class Thumbnail extends StatefulWidget {
  final Size size;
  final File image;

  const Thumbnail({Key key, this.size, this.image}) : super(key: key);
  @override
  _ThumbnailState createState() => _ThumbnailState();
}

class _ThumbnailState extends State<Thumbnail> {
  List<int> imgBytes;
  Isolate isolate;

  @override
  void initState() {
    _asyncInit();

    super.initState();
  }

  static _isolateEntry(dynamic d) async {
    final ReceivePort receivePort = ReceivePort();
    d.send(receivePort.sendPort);

    final config = await receivePort.first;

    print(config);

    final file = File(config['path']);
    final bytes = await file.readAsBytes();

    IMG.Image image = IMG.decodeImage(bytes);
    IMG.Image thumbnail = IMG.copyResize(
      image,
      width: config['size'].width.toInt(),
    );

    d.send(IMG.encodeNamedImage(thumbnail, basename(config['path'])));
  }

  _asyncInit() async {
    final ReceivePort receivePort = ReceivePort();
    isolate = await Isolate.spawn(_isolateEntry, receivePort.sendPort);

    receivePort.listen((dynamic data) {
      if (data is SendPort) {
        if (mounted) {
          data.send({
            'path': widget.image.path,
            'size': widget.size,
          });
        }
      } else {
        if (mounted) {
          setState(() {
            imgBytes = data;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    if (isolate != null) {
      isolate.kill();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.size.height,
      width: widget.size.width,
      child: imgBytes != null
          ? Image.memory(
              imgBytes,
              fit: BoxFit.cover,
            )
          : Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.grey[100], Colors.grey[300]],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
              ),
            ),
    );
  }
}

答案 8 :(得分:1)

您可以使用dart ui库中的图像类,使用intantiateImageCodec中的frameInfo获取具有所需宽度和高度的图像对象,然后将其保存在所需路径中

 import 'dart:ui' as ui;

        Uint8List m = File(path).readAsBytesSync();
        ui.Image x = await decodeImageFromList(m);
        ByteData bytes = await x.toByteData();
        print('height is ${x.height}'); //height of original image
        print('width is ${x.width}'); //width of oroginal image

        print('array is $m');
        print('original image size is ${bytes.lengthInBytes}');

            ui.instantiateImageCodec(m, targetHeight: 800, targetWidth: 600)
            .then((codec) {
          codec.getNextFrame().then((frameInfo) async {
            ui.Image i = frameInfo.image;
            print('image width is ${i.width}');//height of resized image
            print('image height is ${i.height}');//width of resized image
            ByteData bytes = await i.toByteData();
            File(path).writeAsBytes(bytes.buffer.asUint32List());
            print('resized image size is ${bytes.lengthInBytes}');
          });
        });

答案 9 :(得分:0)

您可以在“脚手架”小部件中使用“图像”小部件,

首先,您需要在根目录中创建资产文件夹并添加图片文件夹,然后添加

    flutter:
      assets:
        - assets/images/
然后

pubspec.yaml 文件

new Image(
          image: AssetImage('assets/images/pizzaFont.png'),
          height: 12,
          width:12, ......
   )

您可以使用宽度和高度来更改图像的大小。

有关更多信息,请

https://medium.com/@suragch/how-to-include-images-in-your-flutter-app-863889fc0b29