如何在Flutter/Dart中将资源图像转换为位图?

3

我需要比较两张图片,因此我需要将这两张图片(资源)解码为位图。 我尝试了以下方法:

import 'package:flutter/services.dart';
import 'package:image/image.dart';

var imageData = await rootBundle.load("assets/images/test.png");
Image firstImage = Image.fromBytes(100, 100, imageData.buffer.asUint8List());
int pixel = firstImage.getPixel(5, 0);
print('$pixel');

但是它不起作用,因为在将getPixel(x, y)的第二个参数设为除0以外的任何值之后,它都会抛出异常:

E/flutter (11752): [ERROR:flutter/shell/common/shell.cc(199)] Dart Error: Unhandled exception:
E/flutter (11752): RangeError (index): Index out of range: index should be less than 86: 101
E/flutter (11752): #0      _Uint32ArrayView.[] (dart:typed_data-patch/typed_data_patch.dart:3999:7)
E/flutter (11752): #1      Image.getPixel (package:image/src/image.dart:409:37)

我尝试了这种方式:

Image firstImage = decodeImage(new File('assets/images/test.png').readAsBytesSync());
int pixel = firstImage.getPixel(1, 1);
print('$pixel');

但是出现了下一个异常:

E/flutter (11752): FileSystemException: Cannot open file, path = 'assets/images/test.png' (OS Error: No such file or directory, errno = 2)

因此,我正在寻找一种解决方案,可以帮助我将资产转换为位图,以便我可以获取每个图像像素的颜色。

1个回答

3

试试这个:

import 'package:image/image.dart' as img;

...

ByteData imageBytes = await rootBundle.load('assets/images/test.png');
List<int> values = imageBytes.buffer.asUint8List();
img.Image photo;
photo = img.decodeImage(values);
int pixel = photo.getPixel(5, 0);

我可以使用SVG替代PNG吗? - saddam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接