flutter如何压缩图片到指定宽高
在Flutter中,如何将图片压缩到指定的宽度和高度?我尝试使用flutter_image_compress插件,但压缩后的图片尺寸总是不准确。有没有可靠的方法能精确控制输出图片的宽高,同时保持较好的画质?最好能提供具体的代码示例。
        
          2 回复
        
      
      
        使用Flutter压缩图片到指定宽高,推荐使用flutter_image_compress库。步骤如下:
- 添加依赖到pubspec.yaml。
- 使用FlutterImageCompress.compressAndGetFile()方法,传入原图路径、目标路径和宽高参数即可。
示例代码:
import 'package:flutter_image_compress/flutter_image_compress.dart';
Future<File> compressImage(File file, int width, int height) async {
  var result = await FlutterImageCompress.compressAndGetFile(
    file.absolute.path,
    file.path + '_compressed.jpg',
    minWidth: width,
    minHeight: height,
  );
  return result;
}
更多关于flutter如何压缩图片到指定宽高的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中压缩图片到指定宽高,可以使用image包进行处理。以下是具体实现方法:
1. 添加依赖
在 pubspec.yaml 中添加:
dependencies:
  image: ^4.0.17
2. 实现代码
import 'dart:io';
import 'package:image/image.dart' as img;
Future<File> compressImageToSize(
  File imageFile, 
  int targetWidth, 
  int targetHeight,
  {int quality = 85}
) async {
  // 读取原始图片
  final List<int> imageBytes = await imageFile.readAsBytes();
  img.Image? originalImage = img.decodeImage(imageBytes);
  
  if (originalImage == null) {
    throw Exception('无法解码图片');
  }
  
  // 调整尺寸
  img.Image resizedImage = img.copyResize(
    originalImage,
    width: targetWidth,
    height: targetHeight,
  );
  
  // 编码为JPEG格式(可调整质量)
  List<int> compressedBytes = img.encodeJpg(resizedImage, quality: quality);
  
  // 保存压缩后的图片
  String compressedPath = '${imageFile.path}_compressed.jpg';
  File compressedFile = File(compressedPath);
  await compressedFile.writeAsBytes(compressedBytes);
  
  return compressedFile;
}
3. 使用方法
// 压缩图片到 300x200 像素
File originalImage = File('/path/to/your/image.jpg');
File compressedImage = await compressImageToSize(originalImage, 300, 200);
// 使用压缩后的图片
Image.file(compressedImage);
主要参数说明
- targetWidth、- targetHeight:目标宽高
- quality:图片质量(1-100),数值越小压缩率越高
- 支持多种格式:JPEG、PNG、WebP等
这种方法可以有效地将图片压缩到指定尺寸,同时保持较好的视觉效果。
 
        
       
             
             
            

