如何在Flutter中裁剪图像?

jrcvhitl  于 2023-02-25  发布在  Flutter
关注(0)|答案(8)|浏览(199)

假设我有一个矩形的纵向图像:

我想裁剪它,使它呈现为这样:

我如何在Flutter中做到这一点?
(我不需要调整图像大小。)
(图片来自https://flic.kr/p/nwXTDb

1sbrub3j

1sbrub3j1#

我可能会将BoxDecorationDecorationImage一起使用,您可以使用alignmentfit属性来确定图像的裁剪方式,如果您不想在Container上硬编码高度,则可以使用AspectRatio小部件。

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Image Crop Example"),
      ),
      body: new Center(
        child: new AspectRatio(
          aspectRatio: 487 / 451,
          child: new Container(
            decoration: new BoxDecoration(
              image: new DecorationImage(
                fit: BoxFit.fitWidth,
                alignment: FractionalOffset.topCenter,
                image: new NetworkImage('https://i.stack.imgur.com/lkd0a.png'),
              )
            ),
          ),
        ),
      ),
    );
  }
}
vlurs2pr

vlurs2pr2#

您还可以直接将Image类与BoxFit一起使用,并执行如下操作:

new Image.asset(
  stringToImageLocation,
  fit: BoxFit.cover,
)
sc4hvdpw

sc4hvdpw3#

Image小部件提供一个fit因子,然后将其 Package 在AspectRatio中。

AspectRatio(
  aspectRatio: 1.5, 
  child: Image.asset(
    'your_image_asset',
    fit: BoxFit.cover,
  ),
)
j91ykkif

j91ykkif4#

看看brendan-duncan/image,它是一个独立于平台的库,用于在Dart中操作图像。
您可以使用函数:

Image copyCrop(Image src, int x, int y, int w, int h);
a9wyjsp7

a9wyjsp75#

仅使用以下2个属性对我有效:

CachedNetworkImage(
  fit: BoxFit.cover,// OR BoxFit.fitWidth
  alignment: FractionalOffset.topCenter,
  ....
)
shyt4zoc

shyt4zoc6#

有一个新的软件包叫ImageCropper。我建议大家使用这个软件包,因为它有很多功能,让一切变得更容易。它允许你裁剪图像到任何或指定的长宽比,你想要的,甚至可以压缩图像。这里是链接到该软件包:https://pub.dev/packages/image_cropper

xkftehaa

xkftehaa7#

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  /// Variables
  File imageFile;

  /// Widget
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0XFF307777),
          title: Text("Image Cropper"),
        ),
        body: Container(
            child: imageFile == null
                ? Container(
                    alignment: Alignment.center,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        RaisedButton(
                          color: Color(0XFF307777),
                          onPressed: () {
                            _getFromGallery();
                          },
                          child: Text(
                            "PICK FROM GALLERY",
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ],
                    ),
                  )
                : Container(
                    child: Image.file(
                      imageFile,
                      fit: BoxFit.cover,
                    ),
                  )));
  }

  /// Get from gallery
  _getFromGallery() async {
    PickedFile pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    _cropImage(pickedFile.path);
  }

  /// Crop Image
  _cropImage(filePath) async {
    File croppedImage = await ImageCropper.cropImage(
      sourcePath: filePath,
      maxWidth: 1080,
      maxHeight: 1080,
    );
    if (croppedImage != null) {
      imageFile = croppedImage;
      setState(() {});
    }
  }
}
v6ylcynt

v6ylcynt8#

在这里我裁剪文件到广场。
我使用image库。

import 'dart:io';
import 'package:image/image.dart' as img;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

class CropperService {
  static const _side = 1800;

  Future<File> cropImageFile(File file, [int? side]) async {
    final image = await img.decodeImageFile(file.path);
    if (image == null) throw Exception('Unable to decode image');
    final croppedImage = img.copyResizeCropSquare(image, size: _side);
    final croppedFile = await _convertImageToFile(croppedImage, file.path);
    return croppedFile;
  }

  Future<File> _convertImageToFile(img.Image image, String path) async {
    final newPath = await _croppedFilePath(path);
    final jpegBytes = img.encodeJpg(image);

    final convertedFile = await File(newPath).writeAsBytes(jpegBytes);
    await File(path).delete();
    return convertedFile;
  }

  Future<String> _croppedFilePath(String path) async {
    final tempDir = await getTemporaryDirectory();
    return join(
      tempDir.path,
      '${basenameWithoutExtension(path)}_compressed.jpg',
    );
  }
}

相关问题