Created
August 12, 2021 14:28
-
-
Save lslv1243/6e5e3ab44ce0e2e834ceac6d9123edfe to your computer and use it in GitHub Desktop.
Flutter Image Editor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:typed_data'; | |
import 'dart:ui'; | |
const _BYTES_PER_PIXEL = 4; | |
class ImageEditor { | |
final int imageWidth; | |
final int imageHeight; | |
final ByteData _byteData; | |
ImageEditor._( | |
this.imageWidth, | |
this.imageHeight, | |
this._byteData, | |
); | |
ImageEditor(this.imageWidth, this.imageHeight) | |
: _byteData = ByteData(imageWidth * imageHeight * _BYTES_PER_PIXEL); | |
static Future<ImageEditor?> load(Image image) async { | |
final byteData = await image.toByteData(); | |
if (byteData == null) return null; | |
return ImageEditor._(image.width, image.height, byteData); | |
} | |
Future<Image> render() async { | |
final bytes = _byteData.buffer.asUint8List( | |
_byteData.offsetInBytes, | |
_byteData.lengthInBytes, | |
); | |
final completer = Completer<Image>(); | |
decodeImageFromPixels( | |
bytes, | |
imageWidth, | |
imageHeight, | |
PixelFormat.rgba8888, | |
completer.complete, | |
); | |
return completer.future; | |
} | |
Color getColor(int x, int y) { | |
final byteOffset = (y * imageWidth + x) * _BYTES_PER_PIXEL; | |
final bytes = _byteData.getUint32(byteOffset); | |
final r = (bytes & 0xFF << 24) >> 24; | |
final g = (bytes & 0xFF << 16) >> 16; | |
final b = (bytes & 0xFF << 08) >> 08; | |
final a = (bytes & 0xFF << 00) >> 00; | |
return Color.fromARGB(a, r, g, b); | |
} | |
void setColor(Color color, int x, int y) { | |
final byteOffset = (y * imageWidth + x) * _BYTES_PER_PIXEL; | |
final a = color.alpha; | |
final r = color.red; | |
final g = color.green; | |
final b = color.blue; | |
_byteData.setUint8(byteOffset + 0, r); | |
_byteData.setUint8(byteOffset + 1, g); | |
_byteData.setUint8(byteOffset + 2, b); | |
_byteData.setUint8(byteOffset + 3, a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment