Thursday, 21 May 2015

Showing Base 64 image in WebView android

Step1: Create a Project
Copy paste below code into xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <WebView
        android:id="@+id/web_img"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="42dp"
        android:layout_marginTop="64dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/web_img"
        android:layout_toRightOf="@+id/web_img"
        android:text="@string/txt_web" />

</RelativeLayout>

Step2: Copy Paste Below code in java File
package com.example.imagewebview;

import android.content.Context;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.webkit.WebView;

public class MainActivity extends ActionBarActivity {

WebView webview;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.web_img);

String byte_image = "<div style='width='100%' height='100%''><img src='data:image/png;base64,Copy paste any base 64 string here' /></div>";

url_to_show = "<html><body>" + byte_image + "<html><body>";
// webview.setBackgroundColor(0x00000000);
webview.loadData(url_to_show, "text/html", "utf-8");
}
}

Run and Enjoy

No comments:

Post a Comment