我希望将 SVG 从 asset 转换为 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;
}
Run Code Online (Sandbox Code Playgroud)
我在另一个答案中找到了解决您问题的方法。
您将需要添加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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5482 次 |
最近记录: |