Category Archives: Image

How to store an Image from Android to a SQlite and retrieve it?

Hello all…

In today’s post I will show you how to store an image in an SQLite database and retrieve it.

Check out the output after running the program.

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

This is the layout for the MainActivity.

<ScrollView 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:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/get_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Get Image" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:src="@drawable/ic_action_search"
            android:visibility="gone" />

        <Button
            android:id="@+id/save_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Save Image in DB" />

        <Button
            android:id="@+id/read_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Read Image from DB" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            tools:context=".MainActivity" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:layout_marginBottom="40dp"
            android:src="@drawable/ic_action_search" />
    </LinearLayout>

</ScrollView>

Now the code for the Activity.

MainActivity.java

package com.coderzheaven.saveimageindb;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	protected static TextView textView;
	protected static ImageView image1, image2;
	protected Button get_image, save_image, read_image;
	private String selectedImagePath;
	private static final int SELECT_PICTURE = 1;
	String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
	String TABLE_NAME = "mytable";

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

		image1 = (ImageView) findViewById(R.id.imageView1);
		image2 = (ImageView) findViewById(R.id.imageView2);
		textView = (TextView) findViewById(R.id.textView1);

		get_image = (Button) findViewById(R.id.get_image);
		get_image.setOnClickListener(this);

		save_image = (Button) findViewById(R.id.save_image);
		save_image.setOnClickListener(this);

		read_image = (Button) findViewById(R.id.read_image);
		read_image.setOnClickListener(this);

	}

	public void onClick(View v) {

		int id = v.getId();
		switch (id) {

		case R.id.get_image:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					SELECT_PICTURE);
			break;

		case R.id.save_image:
			createTable();
			saveInDB();
			break;

		case R.id.read_image:
			readFromDB();
			break;
		default:
			break;

		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				image1.setVisibility(View.VISIBLE);
				image1.setImageURI(selectedImageUri);
			}
		}
	}

	@SuppressWarnings("deprecation")
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	void createTable() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		String MySQL = "create table if not exists "
				+ TABLE_NAME
				+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
		myDb.execSQL(MySQL);
		myDb.close();
	}

	void saveInDB() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		byte[] byteImage1 = null;
		String s = myDb.getPath();

		myDb.execSQL("delete from " + TABLE_NAME); 			// clearing the table
		ContentValues newValues = new ContentValues();
		String name = "CoderzHeaven";
		newValues.put("name", name);
		try {
			FileInputStream instream = new FileInputStream(selectedImagePath);
			BufferedInputStream bif = new BufferedInputStream(instream);
			byteImage1 = new byte[bif.available()];
			bif.read(byteImage1);
			newValues.put("image", byteImage1);
			long ret = myDb.insert(TABLE_NAME, null, newValues);
			if (ret < 0)
				textView.append("Error");
		} catch (IOException e) {
			textView.append("Error Exception : " + e.getMessage());
		}
		myDb.close();
		textView.append("\n Saving Details \n Name : " + name);
		textView.append("\n Image Size : " + byteImage1.length + " KB");
		textView.append("\n Saved in DB : " + s + "\n");
		Toast.makeText(this.getBaseContext(),
				"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
	}

	void readFromDB() {
		byte[] byteImage2 = null;
		SQLiteDatabase myDb;
		myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
		Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			textView.append("\n Reading Details \n Name : " + cur.getString(1));
			cur.moveToNext();
		}

		// /////Read data from blob field////////////////////
		cur.moveToFirst();
		byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
		setImage(byteImage2);
		cur.close();
		myDb.close();
		Toast.makeText(this.getBaseContext(),
				"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
		Toast.makeText(this.getBaseContext(),
				"If your image is big, please scrolldown to see the result.",
				Toast.LENGTH_SHORT).show();
	}

	void setImage(byte[] byteImage2) {
		image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
				byteImage2.length));
		textView.append("\n Image Size : " + byteImage2.length + " KB");
	}

}

Please leave your valuable comments.

How to crop an Image in Android?

This is a sample program that launches the camera and crop the captured image.

Check this link to another crop image example.

http://www.coderzheaven.com/2011/03/15/crop-an-image-in-android/

Crop an Image in Android

Crop an Image in Android

Crop an Image in Android

This is the layout xml.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:text="@string/intro"
        android:textStyle="bold" />

    <Button
        android:id="@+id/capture_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/capture" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:contentDescription="@string/picture" />

</LinearLayout>

Now this is the Main Java File that implements the crop functionality.

Here we are using the “com.android.camera.action.CROP” Intent to crop the Image passing the captured Image URI to it.

package com.coderzheaven.cropimage;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class ShootAndCropActivity extends Activity implements OnClickListener {

	final int CAMERA_CAPTURE = 1;
	final int CROP_PIC = 2;
	private Uri picUri;

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

		Button captureBtn = (Button) findViewById(R.id.capture_btn);
		captureBtn.setOnClickListener(this);
	}

	public void onClick(View v) {
		if (v.getId() == R.id.capture_btn) {
			try {
				// use standard intent to capture an image
				Intent captureIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				// we will handle the returned data in onActivityResult
				startActivityForResult(captureIntent, CAMERA_CAPTURE);
			} catch (ActivityNotFoundException anfe) {
				Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == CAMERA_CAPTURE) {
				// get the Uri for the captured image
				picUri = data.getData();
				performCrop();
			}
			// user is returning from cropping the image
			else if (requestCode == CROP_PIC) {
				// get the returned data
				Bundle extras = data.getExtras();
				// get the cropped bitmap
				Bitmap thePic = extras.getParcelable("data");
				ImageView picView = (ImageView) findViewById(R.id.picture);
				picView.setImageBitmap(thePic);
			}
		}
	}

	/**
	 * this function does the crop operation.
	 */
	private void performCrop() {
		// take care of exceptions
		try {
			// call the standard crop action intent (the user device may not
			// support it)
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			// indicate image type and Uri
			cropIntent.setDataAndType(picUri, "image/*");
			// set crop properties
			cropIntent.putExtra("crop", "true");
			// indicate aspect of desired crop
			cropIntent.putExtra("aspectX", 2);
			cropIntent.putExtra("aspectY", 1);
			// indicate output X and Y
			cropIntent.putExtra("outputX", 256);
			cropIntent.putExtra("outputY", 256);
			// retrieve data on return
			cropIntent.putExtra("return-data", true);
			// start the activity - we handle returning in onActivityResult
			startActivityForResult(cropIntent, CROP_PIC);
		}
		// respond to users whose devices do not support the crop action
		catch (ActivityNotFoundException anfe) {
			Toast toast = Toast
					.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
			toast.show();
		}
	}
}

Download the complete source code for the above example from here.

How to create Image Reflection in Android?

Reflection in Android

This simple Activity creates a reflection of the provided image.

package com.coderzheaven.imagereflection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class ImageReflection extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.activity_image_reflection);

		Bitmap originalImage = BitmapFactory.decodeResource(getResources(),
				R.drawable.coderzheaven_logo);

		// Create an Image view and add our bitmap with reflection to it
		ImageView imageView = new ImageView(this);
		imageView.setImageBitmap(getRefelection(originalImage));

		// Add the image to a linear layout and display it
		LinearLayout linLayout = new LinearLayout(this);
		linLayout.addView(imageView, new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

                linLayout.setBackgroundColor(Color.BLACK);
		// set LinearLayout as ContentView
		setContentView(linLayout);
	}


	public Bitmap getRefelection(Bitmap image) {
		// The gap we want between the reflection and the original image
		final int reflectionGap = 4;

		// Get you bit map from drawable folder
		Bitmap originalImage = image;

		int width = originalImage.getWidth();
		int height = originalImage.getHeight();

		// This will not scale but will flip on the Y axis
		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		// Create a Bitmap with the flip matix applied to it.
		// We only want the bottom half of the image
		Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
				height / 2, width, height / 2, matrix, false);

		// Create a new bitmap with same width but taller to fit reflection
		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);

		// Create a new Canvas with the bitmap that's big enough for
		// the image plus gap plus reflection
		Canvas canvas = new Canvas(bitmapWithReflection);
		// Draw in the original image
		canvas.drawBitmap(originalImage, 0, 0, null);
		//Draw the reflection Image
		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

		// Create a shader that is a linear gradient that covers the reflection
		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0,
				originalImage.getHeight(), 0, bitmapWithReflection.getHeight()
						+ reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
		// Set the paint to use this shader (linear gradient)
		paint.setShader(shader);
		// Set the Transfer mode to be porter duff and destination in
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// Draw a rectangle using the paint with our linear gradient
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);
		return bitmapWithReflection;
	}

}

Download the complete source code for above example from here.