I am trying to convert HTML to image,
I tried this via the screenshot, but when the html is height than the display screen, the image is cropped
/// Convert Html to Image
Future<File> htmlToImage(
String html, String targetPath, String fileName) async {
Uint8List img = await screenshotController.captureFromWidget(MediaQuery(
data: const MediaQueryData(),
child: Html(
shrinkWrap: true,
data: html,
),
));
File file = await File('$targetPath/$fileName.jpg').create();
file.writeAsBytesSync(img);
return file;
}
Is there a better way to achieve this, or can this problem be solved
Related
hey guys I need to convert image from pdf file!
i have an experience image to pdf but
Future<void> addPage(pw.Document pdf, String filename) async {
final imageByteData = await rootBundle.load('assets/$filename');
// Convert ByteData to Uint8List
final imageUint8List = imageByteData.buffer.asUint8List(imageByteData.offsetInBytes, imageByteData.lengthInBytes);
final image = pw.MemoryImage(imageUint8List);
pdf.addPage(
pw.Page(
build: (pw.Context context) {
return pw.Center(
child: pw.Image(image),
); // Center
},
),
);
}
i have tried this kind of solution didn't work as I want
so for examople if i have 3 files in pdf file I need to change each files to image and display it
How do I load AssetImage or check if it exists? The data is coming from the api, so I cannot list all the file paths as constants.
As an example path maybe be 'assets/images/${card.imageType}.png' where card.inageType is a variable.
...
child: Image(
height: 60.0,
image: Utils.getImage('assets/images/card-${card.category}.png'),
),
...
For my getImage function, I tried 2 kinds but not working
Method 1: Using File: The existsSync method is always false. Keep in mind the await async cannot work as the Image widget is expecting not a Future
static dynamic getImage(path) {
File f = File(path);
return f.existsSync()
? FileImage(f)
: const AssetImage('assets/images/default.png');
}
}
Method 2: Using try catch: The exceptions is not being caught
static AssetImage getImage(path) {
AssetImage image;
try {
image = AssetImage(path);
} catch (e) {
image = const AssetImage('assets/images/default.png');
}
return image;
}
You can use something like this to check if an asset exists:
// example: 'assets/check_green.png'
Future<bool> checkIfAssetExists(String fullAssetPath) async {
final Uint8List encoded = Utf8Codec()
.encoder
.convert(Uri(path: Uri.encodeFull(fullAssetPath)).path);
// returns null if an asset is not found
final ByteData? asset = await ServicesBinding.instance!.defaultBinaryMessenger
.send('flutter/assets', encoded.buffer.asByteData());
return asset != null;
}
You can run this in your initState and then use AssetImage confidently.
As for the exception not being caught, it probably means than an Error was throw which is different from Exceptions
You can check if a file exists asynchronously with this code:
import 'dart:io';
File("path/to/file").exists()
or checking it synchronously:
import 'dart:io';
File("path/to/file").existsSync()
Update:
isPathExists() function is called from initState.
AssetBundle is used for to obtain asset inside asset folder. You can insert anything to menubanner.png if it exists, the image will be assigned to variable and if it does not, an exception throws.
late Image image;
isPathExists() async {
try {
var assetbundle = DefaultAssetBundle.of(context);
ByteData res = await assetbundle.load('assets/images/menubanner.png');
var list = Uint8List.sublistView(res);
setState(() {
image = Image.memory(list);
});
} catch (exception) {
print(exception);
}
}
You can not use Asset Image for images fetched from Network.
Once you get response from your api. Store the url of the image in a String variable. Usually images from API are stored in a web service.
When you have the url of the image just use NetworkImage widget, example:
SizedBox(
width: 75,
height: 75,
child: userImgUrl.isEmpty
? const CircleAvatar(
child: Text('Avatar'))
: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(
userImgUrl),
backgroundColor: Colors.transparent),)
Think userImgUrl is the String that holds the url for the image that can be found on the internet. If image is empty just show a text inside circle avatar. If image is available from API, then show the image inside NetworkImage()
I am simply picking image from image_picker package like this
_imgFromCamera() async {
File image = await ImagePicker.pickImage(
source: ImageSource.camera, imageQuality: 50
);
final bytes = image.readAsBytesSync();
String base64Image = base64Encode(bytes);
print(base64Image);
setState(() {
_image = image;
});
}
You can see I have convert image in the string also. I need to know how can I show this string as an image? Because I save this string on other page now I need to show is an image
You can convert the base64 string into a file using
import `dart:covert`
Uint8List bytes = base64decode(_base64);
and then display it using the widget
Image.memory(bytes),
You can just write it in a single line but I split it for the sake of readability
Image.memory(base64Decode(base64String));
I am trying to generate an image using RenderRepaintBoundary and want to save the image in my local directory.
I am able to save the image but I get a black image instead of a QR image.
Code block where I am writing the image to the directory:
try {
RenderRepaintBoundary boundary =
globalKey.currentContext.findRenderObject();
var image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
final file =
await new File('/<localpath>/image.png').create();
await file.writeAsBytes(pngBytes);
} catch (e) {
print(e);
}
Code block where QR code is being generated:
RepaintBoundary( key: globalKey,child: QrImage(data: _dataString,size: 0.3 * bodyHeight,), );
This is caused by having transparent background;
Simple solution is to wrap your QrImage with Container that has white backround:
Container(
color: Colors.white,
child: QrImage(....
)
I'm trying to capture an image, then send path of the image to a function that returns the image in Base64. For capturing an image I'm using the example on Flutter website.
Future _takePhoto(BuildContext context) async {
try {
await _initializeControllerFuture;
final path = join(
(await getTemporaryDirectory()).path,
'${DateTime.now()}.png',
);
await _cameraController.takePicture(path);
setState(() {
_imagePath = path;
});
} catch (e) {
print(e);
}
}
It's working well. I can see the captured image in widget Image.file(File(_imagePath))
The problem starts when I'm trying to convert the image into Base64.
File file = File(_imagePath);
final _imageFile = ImageProcess.decodeImage(
file.readAsBytesSync(),
);
String base64Image = base64Encode(ImageProcess.encodePng(_imageFile));
print(base64Image);
I copy and paste the printed message into an online tool that generates an image from Base64 and either it's all black or there is tiny top layer of the image and the rest is black.
print function did not print everything.
you can see full result with debug mode
and copy paste full result in debug mode to online tool
This should print your image as a base64 string
import 'dart:typed_data';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
File file = File(_imagePath);
Uint8List bytes = file.readAsBytesSync();
String base64Image = base64Encode(bytes);
print(base64Image);
To show base64 print:
import 'dart:developer' as developer;
developer.log(
'log me',
name: 'my.app.category',
error: jsonEncode(base64Image),
);