2014-02-13 15 views
0

所以我有這個簡單的應用程序,我想要做的是,當我點擊按鈕我想打開WebView並顯示自定義HTML網站與我的形象(現在它會在RES /繪製文件夾的圖標)打開Webview與自定義HTML包含圖像

這是我的WebView的樣子:

public class WebViewActivity extends Activity { 

private WebView webView; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.webview); 

    webView = (WebView) findViewById(R.id.webView1); 
    webView.getSettings().setJavaScriptEnabled(true); 
    //webView.loadUrl("http://www.google.com"); 

    //image to byte[] 
    Bitmap bmBef = null; 
    Bitmap bmAft = null; 
     BitmapFactory.Options bmo = new BitmapFactory.Options(); 
     bmo.inPreferredConfig = Config.ARGB_8888; 

     String patth = "android.resource://com.mkyong.android/drawable/ic_launcher.png"; 
     bmBef = BitmapFactory.decodeFile(patth, bmo); 
     //byte[] b = bitmapToByteArray(bmBef); 





    byte[] imageRaw = bitmapToByteArray(bmBef); 
     String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT); 
    String customHtml = "<html><body><h1>Hello, WebView</h1><img src=\"data:image/jpeg;base64," + image64 + "\" /></img></body></html>"; 
    webView.loadData(customHtml, "text/html", "UTF-8"); 

} 

public static byte[] bitmapToByteArray(Bitmap bm) { 
    // Create the buffer with the correct size 
    int iBytes = bm.getWidth() * bm.getHeight() * 4; 
    ByteBuffer buffer = ByteBuffer.allocate(iBytes); 

    // Log.e("DBG", buffer.remaining()+""); -- Returns a correct number based on dimensions 
    // Copy to buffer and then into byte array 
    bm.copyPixelsToBuffer(buffer); 
    // Log.e("DBG", buffer.remaining()+""); -- Returns 0 
    return buffer.array(); 
} 

} 

但它崩潰在該行 int iBytes = bm.getWidth() * bm.getHeight() * 4; 我缺少什麼?是路徑錯誤,沒有圖像,然後在該路徑,所以我得到一個空指針? 如何修復路徑? 將來我會想用相機拍照並使用它,而不是我現在使用的圖標。

回答

0

當你說它崩潰,錯誤是什麼?查看LogCat輸出中的問題來源。在此期間,該代碼加載在WebView中對我的圖像:

File rootDirectory = mContext.getFilesDir(); 
String baseUrl = "file://" + rootDirectory.getAbsolutePath() + File.separator + filePath + File.separator;   

String imageName = <somthing_that_provides_your_fiename>; 
Bitmap image = BitmapFactory.decodeFile(rootDirectory.getAbsolutePath() + File.separator + filePath + imageName); 
WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); 
Display display = windowManager.getDefaultDisplay(); 
int width = display.getWidth(); 

int scale = width * 100/image.getWidth(); 

browser.setInitialScale(scale); 
browser.loadUrl(baseUrl + imageName); 

我縮放基於寬度圖像,但你可能要檢查的寬度和高度。

+0

我剛剛發現我的問題,我不得不在Manifest中設置權限才能看到文件。 – AAlferez