Mohammad Shamsi
Mohammad Shamsi

Reputation: 571

Calculate Average Color from a SVG Image (SvgPicture.network(""))

I try to calculate the average color from SVG format Image, but I don't know how can an SVG Image from the network convert to Unit8List, ImageProvider, or BitMap! for any of these types that I say, I can calculate the average color with the below code :

(I use image package)

import 'package:image/image.dart' as imgPack;
//
Unit8List _myHunit8List =  ...
imgPack.Image bitmap = imgPack.decodeImage(_myHunit8List );

  int redBucket = 0;
  int greenBucket = 0;
  int blueBucket = 0;
  int pixelCount = 0;

  for (int y = 0; y < bitmap.height; y++) {
    for (int x = 0; x < bitmap.width; x++) {
      int c = bitmap.getPixel(x, y);

      pixelCount++;
      redBucket += img.getRed(c);
      greenBucket += img.getGreen(c);
      blueBucket += img.getBlue(c);
    }
  }

  Color averageColor = Color.fromRGBO(redBucket ~/ pixelCount,
      greenBucket ~/ pixelCount, blueBucket ~/ pixelCount, 1);

how can I an SVG Image from the network

( I use flutter_svg package like:

SvgPicture.network(url);

) convert to Unit8List ?

Upvotes: 2

Views: 498

Answers (2)

KuKu
KuKu

Reputation: 7502

It transfers from Image url to Uint8List.

Future<Uint8List> getUint8ListFromImage(imgUrl) async {
    Uint8List bytes = (await NetworkAssetBundle(Uri.parse(imgUrl)).load(imgUrl))
        .buffer
        .asUint8List();
    print(bytes);
    return bytes;
  }

Upvotes: 2

Ruchit
Ruchit

Reputation: 2770

you can convert network image to file and then you can easily convert file to uint8List,

convert image url to file

Future<File> urlToFile(String imageUrl) async {
// generate random number.
var rng = new Random();
// get temporary directory of device.
Directory tempDir = await getTemporaryDirectory();
// get temporary path from temporary directory.
String tempPath = tempDir.path;
// create a new file in temporary path with random file name.
File file = new File('$tempPath'+ (rng.nextInt(100)).toString() +'.svg');
// call http.get method and pass imageUrl into it to get response.
http.Response response = await http.get(imageUrl);
// write bodyBytes received in response to file.
await file.writeAsBytes(response.bodyBytes);
// now return the file which is created with random name in 
// temporary directory and image bytes from response is written to // that file.
return file;
}

Upvotes: 0

Related Questions