Site icon ParallelCodes

Android Storing Images in Base64 string in MS SQL server using Web Service

In my previous post on Android Storing Images in MS SQL Server, I explained how to store the Base64 value of a Images directly into MS SQL server using JTDS jar Library. But its less secure supplying all your database username and passwords in the Application itself.

You should always consider using Webservices (ASP.NET OR PHP). 🙂
This post explains using a ASP.NET webservice to store Base64 string of the image from Android into MS SQL DATABASE.

Step 1 :

Create a Webservice in Asp.net as shown below. This will receive the Base64 value of an image and will store it in SQL server

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;

///
<summary>
/// Summary description for ByteArray2
/// </summary>

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class ByteArray2 : System.Web.Services.WebService {

public ByteArray2 () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string Hello(String ImgName, String ImgValue)
{
String message = " ";
try
{

SqlConnection con = new SqlConnection("Data Source=192.168.0.16;Initial Catalog=MyDb;Persist Security Info=True;User ID=hitesh;Password=789");
SqlCommand cmd = new SqlCommand("insert into ImgTbl (ImgName,Images) values (@ImgName,@Images)", con);
cmd.Parameters.AddWithValue("@ImgName", ImgName);
cmd.Parameters.AddWithValue("@Images", ImgValue);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
message = "Added Successfully in Base64 format.";
}
catch (Exception ex)
{
message = ex.Message.ToString();
}
return message;
}

}

Please note that the Namespace and the Method name as they are important.

Namespaces :

[WebService(Namespace = “http://tempuri.org/”)]

Method Name :

Hello(String ImgName, String ImgValue)

Web.config file

Add this lines in the tag in your Web.config file to allow Http connections :

<system.web>
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>

 

Step 2 :

You will have to host this Webservice so that Android can connect with it. To see how you host a ASP.NET website please refer this HOW TO HOST ASP.NET WEBSITE IN ISS.

Step 3 :

Now create an Android Application in Eclipse ADT or Android Studio.

Open the activity_main.xml file from the res > layout > activity_main.xml and Edit it as following :

<LinearLayout 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"
android:background="#e74c3c"
android:orientation="vertical"
android:weightSum="12" >

<TextView
android:id="@+id/lblclick"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_marginTop="7dp"
android:layout_weight="1"
android:padding="2dp"
android:text="ADROID IMAGEVIEW UPLOAD"
android:textColor="#fff"
android:textSize="19dp"
android:typeface="sans" />

<EditText
android:id="@+id/edtname"
android:layout_width="256dp"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="1"
android:background="#fff"
android:gravity="center"
android:hint="ENTER IMAGE NAME"
android:padding="5dp"
android:textColor="#e74c3c"
android:typeface="sans" />

<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:gravity="center" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="2" >

<Button
android:id="@+id/btnchooseimage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="2dp"
android:background="#2c3e50"
android:gravity="center"
android:textStyle="bold"
android:text="CHOOSE IMAGE"
android:textColor="#e74c3c"
android:typeface="sans" />

<Button
android:id="@+id/btnupload"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:layout_margin="2dp"
android:background="#34495e"
android:gravity="center"
android:text="UPLOAD"
android:textColor="#e74c3c"
android:typeface="sans" />
</LinearLayout>

<ImageView
android:id="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="6.5" />

<TextView
android:id="@+id/txtmsg"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_margin="5dp"
android:layout_weight="1.5"
android:padding="10dp"
android:text="v xcvcxvcvcvxcvxcvxcvxcvxcvxc v xcvcxvcvcvxcvxcvxcvxcvxcvxc v xcvcxvcvcvxcvxcvxcvxcvxcvxc"
android:textColor="#fff"
android:textSize="13sp" />

</LinearLayout>

I have make the layout pretty much easy to understand see the Design view after editing it, you will get an Idea about working.

Now download the KSOAP library and add it to the Lib folder of your application.

Step 4 :

Open the AndroidManifest.xml file and add the following permissions so the App can have network and Memory access.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

Step 5 : THE CODE

Open the MainActivity.java class file.

Declare these :

public static final int requestcode = 1;
ImageView img;
Button btnupload, btnchooseimage;
EditText edtname;
byte[] byteArray;

String encodedImage;
TextView txtmsg;

ProgressBar pg;

String serverresponse;
String imgName;

private static String NAMESPACE = "http://tempuri.org/"; // namespace of the
// webservice
private static String URL = "http://192.168.0.100:94/ByteArray2.asmx";
// url of the webservice hosted on localhost

private static String SOAP_ACTION = "http://tempuri.org/";
String serverreponse = " ";
SoapSerializationEnvelope envelope;
SoapPrimitive response;
SoapObject request;
PropertyInfo ImgName, ImgValue;
HttpTransportSE androidHttpTransport;

In the onCreate method :

img = (ImageView) findViewById(R.id.imageview);

btnupload = (Button) findViewById(R.id.btnupload); // this will be used for sending the base64 value to the server.
btnchooseimage = (Button) findViewById(R.id.btnchooseimage); // this will be used for choosing the image from gallery
edtname = (EditText) findViewById(R.id.edtname);
txtmsg = (TextView) findViewById(R.id.txtmsg);

pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.GONE);

Create onClick listener for the btnchooseimage button

btnchooseimage.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
ChooseImage();
}
});

