PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How to Make image from flutter material widget on server side

 July 30, 2022     dart, flutter, flutter-test, image, widget     No comments   

Issue

I have tried several times but failed, I have also dissected the [image] and pdf libraries, but I don't understand how to create a widget to an image on the server side only,

does anyone know how to make a widget to an image on serverside only?

here's the code I tried

import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui; 
void main() async {
  GlobalKey globalKey = GlobalKey();
  RepaintBoundary(
    key: globalKey,
    child: Container(
      padding: const EdgeInsets.all(50),
      child: const Text(
        "Hello world",
      ),
    ),
  );
  RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
  ui.Image image = await boundary.toImage();
  ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  Uint8List pngBytes = byteData!.buffer.asUint8List();
  print(pngBytes);
}
 

Solution

Flutter isn't meant to be used on the server side, but if you simply want to render an image with some text on the server, there are dart libraries for that.

For example, using the image library, you can do something like this:

import 'dart:io';

import 'package:image/image.dart';

void main() {
  final white = 0xFFFFFFFF;
  final black = 0xFF000000;

  final whiteRect = fill(Image(200, 100), white);

  final helloWorld = drawStringCentered(
    whiteRect,
    arial_24,
    "Hello, World!",
    color: black,
  );

  final data = encodePng(helloWorld);

  final file = File('test.png');

  // Save the image to '$PROJECT_ROOT/test.png'
  file.writeAsBytes(data);
}

Which will create this output:

Hello World image



Answered By - Michael Horn
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing