Flutter Custom Painter - missing offset in coefficient calculation - flutter

first i transform my image file to dart:ui image. then i set sizes i will be using with this method
void setSizes() async {
imgOgSize =
Size(image.value!.width.toDouble(), image.value!.height.toDouble());
double wDiff = imgOgSize!.width - Get.width;
double hDiff = imgOgSize!.height - Get.height;
if (wDiff > hDiff) {
coef.value = imgOgSize!.width / Get.width;
canvasSize =
Size(imgOgSize!.width / coef.value, imgOgSize!.height / coef.value);
} else {
coef.value = imgOgSize!.height / Get.height;
canvasSize =
Size(imgOgSize!.width / coef.value, imgOgSize!.height / coef.value);
}
print(coef.value);
// canvasSize = Size(
// min(imgOgSize!.width, Get.width), min(imgOgSize!.height, Get.height));
}
my logic is finding size, that needs to be shrank more than the other and using it as a coefficient, because if i wanted to use fit: BoxFit.scaleDown i would not know what the coefficient would end up being.
the image is ready to be used on canvas, but i also need to get a list of points.
here is how i get the points
GestureDetector(
onPanDown: (detailData) {
controller.editor.value!.update(detailData.localPosition);
controller.canvasKey.currentContext!
.findRenderObject()!
.markNeedsPaint();
},
onPanUpdate: (detailData) {
controller.editor.value!.update(detailData.localPosition);
controller.canvasKey.currentContext!
.findRenderObject()!
.markNeedsPaint();
},
child: CustomPaint(
key: controller.canvasKey,
painter: controller.editor.value,
size: controller.canvasSize!,
),
)
now the overriden paint function looks like this with fullSize being false
void paint(Canvas canvas, Size size) {
final imageSize = Size(image.width.toDouble(), image.height.toDouble());
final src = Offset.zero & imageSize;
final dst = Offset.zero & size;
// canvas.drawImageRect(image, src, dst, Paint());
paintImage(
canvas: canvas,
rect: dst,
image: image,
// fit: BoxFit.scaleDown,
repeat: ImageRepeat.noRepeat,
scale: 1 / coef,
alignment: Alignment.center,
flipHorizontally: false,
filterQuality: FilterQuality.high,
);
for (Offset offset in points) {
if (fullSize) {
Offset of = Offset(offset.dx * coef, offset.dy * coef);
canvas.drawCircle(of, 10 * coef, painter);
} else {
canvas.drawCircle(offset, 10, painter);
}
}
}
result:
but now, when i want to export it with this function with image's original height and width, to have full quality picture (using imgOgSize instead of canvasSize)
Future<ui.Image> getImage() async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
editor.value!.fullSize = true;
editor.value!.paint(Canvas(recorder), imgOgSize!);
editor.value!.fullSize = false;
final ui.Picture picture = recorder.endRecording();
ui.Image genImg = await picture.toImage(
imgOgSize!.width.toInt(), imgOgSize!.height.toInt());
// ui.Image genImg = await picture.toImage(canvasSize!.width.toInt(), canvasSize!.height.toInt());
final pngBytes = await genImg.toByteData(format: ui.ImageByteFormat.png);
final buffer = pngBytes!.buffer;
await File('/data/user/0/app/app_flutter/t1.png')
.delete();
await File('/data/user/0/app/app_flutter/t1.png')
.writeAsBytes(
buffer.asUint8List(pngBytes.offsetInBytes, pngBytes.lengthInBytes));
Get.find<HomeController>().imageViewPath.refresh();
Get.to(() => ImageView());
return await picture.toImage(
imgOgSize!.width.toInt(), imgOgSize!.height.toInt());
}
this is the exported .png result
am i calculating the coefficient wrong? or is there some offset im not taking in account? help please. i also can provide more code if something important is missing, let me know please.

