How can I read (from disk) and resize an image, in Flutter/Dart

前端 未结 8 643
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 08:53

In Flutter/Dart, how can I perform the following 3 steps:

  1. Read an image from disk,
  2. Read its original dimensions (width and height),
  3. Resiz
相关标签:
8条回答
  • 2020-12-09 09:16

    you can use the image class from dart ui library, get the image object with your desired width and height using the frameInfo from intantiateImageCodec and then save it in your desired path

     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}');
              });
            });
    
    0 讨论(0)
  • 2020-12-09 09:19

    You can use the Image widget in the Scaffold widget,

    First of all you need to create assets folder in the root and add an images folder, after that add,

        flutter:
          assets:
            - assets/images/
    

    to the pubspec.yaml file, after that

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

    You can use width and height to change the size of the image.

    For more information follow,

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

    0 讨论(0)
提交回复
热议问题