简体   繁体   English

Flutter:如何使用“多图像选择器”来降低图像质量并将输出作为“文件”?

[英]Flutter: How to use "Multi Image Picker" to reduce image quality and get output as "File"?

I am using Flutter package to multi select images.我正在使用 Flutter 包来多选图像。 Below is my code下面是我的代码

List<Asset>localAssetList = [];//new

localAssetList = await MultiImagePicker.pickImages(
        maxImages: 5,
        enableCamera: true,
        
       selectedAssets: localAssetList,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Example App",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );

I want to reduce the image quality by 60% in every image, then get the results as List<File> .我想将每张图像的图像质量降低 60%,然后将结果作为List<File> How can I do this?我怎样才能做到这一点?

You can do something as below:您可以执行以下操作:

  _getImageList() async {
    var resultList = await MultiImagePicker.pickImages(
      maxImages: 6,
      enableCamera: true,
    );

    // The data selected here comes back in the list
    for (var imageFile in resultList) {
      await postImage(imageFile).then((downloadUrl) {
        // Get the download URL and do your stuff here
      }).catchError((err) {
        print(err);
      });
    }
  }

And in postImage function, you can resize each image and change its quality.在 postImage 函数中,您可以调整每个图像的大小并更改其质量。

Future<dynamic> postImage(Asset imageFile) async {
    double imageDesiredWidth = 500;

    double getAspectRatio(double originalSize, double desiredSize) => desiredSize / originalSize;
    final aspectRatio = getAspectRatio(imageFile.originalWidth.toDouble(), imageDesiredWidth);
    ByteData byteData = await imageFile.getThumbByteData(
        (imageFile.originalWidth * aspectRatio).round(),
        (imageFile.originalHeight * aspectRatio).round(),
        quality: 85
    );

    String fileName = DateTime
        .now()
        .millisecondsSinceEpoch
        .toString();
    StorageReference reference = _storage.ref().child(fileName);
    StorageUploadTask uploadTask =
    reference.putData(byteData.buffer.asUint8List());
    StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
    return await storageTaskSnapshot.ref.getDownloadURL();
  }

There's a nice library you can use on this case: flutter_image_compress.在这种情况下,您可以使用一个不错的库:flutter_image_compress。

First add the dependency:首先添加依赖:

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  flutter_image_compress: ^0.7.0

Import it导入它

import 'package:flutter_image_compress/flutter_image_compress.dart';

And for using it, you can use this method:对于使用它,您可以使用以下方法:

void compressImage(File file) async {
    // Get file path
    // eg:- "Volume/VM/abcd.jpeg"
    final filePath = file.absolute.path;
    
    // Create output file path
    // eg:- "Volume/VM/abcd_out.jpeg"
    final lastIndex = filePath.lastIndexOf(new RegExp(r'.jp'));
    final splitted = filePath.substring(0, (lastIndex));
    final outPath = "${splitted}_out${filePath.substring(lastIndex)}";

    final compressedImage = await FlutterImageCompress.compressAndGetFile(
          filePath, 
          outPath,
          minWidth: 1000,
          minHeight: 1000,
          quality: 70);
}

You can find more about Flutter Image Compress here: https://pub.dev/packages/flutter_image_compress .您可以在此处找到有关 Flutter Image Compress 的更多信息: https : //pub.dev/packages/flutter_image_compress Let me know if this solves your problem.如果这能解决您的问题,请告诉我。

First, multi_image_picker is deprecated.首先,不推荐使用multi_image_picker Use multi_image_picker2 .使用multi_image_picker2

There are 2 ways of doing this as of October 2021.截至 2021 年 10 月,有两种方法可以做到这一点。

First Way第一种方式

Use flutter_image_compress library as following.使用flutter_image_compress库如下。 Here I am using Uint8List but you can use File as well.这里我使用的是Uint8List但您也可以使用File

Future<Uint8List> compressUintImage(Uint8List list) async {
    var result = await FlutterImageCompress.compressWithList(
      list,
      minHeight: 1920,
      minWidth: 1080,
      quality: 96,
    );
    print(list.length);
    print(result.length);
    return result;
  }

Second Way第二种方式

ByteData byteData = await file.getByteData(quality: 100);

This is by using the multi_image_picker2 itself.这是通过使用multi_image_picker2本身。 Here the file is an Asset .这里的file是一个Asset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在将其上传到服务器之前降低图像质量 - How to reduce image quality before uploading it on server 如何将 multi_image_picker2 `Asset ` 转换为 `File ` 对象? - How to convert multi_image_picker2 `Asset ` to a `File ` object? 使用Universal Image Loader时如何降低图像质量? - How to reduce image quality when using Universal Image Loader? 如何使用位图工厂压缩图像而不降低相机拍摄的质量? - How to use bitmap factory to compress image without reduce the quality taken from camera? 文件选择器类型图像返回空颤动 - File picker type image returns null flutter flutter web:当我将图像上传到存储时,我无法控制图像选择器的质量 - flutter web : When I image upload to storage, I can't control the quality of the image picker 如何在android中没有质量中断的情况下减小图像大小 - how to reduce image Size without Quality break in android 如何使用 Glide for android 压缩和降低图像质量 - How to Compress and reduce Quality of image using Glide for android 如何在Android上降低字节格式的图像质量? - How do I reduce the quality of an image in byte format on Android? Android如何在不降低质量的情况下减小图像尺寸 - Android how to reduce image size without loosing quality
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM