【问题标题】:Save image locally and display in webview将图像保存在本地并在 webview 中显示
【发布时间】:2012-12-29 02:35:51
【问题描述】:

我对这段简单的代码有问题。 我从网上下载了一张图片并将其保存在本地:

               File mFile = new File(context.getFilesDir(), "a.png");
               if(!mFile.exists()) {         mFile.createNewFile();                }
               FileOutputStream fos = new FileOutputStream(mFile);
               fos.write(baf.toByteArray());
               fos.flush();
               fos.close();

我尝试在 ImageView 上显示此图像并且它正在工作。 现在我尝试在 WebView 上显示保存图像。

  String data = "<body>" +"<img src=\"a.png\"/></body>";
  webview.loadDataWithBaseURL(getActivity().getFilesDir().toString(),data , "text/html", "utf-8",null);

它不起作用,webview 什么也没显示。我尝试了一个带有 png 的 webview,我把自己放在 /assets 中,它正在工作。

我认为我在字符串数据中指向文件的语法是错误的,但我不确定。

任何帮助表示赞赏。

谢谢。

亚历克斯。

【问题讨论】:

    标签: android webview save local


    【解决方案1】:

    好的,在测试了很多不同的东西之后,我最终得到了这个工作代码。

        WebView webview = (WebView) view.findViewById(R.id.imageView);      
    
        try {
            FileInputStream in = getActivity().openFileInput("image_behindfragment.png");
            BufferedInputStream buf = new BufferedInputStream(in);
            byte[] bitMapA= new byte[buf.available()];
            buf.read(bitMapA);
            Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
            //imageview.setImageBitmap(bM);
            if (in != null) {
            in.close();
            }
            if (buf != null) {
            buf.close();
    
            String imgToString = Base64.encodeToString(bitMapA,Base64.DEFAULT);
            String imgTag = "<img src='data:image/png;base64," + imgToString               
                    + "' align='left' bgcolor='ff0000'/>"; 
            webview.getSettings().setBuiltInZoomControls(true);
    
            webview.setInitialScale(30);
            WebSettings webSettings = webview.getSettings();
            webSettings.setUseWideViewPort(true);
    
    
            webview.loadData(imgTag, "text/html", "utf-8");
    
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    

    【讨论】:

      【解决方案2】:
      String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
      String imagePath = "file://"+ base + "/a.png";
      String html = "<html><head></head><body><img src=\""+ imagePath + "\"></body></html>";
      WebView.loadDataWithBaseURL("file:///mnt/sdcard/Your Folder/", html, "text/html","utf-8", "");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        • 2017-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-26
        相关资源
        最近更新 更多