【问题标题】:How to convert SVG to PNG in flutter如何在颤振中将SVG转换为PNG
【发布时间】:2021-11-08 02:04:13
【问题描述】:

我希望将 SVG 从资产转换为 png 并将其写入文件。

我已设法将 SVG 写入文件,但我想将图像以 PNG 格式写入文件

将 SVG 写入文件的代码:

 final bytes = await rootBundle.load('assets/images/example.svg');
  final String tempPath = (await getTemporaryDirectory()).path;
  final File file = File('$tempPath/profile.svg');
  await file.writeAsBytes(
      bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
  return file;
}

【问题讨论】:

  • 有什么更新吗?

标签: flutter dart svg


【解决方案1】:

我在another answer 上找到了您的问题的解决方案。

您需要将flutter_svg 添加为项目的依赖项。

这几乎是参考答案中给出的代码的副本:

Future<Uint8List> svgToPng(BuildContext context, String svgString,
    {int svgWidth, int svgHeight}) async {
  DrawableRoot svgDrawableRoot = await svg.fromSvgString(svgString, null);

  // to have a nice rendering it is important to have the exact original height and width,
  // the easier way to retrieve it is directly from the svg string
  // but be careful, this is an ugly fix for a flutter_svg problem that works
  // with my images
  String temp = svgString.substring(svgString.indexOf('height="') + 8);
  int originalHeight =
      svgHeight ?? int.parse(temp.substring(0, temp.indexOf('p')));
  temp = svgString.substring(svgString.indexOf('width="') + 7);
  int originalWidth =
      svgWidth ?? int.parse(temp.substring(0, temp.indexOf('p')));

  // toPicture() and toImage() don't seem to be pixel ratio aware, so we calculate the actual sizes here
  double devicePixelRatio = MediaQuery.of(context).devicePixelRatio;

  double width = originalHeight *
      devicePixelRatio; // where 32 is your SVG's original width
  double height = originalWidth * devicePixelRatio; // same thing

  // Convert to ui.Picture
  final picture = svgDrawableRoot.toPicture(size: Size(width, height));

  // Convert to ui.Image. toImage() takes width and height as parameters
  // you need to find the best size to suit your needs and take into account the screen DPI
  final image = await picture.toImage(width.toInt(), height.toInt());
  ByteData bytes = await image.toByteData(format: ImageByteFormat.png);

  return bytes.buffer.asUint8List();
}

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2020-04-28
    • 2020-06-22
    • 2015-01-31
    • 2011-08-31
    相关资源
    最近更新 更多