edit: this answer works for phone orientation portrait, not landscape, which somehow still does not work. therefore i'm leaving the question open if someone can help.
i calculated the size wrong.
this is the correct setSizes()
void setSizes() {
imgOgSize =
Size(image.value!.width.toDouble(), image.value!.height.toDouble());
double wC = imgOgSize!.width / Get.width;
ouble hC = imgOgSize!.height / (Get.height - appBar.preferredSize.height);
if (wC > hC) {
coef.value = wC;
canvasSize =
Size(imgOgSize!.width / coef.value, imgOgSize!.height / coef.value);
} else {
coef.value = hC;
canvasSize =
Size(imgOgSize!.width / coef.value, imgOgSize!.height / coef.value);
}
print(coef.value);
// canvasSize = Size(
// min(imgOgSize!.width, Get.width), min(imgOgSize!.height, Get.height));
}

Related

Mask out color in Image canvas flutter

I am trying to add skin tone to an image in flutter canvas.
I've used the following code before to apply chroma by altering pixels when I load the image:
static Future<ui.Image> applyChromaToImage(ui.Image image, String pathForImage, RGBPixel chromaToApply, {RGBPixel previousChromaColor}) async
{
List<ChromaPointRange> chromaPoints = processChromaImageBytes(
image, imgBytes);
for(ChromaPointRange rnge in chromaPoints)
{
for(int y = rnge.yValStart; y <= rnge.yValEnd; y++)
{
RGBPixel currentPixel = RGBPixel.generatePixelFromImagePos(imgBytes, image.width, rnge.xVal, y);
//replace current pixel with skin tone
RGBPixel newPixl = currentPixel.mergeSkinTonePixel(chromaToApply, previousChromaColor);
imgBytes.setUint32((y * image.width + rnge.xVal) * 4, newPixl.getHex());
}
}
final Completer<ui.Image> imageCompleter = new Completer();
//looks the endian format doesn't get set right here
ui.PixelFormat formatToUse = Endian.host == Endian.little ? ui.PixelFormat.rgba8888 : ui.PixelFormat.bgra8888;
ui.decodeImageFromPixels(
imgBytes.buffer.asUint8List(),
image.width,
image.height,
formatToUse,
(ui.Image result) {
imageCompleter.complete(result);
// use your result image
},
);
//return image;
return await imageCompleter.future;
}
static List<ChromaPointRange> processChromaImageBytes(ui.Image image, ByteData imgBytes)
{
List<ChromaPointRange> chromaPoints = [];
ChromaPointRange currentPoints = null;
for(int x = 0; x < image.width; x = x + 1)
{
for(int y = 0; y < image.height; y = y + 1)
{
RGBPixel currentPixel = RGBPixel.generatePixelFromImagePos(imgBytes, image.width, x, y);
if(currentPixel.isSkinTonePixel())
{
if(currentPoints == null)
{
currentPoints = ChromaPointRange.fromEmpty();
currentPoints.xVal = x;
currentPoints.yValStart = y;
}
}
else if(currentPoints != null)
{
currentPoints.yValEnd = y - 1;
chromaPoints.add(currentPoints);
currentPoints = null;
}
}
if(currentPoints != null)
{
currentPoints.yValEnd = image.height - 1;
chromaPoints.add(currentPoints);
currentPoints = null;
}
}
return chromaPoints;
}
which basically checks every pixel in the image to see if it's within a range of the target color ( with is RGB 0, 255, 0), then adjusts the pixel if it is. This works, but takes a really long time ~ 3 seconds for a 1920 x 1080 image.
The end result is that I want to paint the image to a canvas with a skin tone applied. I've tried a different strategy, by painting the color underneath the image, and then trying to mask out that color from the image using canvas color filters. This is 1000% faster, but doesn't quite work.
Here is the code:
renderSprite(Canvas canvasToRender, Offset offsetToRender)
{
Paint imgPaint = new Paint();
if(chromaToApply != null)
{
Paint chromaPaint = new Paint();
chromaPaint.colorFilter = ColorFilter.mode(Color.fromRGBO(chromaToApply.redVal, chromaToApply.greenVal, chromaToApply.blueVal, 1), BlendMode.modulate);
canvasToRender.drawImage(spriteImage, offsetToRender, chromaPaint);
imgPaint.colorFilter = ColorFilter.mode(Color.fromRGBO(0, 255, 0, 1), BlendMode.dstOut);
}
if(spriteImage != null)
canvasToRender.drawImage(spriteImage, offsetToRender, imgPaint);
}
Here is the image that is painted underneath
Here is the image that is painted ontop
So I'm trying to mask out the green so the tan skin tone shows through on specific parts of the image.
I can't seem to find any combination of ColorFilter or anything else that will mask out the green color for me from the canvas. Any suggestions?

