RGB가 아니라 RGBA(A:투명도)라서 i+4 해야함
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as Img;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
Widget build(BuildContext context) {
return Scaffold(
// body: Image.asset("assets/aaaa.png"),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// BlendMode 위젯을 통해 이미지 변환 수행
BlendMode(
removeColorRGB: [255, 0, 0],
addColorRGB: [33, 33, 33],
),
],
),
),
);
}
}
class BlendMode extends StatelessWidget {
final List<int> removeColorRGB;
final List<int> addColorRGB;
const BlendMode({required this.removeColorRGB, required this.addColorRGB, super.key});
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, required List<int> removeColorRGB, required 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]) {
// if (pixels[i] == removeColorRGB[0] && pixels[i + 1] == removeColorRGB[1] && pixels[i + 2] == removeColorRGB[2] && pixels[i + 3] == 255) {
pixels[i] = addColorRGB[0];
pixels[i + 1] = addColorRGB[1];
pixels[i + 2] = addColorRGB[2];
}
}
return src;
}
convertImage() async {
ByteData imageData1 = await rootBundle.load("assets/cccc.png");
Uint8List bytes = imageData1.buffer.asUint8List();
// Uint8List newbyte = await AppUtils.changeBackgroundOfImage(bytes: bytes, removeColorRGB: [0, 0, 0], addColorRGB: [66, 245, 120]);
Uint8List newbyte = await changeBackgroundOfImage(bytes: bytes, removeColorRGB: removeColorRGB, addColorRGB: addColorRGB);
return newbyte;
}
Widget build(BuildContext context) {
return FutureBuilder(
future: convertImage(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// 이미지 변환 결과를 Image.memory로 표시
// return Image.memory(snapshot.data as Uint8List);
if (snapshot.data != null) {
return Image.memory(snapshot.data! as Uint8List);
} else {
// 데이터가 아직 로드되지 않은 경우에 대한 처리
return CircularProgressIndicator();
}
} else {
// 로딩 중이면 로딩 스피너 표시
return CircularProgressIndicator();
}
},
);
}
}