Create a new method outside the onCreate method with name ChooseImage() :

public void ChooseImage() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)
&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_CHECKING)) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);

} else {
Toast.makeText(MainActivity.this,
"No activity found to perform this task",
Toast.LENGTH_SHORT).show();

}
}

And also onActivityResult() method :

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
Bitmap originBitmap = null;
Uri selectedImage = data.getData();
Toast.makeText(MainActivity.this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
txtmsg.setText(selectedImage.toString());
InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
originBitmap = BitmapFactory.decodeStream(imageStream);

} catch (FileNotFoundException e) {
}
if (originBitmap != null) {
this.img.setImageBitmap(originBitmap);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
originBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
} else {
txtmsg.setText("There's an error if this code doesn't work, thats all I know");

}
}

In this method the image you will be picking from gallery will be converted into Bitmap and to Base64 string value :

if (originBitmap != null) {
this.img.setImageBitmap(originBitmap);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
originBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}

Now create onClickListener method for the btnupload button :

btnupload.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
imgName = edtname.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});

Here’s the AsyncTask which will be called :


private class AsyncCallWS extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {

request = new SoapObject(NAMESPACE, "Hello"); // creating the SoapObject and "Hello" is the method name of the webservice which will called.
ImgName = new PropertyInfo();
ImgName.setName("ImgName"); // setting the variable name
ImgName.setValue(imgName);// setting the value
ImgName.setType(String.class); // setting the type
request.addProperty(ImgName);// adding the property

ImgValue = new PropertyInfo();
ImgValue.setName("ImgValue");
ImgValue.setValue(encodedImage);
ImgValue.setType(String.class);
request.addProperty(ImgValue);

envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); //creating a serialized envelope which will be used to carry the parameters for SOAP body and call the method
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

androidHttpTransport = new HttpTransportSE(URL);

try {

androidHttpTransport.call(SOAP_ACTION + "Hello", envelope); // Hello
response = (SoapPrimitive) envelope.getResponse();
serverreponse = response.toString();

} catch (Exception e) {
e.printStackTrace();
serverreponse = "Error Occurred";
}

return serverreponse;
}

@Override
protected void onPostExecute(String result) {
txtmsg.setText(result);
pg.setVisibility(View.INVISIBLE);
}

@Override
protected void onPreExecute() {
pg.setVisibility(View.VISIBLE);
}

@Override
protected void onProgressUpdate(Void... values) {
}

}

Here’s the full code of MainActivity.java file :

MainActivity.java


package com.example.aaa;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

public static final int requestcode = 1;
ImageView img;
Button btnupload, btnchooseimage;
EditText edtname;
byte[] byteArray;