Drawing curved corner borders in Flutter with dart:ui Canvas

I am using the https://pub.dev/packages/ncnn_yolox_flutter package for object detection in my Flutter app. I want the border outline of detections to look similar to the image below; curved corners only. (Different opacity not necessary, although if anyone knows how to draw that dynamically I would be interested).
What I'm looking for:
I currently have two options working.
Curved corners, but drawing the entire rectangle... Code and picture below (e references my detection results and drawRectPaint is my decoration):
final rect = ui.Rect.fromLTWH(
e.x,
e.y,
e.width,
e.height,
);
canvas.drawRRect(
RRect.fromRectAndRadius(rect, Radius.circular(10.0)),
drawRectPaint,
);
Corners only but without the curve. (Code for just the top left corner below):
var topLeftPath = Path();
topLeftPath.addPolygon([
Offset((e.x), (e.y + 40)),
Offset((e.x), (e.y)),
Offset((e.x + 40), (e.y)),
], false);
canvas.drawPath(
topLeftPath,
drawRectPaint,
);
You have to use moveTo, lineTo and arcTo to draw border outlines with rounded corners. You need to adjust the values to your needs.
Try this:
topLeftPath.moveTo(e.x, 40);
topLeftPath.relativeLineTo(e.x, -20);
topLeftPath.arcTo(
Rect.fromCenter(
center: Offset(20,20),
width: 40,
height: 40
), math.pi, math.pi/2, false);
topLeftPath.relativeLineTo(20, e.y);
canvas.drawPath(topLeftPath,drawRectPaint);
Clever use of PathFillType.evenOdd to darken the outside, and arcTo for the outer lines:
https://dartpad.dartlang.org/?id=20afacc59439722a28c2f7ccea4782bf
class ViewfinderPainter extends CustomPainter {
#override
void paint(Canvas canvas, Size size) {
final canvasRect = Offset.zero & size;
const rectWidth = 300.0;
final rect = Rect.fromCircle(
center: canvasRect.center,
radius: rectWidth / 2,
);
const radius = 16.0;
const strokeWidth = 6.0;
const extend = radius + 24.0;
const arcSize = Size.square(radius * 2);
canvas.drawPath(
Path()
..fillType = PathFillType.evenOdd
..addRRect(
RRect.fromRectAndRadius(
rect,
const Radius.circular(radius),
).deflate(strokeWidth / 2),
)
..addRect(canvasRect),
Paint()..color = Colors.black26,
);
canvas.save();
canvas.translate(rect.left, rect.top);
final path = Path();
for (var i = 0; i < 4; i++) {
final l = i & 1 == 0;
final t = i & 2 == 0;
path
..moveTo(l ? 0 : rectWidth, t ? extend : rectWidth - extend)
..arcTo(
Offset(l ? 0 : rectWidth - arcSize.width,
t ? 0 : rectWidth - arcSize.width) &
arcSize,
l ? pi : pi * 2,
l == t ? pi / 2 : -pi / 2,
false)
..lineTo(l ? extend : rectWidth - extend, t ? 0 : rectWidth);
}
canvas.drawPath(
path,
Paint()
..color = Colors.deepOrange
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke,
);
canvas.restore();
}
#override
bool shouldRepaint(ViewfinderPainter oldDelegate) => false;
}

Converting matrix of colors to image in flutter

