首先需要安装Image包
导入包
import 'package:image/image.dart' as Img;
然后使用下面的代码来改变图片的背景颜色
Future<Uint8List> changeBackgroundOfImage(
{@required Uint8List bytes,
@required List<int> removeColorRGB,
@required List<int> addColorRGB}) async {
Img.Image image = Img.decodeImage(bytes);
Img.Image newImage = await _customeColor(
src: image, removeColorRGB: removeColorRGB, addColorRGB: addColorRGB);
var newPng = Img.encodePng(newImage);
return newPng;
}
Future<Img.Image> _customeColor(
{Img.Image src, List<int> removeColorRGB, List<int> addColorRGB}) async {
var pixels = src.getBytes();
for (int i = 0, len = pixels.length; i < len; i += 4) {
if (pixels[i] == removeColorRGB[0] &&
pixels[i + 1] == removeColorRGB[1] &&
pixels[i + 2] == removeColorRGB[2]) {
pixels[i] = addColorRGB[0];
pixels[i + 1] = addColorRGB[1];
pixels[i + 2] = addColorRGB[2];
}
}
return src;
}
注意:上面的函数需要三个参数,第一个是图像字节,第二个和第三个是removeColorRGB,addColorRGB是一个RGB值的List,见下面的代码行
Uint8List newbyte = await changeBackgroundOfImage(
bytes: bytes, removeColorRGB: [0, 0, 0], addColorRGB: [66, 245, 120]);
完整代码:
import 'package:image/image.dart' as Img;
class BlendMode extends StatelessWidget {
static Future<Uint8List> changeBackgroundOfImage(
{@required Uint8List bytes,
@required List<int> removeColorRGB,
@required List<int> addColorRGB}) async {
Img.Image image = Img.decodeImage(bytes);
Img.Image newImage = await _customeColor(
src: image, removeColorRGB: removeColorRGB, addColorRGB: addColorRGB);
var newPng = Img.encodePng(newImage);
return newPng;
}
static Future<Img.Image> _customeColor(
{Img.Image src, List<int> removeColorRGB, List<int> addColorRGB}) async {
var pixels = src.getBytes();
for (int i = 0, len = pixels.length; i < len; i += 4) {
if (pixels[i] == removeColorRGB[0] &&
pixels[i + 1] == removeColorRGB[1] &&
pixels[i + 2] == removeColorRGB[2]) {
pixels[i] = addColorRGB[0];
pixels[i + 1] = addColorRGB[1];
pixels[i + 2] = addColorRGB[2];
}
}
return src;
}
convertImage() async {
ByteData imageData1 = await rootBundle.load("assets/images/Vgv5e.png");
Uint8List bytes = imageData1.buffer.asUint8List();
Uint8List newbyte = await AppUtils.changeBackgroundOfImage(
bytes: bytes, removeColorRGB: [0, 0, 0], addColorRGB: [66, 245, 120]);
return newbyte;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: FutureBuilder(
future: convertImage(),
builder: (context, snapshot) => Image.memory(snapshot.data)),
),
);
}
}
重要提示:重要的是您的图片背景必须是一种颜色,这意味着背景不应采用阴影或渐变来完全去除背景颜色