简体   繁体   中英

How to display a png image from api response in flutter?

I'm getting a PNG image (NOT URI) as a response to my api request as shown bellow:

Future PostToGetPostImages(String pic_id,String pic_type) async {
    try {
      var parms = {
        'code': pic_type+"_"+pic_id,
      };

      Response response = await _dio.post(_get_post_image,
          data: parms,
          options: Options(contentType: Headers.formUrlEncodedContentType),
          onSendProgress: (int sent, int total) {
            print('sent : $sent // total : $total');
          }, onReceiveProgress: (v, s) {
            print('v : $v // s : $s');
          });

      print('***** Response body Download Profile Images: ${response.data} **********');
      
      return response.data;
    } catch (error, stacktrace) {
      _handleError(error);
      print("Exception occured A: $error stackTrace: $stacktrace");
    }
  }

This is what it print after execution:

I/flutter (12777): ***** Response body Download Profile Images: �PNG

I need to know how to display this response ( the png image ) in flutter, I'm using this code but it's not working:

FutureBuilder(
                    future: aptProvider().PostToGetProfileImages("1", "m"),
                    builder: (context, snapshot) {
                      return CircleAvatar(
                          radius: 65.0,
                          backgroundImage: backgroundImage: NetworkImage(snapshot.data
                            .toString()));
                    }),

也许 png 就像一个像 404 这样的虚拟图像,就像附加图像中的图像一样,所以你必须复制并尝试使用 Image.network 检查它,如果一切正常,你继续使用 image.network

If you are getting the image url from the response, then you can use the Image.network(imageUrl)

OR

If you are getting the imageData in the form of Uint8List, then you can use the Image.memory(imageData)

The problem here that you is not using a URL image, confirm to use a URL end with (.png, jpg, ..etc.) and also confirm it by open it in your browser.

then

to display it in you widget use one of this ways

First

Image.network('URL') 
// ex: Image.network('https://picsum.photos/250?image=9')

Second

Container( height : 100 , width :100 , decoration : Box decoration ( 
  image : Decoration image ( Network image ('URL'), ), 
), ), ),

It seems like you get the image as a byte array, base64 string.

Here is how I solve that.

var base64 = response.split(';base64,')[1];
base64 = base64.replaceFirst('binary data/', '');
Uint8List bytes = base64Decode(base64);

// Image Widget which you can put in anywhere.
Image.memory(bytes, fit: BoxFit.contain)

I'm not sure if you got it to work but I wanted to leave this for future reference:

You are receiving raw bytes as part of the response; from there you will need to use those to create an image. For this you have two options:

  1. Save the bytes to a file.
  2. Show the image bytes straight from memory.

Option 1 is usually what you want, but if you need a quick test you can do option 2 without issues, keep in mind memory is limited. Both have different implementations depending on the packages you are using.

Here's a quick overview of what Option 2 might look like using just plain old http :

// MyRepository.dart
class Repository {
  Future<Uint8List?> getImageBytes(<...some params>) async {
    final streamResponse = await client.send(<...some req>);
    final response = await Response.fromStream(streamResponse);
    if (response.statusCode == 200) {
      parsedResponse = response.bodyBytes;
    }
    return null;
  }
}

// MyWidget.dart
class MyWidget extends StatelessWidget {

  <... some other code>

  final Uint8List imageRawBytes;

  @override
  Widget build(BuildContext context) {
    return Image.memory(
      imageRawBytes,
    );
  }
}

What's important here is that you use the raw response bytes instead of using a response body (which is usually an encoded String). This way you can build either a File or keep them in memory to be used.

Please share a example of your json data after that I can help you more over you used a incorrect format of function. You need to use mvvm technique

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM