Created
June 27, 2019 21:01
-
-
Save piotr-j/540b98bcc125e4ca010b5026785fd147 to your computer and use it in GitHub Desktop.
GWT GDX file picker with jsni
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
interface Listener { | |
void picked (String b64Image, Pixmap pixmap); | |
void cancelled (); | |
void failed (); | |
} | |
public void pickFile (Listener listener) { | |
_pickFile(listener); | |
} | |
static native void _pickFile (Listener listener) /*-{ | |
// this should be defined somewhere in the index.html probably | |
// <input type='file' id='file-picker' hidden> | |
var fp = $doc.getElementById('file-picker'); | |
if (fp === null) { | |
console.log('File picker input not found!'); | |
[email protected]::failed(); | |
return; | |
} | |
fp.addEventListener('change', function() { | |
// we can pick single file | |
var f = this.files[0]; | |
// undefined if cancelled | |
if (f === undefined) { | |
[email protected]::cancelled(); | |
return | |
} | |
var reader = new FileReader(); | |
reader.onload = function() { | |
var b64Data = this.result; | |
var img = $doc.createElement("img"); | |
// required to load from file | |
img.crossOrigin = "Anonymous"; | |
// need to replace the leading stuff for our use | |
var b64Image = b64Data.replace(/.*base64,/i, ''); | |
// we need to wait for it to load before we access img element | |
img.addEventListener('load', function() { | |
var pixmap = @com.badlogic.gdx.graphics.Pixmap::new(Lcom/google/gwt/dom/client/ImageElement;)(img); | |
[email protected]::picked(Ljava/lang/String;Lcom/badlogic/gdx/graphics/Pixmap;)(b64Image, pixmap); | |
}, false); | |
img.src = b64Data; | |
img.alt = 'selected image'; | |
// easy way to check it if loads | |
//$doc.body.appendChild(img); | |
} | |
reader.onerror = function() { | |
[email protected]::failed(); | |
} | |
reader.readAsDataURL(f); | |
}, false); | |
// show the picker | |
fp.click(); | |
}-*/; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is brilliant.