Search code examples
androidwebviewinputstreamassets

Best way to load a jpeg from an install-time asset pack and show it on a WebView


What is the best way to load a jpeg from an install-time asset pack and show it on a WebView?

I got it working in case the jpeg is a regular asset, however, I couldn't get it working optimally with install-time assets:

        WebView webView = this.findViewById(R.id.webView);
        String sHtmlTemplate = "<img src='file:///android_asset/files/"+file+".jpg' width='100%'/>";
        webView.loadDataWithBaseURL("file:///android_asset/files/", sHtmlTemplate, "text/html", "utf-8", null);

UPDATE: The solution below works, but it is slow. Is there a way to load images directly from InputStream or install-time assets?

            AssetManager assetManager = getAssets();
            InputStream is = assetManager.open(songNo + ".jpg");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024000];
            int count;
            while(-1 != (count = is.read(buffer, 0, buffer.length))) {
                baos.write(buffer, 0, count);
            }
            baos.flush();
            byte[] imageRaw = baos.toByteArray();
            baos.close();
            is.close();

            String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
            String html = String.format("<img width='100%%25' src='data:image/jpeg;base64,%s' />", image64);
            webView.loadData(html, "text/html; charset=UTF-8", null);

Thanks


Solution

  • Perhaps the WebView is not the most optimal way to show a jpg in this case. I ended up using another control:

            com.ortiz.touchview.TouchImageView touchView = this.findViewById(R.id.touchImageView);
            try {
                AssetManager assetManager = getAssets();
                InputStream is = assetManager.open(songNo + ".jpg");
                Drawable d = Drawable.createFromStream(is,"src");
                touchView.setImageDrawable(d);
    
            }catch(Exception e){
                Log.i("xxx", e.getMessage());
            }