I need to convert List<List<int>>> to an dart:ui.Image. I have an algorithm to convert an integer to a color. I tried to do this by drawing one-pixel rectangles on the dart:ui.Canvas, but it is about 100 times slower than I expected! _getPixelColor is the method by which I convert int to Color. Here is my code:
Future<void> matrixToImage(FField sourceMatrix) async {
PictureRecorder p = PictureRecorder();
Canvas c = Canvas(
p,
Rect.fromLTWH(0, 0, sourceMatrix.length.toDouble(),
sourceMatrix[0].length.toDouble()));
Paint paint = Paint();
for (int x = 0; x < sourceMatrix.length; x++) {
for (int y = 0; y < sourceMatrix[0].length; y++) {
int pixelValue = sourceMatrix[x][y];
paint.color = _getPixelColor(pixelValue / 40 / paletteLength + paletteOffset);
c.drawRect(Rect.fromLTWH(x.toDouble(), y.toDouble(), 1, 1), paint);
}
}
Picture picture = p.endRecording();
Image result = await picture.toImage(sourceMatrix.length, sourceMatrix[0].length);
}
If you can compute your int value to an int value that the Image class understands, you don't need the detour through canvas drawing.
Just use Image.fromBytes with the .value of the Color as the list of ints.
That depends on how the image data is stored in the list of INTs.
Generally, I like this package to manipulate images and display them:
https://pub.dev/packages/image
import 'package:image/image.dart' as im;
im.Image? img = decodeImage(bytes); // different-IMAGE class !
Uint8List uint8list = getEncodedJpg(img!,quality: 85) as Uint8List;
// ...
build(BuildContext context) {
return Container(child:
Image.memory(uint8list) // material-IMAGE class !
);
}

How to draw a list of images with circular border in dart canvas?

I need to draw a list of images with canvas, and I need that each image has a circular border:
expected:
but what I implemented is:
my code is:
for (int i = 0; i < participants.length; i++) {
Completer<ui.Image> completer = Completer<ui.Image>();
Image networkImage = Image.network(participants[i]?.avatar ?? "");
networkImage.image
.resolve(const ImageConfiguration())
.addListener(ImageStreamListener((ImageInfo info, bool _) {
canvas.drawImageNine(info.image, const Rect.fromLTRB(0, 0, 0, 0),
Rect.fromLTRB(10+(i*20), 50, (participants.length * 20 )+ 50, 100), Paint());
completer.complete(info.image);
}));
}
I use canvas.clipPath() before canvas.drawImage() too:
Path path = Path()..addOval(const Rect.fromLTWH(10, 50, 50+(i*50), 50));
canvas.clipPath(path);
it clipped whole the list:
Please give me some help if you have any ideas.

flutter - add network images in a pdf while creating it in flutter

hello guys i m trying to add network images or url of images while my pdf is being created.
basically i m tying to achieve when a user clicks on download button in my cart all the products in my cart should be added along with the images of it , so far images are not getting added but the other details are added in the pdf.
i m using syncfusion pdf to create a pdf n my pdf is creating successfully.
i want to add images also with it.
my logic was to download the images n then add it to the pdf but it is getting crashed somehow.
i used below packages
https://pub.dev/packages/syncfusion_flutter_pdf
https://pub.dev/packages/image_downloader
below is the code i have tried
List<File> _mulitpleFiles = [];
Future<void> generateInvoice() async {
//Create a PDF document.
final PdfDocument document = PdfDocument();
//Add page to the PDF
final PdfPage page = document.pages.add();
//Get page client size
final Size pageSize = page.getClientSize();
//Draw rectangle
page.graphics.drawRectangle(
bounds: Rect.fromLTWH(0, 0, pageSize.width, pageSize.height),
pen: PdfPen(PdfColor(142, 170, 219, 255)));
//Generate PDF grid.
final PdfGrid grid = getGrid();
//Draw the header section by creating text element
final PdfLayoutResult result = drawHeader(page, pageSize, grid);
//Draw grid
drawGrid(page, grid, result);
//Add invoice footer
drawFooter(page, pageSize);
//Save the PDF document
final List<int> bytes = document.save();
//Dispose the document.
document.dispose();
//Get external storage directory
Directory directory = (await getExternalStorageDirectory());
//Get directory path
String path = directory.path;
print(path);
//Create an empty file to write PDF data
File file = File('$path/Output.pdf');
//Write PDF data
await file.writeAsBytes(bytes, flush: true);
//Open the PDF document in mobile
OpenFile.open('$path/Output.pdf');
}
//Draws the invoice header
PdfLayoutResult drawHeader(PdfPage page, Size pageSize, PdfGrid grid) {
//Draw rectangle
page.graphics.drawRectangle(
brush: PdfSolidBrush(PdfColor(91, 126, 215, 255)),
bounds: Rect.fromLTWH(0, 0, pageSize.width - 115, 90));
//Draw string
page.graphics.drawString(
'INVOICE', PdfStandardFont(PdfFontFamily.helvetica, 30),
brush: PdfBrushes.white,
bounds: Rect.fromLTWH(25, 0, pageSize.width - 115, 90),
format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle));
page.graphics.drawRectangle(
bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 90),
brush: PdfSolidBrush(PdfColor(65, 104, 205)));
page.graphics.drawString('',
PdfStandardFont(PdfFontFamily.helvetica, 18),
bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 100),
brush: PdfBrushes.white,
format: PdfStringFormat(
alignment: PdfTextAlignment.center,
lineAlignment: PdfVerticalAlignment.middle));
final PdfFont contentFont = PdfStandardFont(PdfFontFamily.helvetica, 9);
//Draw string
page.graphics.drawString('', contentFont,
brush: PdfBrushes.white,
bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 33),
format: PdfStringFormat(
alignment: PdfTextAlignment.center,
lineAlignment: PdfVerticalAlignment.bottom));
//Create data foramt and convert it to text.
final DateFormat format = DateFormat.yMMMMd('en_US');
final String invoiceNumber = '';// + format.format(DateTime.now());
final Size contentSize = contentFont.measureString(invoiceNumber);
// ignore: leading_newlines_in_multiline_strings
const String address = '''''';
// final DateFormat format = DateFormat.yMMMMd('en_US');
// final String invoiceNumber = 'Invoice Number: 2058557939\r\n\r\nDate: ' +
// format.format(DateTime.now());
// final Size contentSize = contentFont.measureString(invoiceNumber);
// // ignore: leading_newlines_in_multiline_strings
// const String address = '''Bill To: \r\n\r\nAbraham Swearegin,
// \r\n\r\nUnited States, California, San Mateo,
// \r\n\r\n9920 BridgePointe Parkway, \r\n\r\n9365550136''';
PdfTextElement(text: invoiceNumber, font: contentFont).draw(
page: page,
bounds: Rect.fromLTWH(pageSize.width - (contentSize.width + 30), 120,
contentSize.width + 30, pageSize.height - 120));
return PdfTextElement(text: address, font: contentFont).draw(
page: page,
bounds: Rect.fromLTWH(30, 120,
pageSize.width - (contentSize.width + 30), pageSize.height - 120));
}
//Draws the grid
void drawGrid(PdfPage page, PdfGrid grid, PdfLayoutResult result) {
Rect totalPriceCellBounds;
Rect quantityCellBounds;
//Invoke the beginCellLayout event.
grid.beginCellLayout = (Object sender, PdfGridBeginCellLayoutArgs args) {
final PdfGrid grid = sender as PdfGrid;
if (args.cellIndex == grid.columns.count - 1) {
totalPriceCellBounds = args.bounds;
} else if (args.cellIndex == grid.columns.count - 2) {
quantityCellBounds = args.bounds;
}
};
//Draw the PDF grid and get the result.
result = grid.draw(
page: page, bounds: Rect.fromLTWH(0, result.bounds.bottom + 40, 0, 0));
//Draw grand total.
page.graphics.drawString('',
PdfStandardFont(PdfFontFamily.helvetica, 9, style: PdfFontStyle.bold),
bounds: Rect.fromLTWH(
quantityCellBounds.left,
result.bounds.bottom + 10,
quantityCellBounds.width,
quantityCellBounds.height));
page.graphics.drawString('',
PdfStandardFont(PdfFontFamily.helvetica, 9, style: PdfFontStyle.bold),
bounds: Rect.fromLTWH(
totalPriceCellBounds.left,
result.bounds.bottom + 10,
totalPriceCellBounds.width,
totalPriceCellBounds.height));
}
//Draw the invoice footer data.
void drawFooter(PdfPage page, Size pageSize) {
final PdfPen linePen =
PdfPen(PdfColor(142, 170, 219, 255), dashStyle: PdfDashStyle.custom);
linePen.dashPattern = <double>[3, 3];
//Draw line
page.graphics.drawLine(linePen, Offset(0, pageSize.height - 100),
Offset(pageSize.width, pageSize.height - 100));
const String footerContent =
// ignore: leading_newlines_in_multiline_strings
'''\r\n\r\nAny Questions? shreennansharda#gmail.com''';
//Added 30 as a margin for the layout
page.graphics.drawString(
footerContent, PdfStandardFont(PdfFontFamily.helvetica, 9),
format: PdfStringFormat(alignment: PdfTextAlignment.right),
bounds: Rect.fromLTWH(pageSize.width - 30, pageSize.height - 70, 0, 0));
}
//Create PDF grid and return
PdfGrid getGrid() {
//Create a PDF grid
final PdfGrid grid = PdfGrid();
//Secify the columns count to the grid.
grid.columns.add(count: 5);
//Create the header row of the grid.
final PdfGridRow headerRow = grid.headers.add(1)[0];
//Set style
headerRow.style.backgroundBrush = PdfSolidBrush(PdfColor(68, 114, 196));
headerRow.style.textBrush = PdfBrushes.white;
headerRow.cells[0].value = 'Product Image';
headerRow.cells[1].value = 'Product Id';
headerRow.cells[1].stringFormat.alignment = PdfTextAlignment.center;
headerRow.cells[2].value = 'Product Name';
headerRow.cells[3].value = 'Metal';
headerRow.cells[4].value = 'Stone';
headerRow.cells[5].value = 'Quantity';
//Add rows
for(int i = 0; i < _totalItems; i++){
addProducts(array[i], nameArray[i], metalArray[i], _mulitpleFiles[i], stoneArray[i], 1, grid);
}
//Apply the table built-in style
grid.applyBuiltInStyle(PdfGridBuiltInStyle.listTable4Accent5);
//Set gird columns width
grid.columns[1].width = 200;
for (int i = 0; i < headerRow.cells.count; i++) {
headerRow.cells[i].style.cellPadding =
PdfPaddings(bottom: 5, left: 5, right: 5, top: 5);
}
for (int i = 0; i < grid.rows.count; i++) {
final PdfGridRow row = grid.rows[i];
for (int j = 0; j < row.cells.count; j++) {
final PdfGridCell cell = row.cells[j];
if (j == 0) {
cell.stringFormat.alignment = PdfTextAlignment.center;
}
cell.style.cellPadding =
PdfPaddings(bottom: 5, left: 5, right: 5, top: 5);
}
}
return grid;
}
//Create and row for the grid.
void addProducts(String productId, String productName, String metal,File productImage,
String stone, int quantity, PdfGrid grid) {
final PdfGridRow row = grid.rows.add();
row.cells[0].value = productImage;
row.cells[1].value = productId;
row.cells[2].value = productName;
row.cells[3].value = metal;
row.cells[4].value = stone;
row.cells[5].value = quantity.toString();
}
//Get the total amount.
double getTotalAmount(PdfGrid grid) {
double total = 0;
for (int i = 0; i < grid.rows.count; i++) {
final String value =
grid.rows[i].cells[grid.columns.count - 1].value as String;
total += double.parse(value);
}
return total;
}
below is the on tap button function when a user click on the download button
onTap: () async {
// var list = photoArray;
var list = [
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/bigsize.jpg",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.jpg",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/sample.HEIC",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_transparent.png",
"https://raw.githubusercontent.com/wiki/ko2ic/flutter_google_ad_manager/images/sample.gif",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_no.png",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.png",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_real_png.jpg",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/bigsize.jpg",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.jpg",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_transparent.png",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_no.png",
"https://raw.githubusercontent.com/wiki/ko2ic/flutter_google_ad_manager/images/sample.gif",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.png",
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_real_png.jpg",
];
List<File> files = [];
for (var url in list) {
try {
final imageId =
await ImageDownloader.downloadImage(url);
final path = await ImageDownloader.findPath(imageId);
print(path);
files.add(File(path));
} catch (error) {
print(error);
}
}
setState(() {
_mulitpleFiles.addAll(files);
});
print('invoice');
//Navigator.push(context, MaterialPageRoute(builder: (context) => FullScreen(total: _totalItems,nameArray: nameArray,skuArray: skuArray,stoneArray: stoneArray,metalArray: metalArray,array: array,)));
generateInvoice();
},
Add this package https://pub.dev/packages/printing
printing: ^5.7.2
Example:
final netImage = await networkImage('https://www.nfet.net/nfet.jpg');
pdf.addPage(pw.Page(build: (pw.Context context) {
return pw.Center(
child: pw.Image(netImage),
);
}));
We have checked the code example provided and identified that “await ImageDownloader.downloadImage(url)” returns null. Due to this, there is no image preserved in PDF grid cell. We have created a sample to read the image data from webspace/website and drawn the image using the retrieved image data. Kindly try the following code example and sample in your side and let us know whether the issue is resolved at your end.
Add http package in dependencies section of pubspec.yaml file
dependencies:
http: ^0.13.3
Import the following package in your dart file.
//Read an image data from website/webspace
import 'package:http/http.dart' show get;
Get image data
//Read an image data from website/webspace
var url = "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg";
var response = await get(Uri.parse(url));
var data = response.bodyBytes;
Draw image into PDF document
//Load image data into PDF bitmap object
PdfBitmap image = PdfBitmap(data);
//Draw image in page graphics
document.pages
.add()
.graphics
.drawImage(image, const Rect.fromLTWH(0, 0, 500, 200));
Draw image into PDF document
//Create a new page to draw PDF grid
final PdfPage girdPage = document.pages.add();
//Draw image in PDF grid cell
//Create a PDF grid
final PdfGrid grid = PdfGrid();
//Specify the columns count to the grid.
grid.columns.add(count: 2);
//Create the header row of the grid.
final PdfGridRow headerRow = grid.headers.add(1)[0];
headerRow.cells[0].value = 'Image 1';
headerRow.cells[1].value = 'Image 2';
//Add a new row
final PdfGridRow row = grid.rows.add();
//Get image bytes and set into PDF grid cell as PDF bitmap object
var imageResponse1 = await get(Uri.parse(
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter.jpg"));
row.cells[0].value = PdfBitmap(imageResponse1.bodyBytes.toList());
//Get image bytes and set into PDF grid cell as PDF bitmap object
var imageResponse2 = await get(Uri.parse(
"https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/flutter_transparent.png"));
row.cells[1].value = PdfBitmap(imageResponse2.bodyBytes.toList());
//Apply the table built-in style
grid.applyBuiltInStyle(PdfGridBuiltInStyle.listTable4Accent5);
//Draw grid in a new page created
grid.draw(
page: girdPage,
bounds: Rect.fromLTWH(0, 0, girdPage.getClientSize().width,
girdPage.getClientSize().height));
Sample link: https://www.syncfusion.com/downloads/support/directtrac/general/ze/pdf_sample-948491757
And also we have support to draw JPEG and PNG images in PDF document. Please ensure that the image data is the type of JPEG or PNG before loading into PdfBitmap object. Please find more details from https://help.syncfusion.com/flutter/pdf/working-with-images
And also identified index related changes in the sample code provided. Please update the columns count as 6 for adding 6 columns in PDF grid. Please check the below code for more details,
//Secify the columns count to the grid.
grid.columns.add(count: 6);