Flutter - Как преобразовать файл SVG в Bitmap - PullRequest
0 голосов
/ 01 августа 2020

Как преобразовать SVG файл из ресурсов Flutter в растровое изображение?

1 Ответ

0 голосов
/ 02 августа 2020

Вам понадобится flutter_svg библиотека, которую вы, вероятно, уже используете, если играете с SVG.

Вам также понадобится растровое изображение библиотека.


    import 'package:bitmap/bitmap.dart';
    import 'package:flutter_svg/flutter_svg.dart';

    String svgString = await DefaultAssetBundle.of(context).loadString(svg_path);
    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 = int.parse(temp.substring(0, temp.indexOf('p')));
    temp = svgString.substring(svgString.indexOf('width="')+7);
    int originalWidth = 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
    ui.Picture 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
    ui.Image image = await picture.toImage(width.toInt(), height.toInt());
    ByteData bytes = await image.toByteData(format: ui.ImageByteFormat.png);

    // finally to Bitmap
    Bitmap bitmap = await Bitmap.fromHeadless(width.toInt(), height.toInt(),
        bytes.buffer.asUint8List()
    );

    // if you need to save it:
    File file = File('temporary_file_path/unique_name.bmp');
    file.writeAsBytesSync(bitmap.content);

Некоторая благодарность этому ответу StackOverflow

...