如何在Dart中下载图片并将其正确转换为base64? [英] How to download picture and convert to base64 correctly in Dart?

查看:333
本文介绍了如何在Dart中下载图片并将其正确转换为base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力下载图片,然后将其显示在页面上。打印的base64编码的字符串看起来有误;它与例如 http://www.freeformatter.com/base64-encoder.html 结果。

I'm in struggle with downloading a picture and then showing it on a page. Printed base64-encoded string looks wrong; it's not identical with e.g. http://www.freeformatter.com/base64-encoder.html result.

这是我的代码:

HttpRequest.request(_url).then((HttpRequest response) {
    String contentType = response.getResponseHeader('Content-Type');

    if (_supportedContentType(contentType)) {
        List bytes = new Utf8Encoder().convert(response.responseText);
        String header = 'data:$contentType;base64,';
        String base64 = CryptoUtils.bytesToBase64(bytes);
        String image = "${header}${base64}";

        me.avatar = image;
        print(image);
    }
}


推荐答案

设置响应类型时,您将获得二进制数据

When you set the responseType you get binary data

import 'dart:html' show HttpRequest;
import 'dart:convert' show base64;
import 'dart:typed_data' show Uint8List, ByteBuffer;

main() {
  HttpRequest
      .request("Zacharie_Noterman_-_Monkey_business.jpg",
          responseType: "arraybuffer")
      .then((HttpRequest response) {
    String contentType = response.getResponseHeader('Content-Type');

    var list = new Uint8List.view((response.response as ByteBuffer));

    String header = 'data:$contentType;base64,';
    String base64 = base64.encode(list);
    String image = "${header}${base64}";

    //  me.avatar = image;
    print(image);
    //}
  });
}

结果:


data:image / png; base64,/ 9j / 4AAQSkZJRgABAQEAYABgAAD ....

data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD....

这篇关于如何在Dart中下载图片并将其正确转换为base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