Skip to content

Instantly share code, notes, and snippets.

@shikelong
Forked from irbull/Binary Fetch Example.js
Created October 9, 2021 02:59
Show Gist options
  • Save shikelong/4dbfecbc47561f60658eba504f74f608 to your computer and use it in GitHub Desktop.
Save shikelong/4dbfecbc47561f60658eba504f74f608 to your computer and use it in GitHub Desktop.
const {PNG} = require('bundle.js');
const {Button, ImageView, ui} = require('tabris');
const base64 = require('base-64');
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return base64.encode( binary );
}
new Button({
left: 16, right: 16, top: 'prev() 12',
text: 'load'
}).on('select', loadData).appendTo(ui.contentView);
let imageView = new ImageView({
left: 16, right: 16, top: 'prev() 12'
}).appendTo(ui.contentView);
function loadData() {
fetch('https://tabrisjs.com/assets/public-content/img/iphone-cropped-small.png')
.then(response => checkStatus(response) && response.arrayBuffer())
.then(buffer => {
console.log(buffer);
new PNG({ filterType:4 }).parse( buffer, function(error, data) {
var options = { colorType: 0 }
var out = PNG.sync.write(data, options);
let base64Encoded = _arrayBufferToBase64(out);
imageView.image = { src:'data:image/png;base64,' + base64Encoded};
});
})
.catch(err => console.error(err)); // Never forget the final catch!
}
function checkStatus(response) {
if (!response.ok) {
throw new Error(`HTTP ${response.status} - ${response.statusText}`);
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment