Pick an image from Android gallery and load it on ImageView & Webview together



I’m developing an app that the user should choose an image from Android gallery and then automatically loaded into Android ImageView and WebView together.

For the WebView, it loads an offline html file in assets folder and it has JavaScript function that can set an image source of an image element. After the user pick an image, that JS function will be called and bring the image to html image element.

HTML file in Assets folder:

<!DOCTYPE html>
<html>
	<head>
		
	</head>
	<body>
		<img src="" id="myimage">
		<script>
			function setImage(img){
				document.getElementById("myimage").src = img;
			}
		</script>
	</body>
</html>

MainActivity.java file:

package com.zofiakreasi.loadimagetoimageview;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button loadImage;
    ImageView imgView;
    TextView txtView;
    WebView browser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        browser = findViewById(R.id.webView);
        browser.setWebChromeClient(new WebChromeClient());
        browser.getSettings().setJavaScriptEnabled(true);
        browser.getSettings().setDomStorageEnabled(true);
        browser.getSettings().setAllowFileAccessFromFileURLs(true);
        browser.getSettings().setAllowUniversalAccessFromFileURLs(true);
        browser.loadUrl("file:///android_asset/index.html");

        imgView = findViewById(R.id.imageView);
        txtView = findViewById(R.id.textView);
        loadImage = findViewById(R.id.button);
        loadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent pickerPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(pickerPhotoIntent, 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK) {
            Uri selectedImage = data.getData();
            imgView.setImageURI(selectedImage);
            txtView.setText(selectedImage.toString());
            browser.loadUrl("javascript:setImage('" + selectedImage.toString() + "')");
        }
    }
}
loading...

Leave a Reply

Your email address will not be published.