Display Image from Http Response With Image Content Type

Display image from http response with image content type

var rawResponse = "�PNG...."; // truncated for example

// convert to Base64
var b64Response = btoa(rawResponse);

// create an image
var outputImg = document.createElement('img');
outputImg.src = 'data:image/png;base64,'+b64Response;

// append it to your page
document.body.appendChild(outputImg);

display PNG from http get request

You can achieve this using the fetch API.

Let's first return the response as a blob.
And then you can use URL.createObjectURL() to create an file object.

fetch(URL)
.then(res=>{return res.blob()})
.then(blob=>{
var img = URL.createObjectURL(blob);
// Do whatever with the img
document.getElementById('img').setAttribute('src', img);
})

Demo

How to display images, received from an API response in flutter?

As suggested by Günter Zöchbauer I included the Request Url directly in my Image.network() widget and it worked.

Here's the Code:

void getStaticMapCoordinates(String address) async {
if (address.isEmpty) {
return;
}

final http.Response response = await http.get(
'https://www.mapquestapi.com/geocoding/v1/address?key=[APIKEY]&inFormat=kvp&outFormat=json&location=${address}&thumbMaps=false&maxResults=1');

final decodedResponse = json.decode(response.body);
setState(() {
_coords = decodedResponse['results'][0]['locations'][0]['latLng'];
});
}

Widget _buildStaticMapImage() {

if(_coords == null) {
return Image.asset('assets/product.jpg');
}
return FadeInImage(
image: NetworkImage(
'https://www.mapquestapi.com/staticmap/v5/map?key=[APIKEY]¢er=${_coords['lat']},${_coords['lng']}&zoom=13&type=hyb&locations=${_coords['lat']},${_coords['lng']}&size=500,300@2x'),
placeholder: AssetImage('assets/product.jpg'),
);
}

The getStaticMapCoordinates function executes everytime the user changes the address field and as a result of setState, the Image Widget re-renders.



Related Topics



Leave a reply



Submit