DSS
DSS

Reputation: 7259

Display local android image in a webview using javascript or jquery

Scene: I am trying to display a file image selected from the gallery into a webview using javascricpt and/or jquery but I am not able to do so. The same works while opening the html in a desktop browser.

What I have tried so far is this in the android code is this:

  1. Written the openFileChooser code and getting the image path and also the image bytes.
  2. calling the following in onActivityResult method:

    String js = "javascript:loadImage(file://" + imagePath + ")";
    mWebView.loadUrl(js);
    

The html looks like this:

<div class="file_chooser">
<!-- <input type="submit" value="File chooser" id="btnSubmit" onclick="sayHello();" > -->
<input type="file" name="banner_image" id="banner_image" onChange="loadImage(this);" accept="image/*" />

    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />

<img alt="" id="image" src=""  width="200px" height="200px" onclick="showSrc(this.src);">
</div>

and the javascript looks like this:

<script type="text/javascript">
    function loadImage(input) {
            if (input.files && input.files[0]) {
            Android.alert('input: ' + input.files[0]);
        var reader = new FileReader();


        reader.onload = (function(input) {
    return function(e) {
         $('#image').attr('src', e.target.result);
        console.log('onload stage finished');
    };
})(input);
reader.onloadend = (function() {
    // $('#image').src(file.name);
});

            reader.readAsDataURL(input.files[0]); 

            //data:image/jpg;base64,xxxxxxxxxxxxxxxxxxxxxxxxxxxx -> this did not work
        }

  function showSrc(src) {
        Android.alert('src : ' + src);
    }
</script>

But i seem to be messing with the android code and also javascript, since i do not know jscript that well.

Please assist as to how to display an image after selection from the gallery.

EDIT:

I have gone through lotsa links that show how to call a javscript function from android , and how to display an image by calling loadBaseUrl with the new html code that has an image inside the src tag, like this, but this is not what I really want.

Upvotes: 1

Views: 2261

Answers (1)

DSS
DSS

Reputation: 7259

For those who fall into such a case: I changed how the loadImage method functions to one that converts a file received into bytes

Steps: 1. Read a file from android and send the path over to the js function 2. Pass the path to a reader and when the reader loads the file, the onLoadEnd method gets called 3. Convert the file to bytes using the code

var stringToReplace = reader.result;
stringToReplace = stringToReplace.replace('data:base64,','data:image\/jpeg;base64,');
  1. Set the image source to the string obtained in #3.

Upvotes: 1

Related Questions