开发者

html5 apps for tablets: possible to load images from device's filesystem?

I created a simple html file that loads some images from my local hard-drive (ubuntu). It is enough to pu开发者_运维知识库t

 <img src=/home/user/directory/image.jpg></img>

Now I need to know if it is the same when Html5 is displayed on a tablet like Android or iOS, or Html5 is used in offline app. I mean, if html5 can load an image from the device's filesystem just like on my computer, without localStorage or sessionStorage.


If you deploy the application as native application it is possible (wrap it with Phonegap).

For saved HTML files it is not possible.


On Android, it can be done even though it looks a bit tricky at first. Say you have defined a WebView in your layout.xml, which you want to fill with an html file shipped with your application, which in turn should import a png also shipped with your application.

The trick is to put the html file into res/raw and the png into assets.

Example.

Say you have hello.html which should include buongiorno.png.

  1. Within your project, say MyProject, place buongiorno.png into MyProject/assets.

  2. The hello.html goes into MyProject/res/raw (because we want to avoid having it 'optimised' by the android resource compiler), and could look like this:

    <html>
    <head></head>
    <body>
      <img src="file:///android_asset/buongiorno.png"/>
      <p>Hello world.</p>
    </body>
    </html>
    

In your java code, you would put this code:

    WebView w = (WebView) findViewById(R.id.myWebview);
    String html = getResourceAsString(context, R.raw.hello);
    if (html != null) {
        w.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
    }

where getResourceAsString() is defined as follows:

public static String getResourceAsString(Context context, int resid) throws NotFoundException {
    Resources resources = context.getResources();
    InputStream is = resources.openRawResource(resid);
    try {
        if (is != null && is.available() > 0) {
            final byte[] data = new byte[is.available()];
            is.read(data);
            return new String(data);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } finally {
        try {
            is.close();
        } catch (IOException ioe) {
            // ignore
        }
    }
    return null;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