String encodedImage;
TextView txtmsg;

ProgressBar pg;

String serverresponse;
String imgName;

private static String NAMESPACE = "http://tempuri.org/"; // namespace of the
// webservice
private static String URL = "http://192.168.0.100:94/ByteArray2.asmx"; // url

// of
// the
// webservice
private static String SOAP_ACTION = "http://tempuri.org/";
String serverreponse = " ";
SoapSerializationEnvelope envelope;
SoapPrimitive response;
SoapObject request;
PropertyInfo ImgName, ImgValue;
HttpTransportSE androidHttpTransport;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

img = (ImageView) findViewById(R.id.imageview);

btnupload = (Button) findViewById(R.id.btnupload);
// this will be used for sending the base64 value to the server.
btnchooseimage = (Button) findViewById(R.id.btnchooseimage);
// this will be used for choosing the image from gallery
edtname = (EditText) findViewById(R.id.edtname);
txtmsg = (TextView) findViewById(R.id.txtmsg);

pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.GONE);

btnchooseimage.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
ChooseImage();
}
});

btnupload.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
imgName = edtname.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

public void ChooseImage() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)
&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_CHECKING)) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);

} else {
Toast.makeText(MainActivity.this,
"No activity found to perform this task",
Toast.LENGTH_SHORT).show();

}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
Bitmap originBitmap = null;
Uri selectedImage = data.getData();
Toast.makeText(MainActivity.this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
txtmsg.setText(selectedImage.toString());
InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
originBitmap = BitmapFactory.decodeStream(imageStream);

} catch (FileNotFoundException e) {
}
if (originBitmap != null) {
this.img.setImageBitmap(originBitmap);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
originBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
} else {
txtmsg.setText("There's an error if this code doesn't work, thats all I know");

}
}

private class AsyncCallWS extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {

request = new SoapObject(NAMESPACE, "Hello");
// creating the SoapObject and "Hello" is the method name of the webservice which will called.

ImgName = new PropertyInfo();
ImgName.setName("ImgName"); // setting the variable name
ImgName.setValue(imgName);// setting the value
ImgName.setType(String.class); // setting the type
request.addProperty(ImgName);// adding the property

ImgValue = new PropertyInfo();
ImgValue.setName("ImgValue");
ImgValue.setValue(encodedImage);
ImgValue.setType(String.class);
request.addProperty(ImgValue);

envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// creating a serialized envelope which will be used to carry the
// parameters for SOAP body and call the method
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

androidHttpTransport = new HttpTransportSE(URL);

try {

androidHttpTransport.call(SOAP_ACTION + "Hello", envelope); // Hello
response = (SoapPrimitive) envelope.getResponse();
serverreponse = response.toString();

} catch (Exception e) {
e.printStackTrace();
serverreponse = "Error Occurred";
}

return serverreponse;
}

@Override
protected void onPostExecute(String result) {
txtmsg.setText(result);
pg.setVisibility(View.INVISIBLE);
}

@Override
protected void onPreExecute() {
pg.setVisibility(View.VISIBLE);
}

@Override
protected void onProgressUpdate(Void... values) {
}

}
}

<a href="https://parallelcodes.com/wp-content/uploads/2015/08/fetch.png"><img src="https://parallelcodes.com/wp-content/uploads/2015/08/fetch-576x1024.png" alt="fetch" width="576" height="1024" class="aligncenter size-large wp-image-700" /></a>

Step 6 : DATABASE

SQL DATABASE SCRIPT


USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ImgTbl](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ImgName] [nvarchar](50) NULL,
[Images] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

P.S. – This will store the images in Base64 value which is not so good if you are aiming at the Application which will be uploading
many images as compare to ByteArray or the path of the image. For that you will have to change the Webservice methods.

Refer this :

Android storing Images in MS SQL Server using ASP.NET Webservice in Byte[] format.

Android storing Images in MS SQL Server using ASP.NET Webservice by specifying Image Path.


Exit mobile version