Saving and retrieving files is a common problem when it comes to writing programs that has a database back end. In this post I will show you how to save and retrieve image files to and from a MySQL database, using Java. This method can be used to store any file in a database.

The Database:

For this example I will create a database called ‘DB’ and a table called ‘images’ where I will store the files. I use wampserver as my database manager.

The format for the ‘images’ table is as follows:

Index    :      INT
Photo    :      MEDIUMBLOB

The data type BLOB can be used to store byte values. There are four such data types available, namely TINYBLOB, MEDIUMBLOB, BLOB, LONGBLOB. Check here to find out the maximum sizes supported by each data type.

Java Program:

The following java program reads an image file (test.jpg) and saves it in the database in a record with index as 5. Then it reads back all the records that are in the table, and stores those images back on the hard disk.

Make sure you have installed MySQL Connector/J. If you are using NetBeans, you can add MySQL JDBC Driver to you libraries folder.

import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.*;
import javax.imageio.ImageIO;

public class Main {

	public static void main(String[] args) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/mysql";
			Connection con = DriverManager.getConnection(url, "root", "");
			System.out.println("Connected to db");

			//saving the image
			PreparedStatement psmnt = (PreparedStatement) con.prepareStatement("INSERT INTO DB.images VALUES(?,?)");
			psmnt.setInt(1, 5);
			File f = new File("test.jpg");
			psmnt.setBlob(2, new FileInputStream(f), f.length());
			psmnt.executeUpdate();
			System.out.println("Image saved in DB");

			//retrieving it

			Statement stmt = (Statement) con.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM DB.images");
			int count = 0;
			while (rs.next()) {
				InputStream is = rs.getBinaryStream("photo");
				BufferedImage image = ImageIO.read(is); //the image is read in
				//store it back again as a file
				ImageIO.write(image, "jpg", new FileOutputStream("recived" + count + ".jpg"));
				count++;
			}

			System.out.println(count+" images saved on disk");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

If you are trying to upload a large file, sometimes you might get a ‘packet size too large’ exception. You can increase the ‘max_allowed_packet’ variable of your server. Check here to find out how to do this.

If you want to know how to save, send and receive Java Image objects over a network have a look at this. It explains how to convert an Image object to a byte array. This byte array can be saved in an SQL database in a BLOB type data field.

Happy Coding! Continue reading

During the previous week I found out some tricks and tips in assembly, and thought of sharing them in this brief post.  I hope you will find these useful. I used NASM compiler to compile these codes.

Clearing a register:

Suppose you want to clear the ax register. XOR’ing it with itself will set all the bits in the register to zero.

xor ax, ax

Printing a single character on screen:

The interrupt 0x10 will print a given character on screen. The following code can be used to print a single character on screen.

mov al, '@'     ; character or the ASCII code of the character to be printed
mov ah, 0x0e    ; video – teletype output
int 0x10

Extracting some bits from a register:
Suppose you want to extract bits 3 and 4 of the AX register, and then print the decimal value on screen. The following code can be used to achieve this.
‘AND’ the register with a binary number which contains 1’s in the bit positions you want to extract. For our example it would be 0b0000000000011000 or 0x0018 (in hexadecimal). Then shift it right until our bits are the right-most bits. Then add 4b to it to get the ASCII number (ASCII value of ‘0’ is 48)

and ax, 0x0018    ; mask out bits 3 – 4
shr ax, 3         ; shift it right 3 times
add ax, 48        ; add 48 to get ASCII character
mov ah, 0x0e      ; print it
int 0x10

Remember the above code will work only if you are going to print values less than 9. If you want to convert a value more than 9 to decimal this will not work (I hope you understand why it doesn’t work 😉 ).

Printing out a register in binary:
For most of our debugging work, we will need to print the contents of a register in binary format. The following code can be used to print the contents of the CX register.

_print_reg:
;print the CX reg
push dx              ; save registers dx,ax,bx
push ax
push bx
mov dx, cx
mov cx, 16           ; loop for 16 times
print_loop:
    mov ax, 32768    ; set  ax = ob1000....
    and ax, dx       ; mask out the MSB of dx and store it in ax
    shr ax, 15       ; shift it to right 15 times
    add al, 48       ; add 48 to get the ASCII (would be either 0 or 1
    mov ah, 0x0e
    int 0x10         ; print it out
    shl dx, 1        ; shift left dx by 1
loop print_loop

pop bx;              ; restore the registers
pop ax
pop dx
ret

Hope these few tips will be helpful. That’s all for now :)


Have you ever wondered how to create those textual user interfaces that appear on console type windows? In this post I will explain how to create some simple user interfaces in C under Windows. With some simple coding, and a little bit of patience you will be able add some GUI elements to your C programs. However the following examples are only for windows operating systems. First let us take a look at some interfaces that I have done.

This shows a Stock Controlling System that I did as a class project. It has text boxes and message boxes and tables.

Inventory Control System user interface with a message box

Inventory Control System user interface

The following is the user interface of our Intelligent Car Park Management System, which we did as a group project in the university.

Car Park Management System User interface

Understanding the Console Window

The console window can be considered as a grid, with top left corner having the coordinates (0, 0).

In order to display our programs correctly, we need to set the size of the console window. Remember to follow this step to change the window size for your programs.

Right click on the title bar of the program and select Properties.

Right click on the title bar of the program and select Properties.

On the Layout tab, change the values as necessary. For this example, I will be using the settings that are shown on the screen shot.

Layout tab

The above procedure can be programmed into the code as well. For this refer the msdn for SetConsoleScreenBufferSize function (http://msdn.microsoft.com/en-us/library/ms686044(v=VS.85).aspx)

Alternative conio.h

We need some functions that are not implemented in the standard conio.h library. These include functions such as gotoxy(), getx(),gety() which basically manipulates the cursor position on the console window. There are a few alternate conio.h libraries available on the internet. I used the one which is available in the following forum by Arthur Christopher Watkins:

http://www.dynamicdrive.com/forums/showthread.php?t=35174

Or you can download a little bit modified version directly from here

It’s all about printf!

Now that you got the console window size adjusted, and alternate conio set up, it’s time to code!

Get an ASCII chart, and note the characters that can be used to draw lines, bends, etc. You can use the following code to print an ascii character.

int n=205;            //ascii code of the character
printf(“%c”,n);

Now you can use your creativity and imagination (and some loops of course :) ) to write functions that will print lines, text boxes, rectangles, etc. Here are some functions that I wrote:

#include <stdio.h>
#include "altconio.h"

void DrawHLine(int x,int y, int length);
void DrawVLine(int x,int y, int height);
void DrawFrame(int beginx,int beginy,int width,int height);

int main()
{
	clrscr();
	DrawFrame(3,3,10,10);
	DrawVLine(15,3,10);
	DrawHLine(3,15,10);
	gotoxy(0,20);
	system("pause");
	return 0;
}

void DrawHLine(int x,int y, int length)
/*
 * this function draws a horizontal line when
 * the x,y values of the starting point and length
 * is given.
 */
{
	int count;
	int currX=getx();	//get the currecnt cursor position
	int currY=gety();
	gotoxy(x,y);
	for(count=0;count<length;count++)
		printf("%c",196);
	gotoxy(currX,currY);	//put the cursor back in place
}

void DrawVLine(int x,int y, int height)
/*
 * this function draws a verticle line when
 * the x,y values of the starting point and height
 * is given.
 */
{
	int count;
	int currX=getx();	//get the currecnt cursor position
	int currY=gety();
	gotoxy(x,y);
	for(count=0;count<height;count++)
	{
		gotoxy(x,y+count);
		printf("%c",179);
	}
	gotoxy(currX,currY);	//put the cursor back in place
}

void DrawFrame(int beginx,int beginy,int width,int height)
/*
 * this function draws a box when the
 * x,y values of the top left corner
 * and hieght and width is given, and
 * clears the inside of it.
 */
{
	int count,i,j;
	int currX=getx();	//get the currecnt cursor position
	int currY=gety();
/*-------Top Horizontal line------*/
	gotoxy(beginx,beginy);
	printf("%c",201);
	for(count=1;count<=width-2;count++)
		printf("%c",205);
	printf("%c",187);

/*-------Left verticle line-------*/
	gotoxy(beginx,beginy+1);
	for(count=1;count<=height-2;count++)
	{   printf("%c",186);
		gotoxy(beginx,beginy+1+count);
	}

/*-------Right verticle line------*/
	gotoxy(beginx+width-1,beginy+1);
	for(count=1;count<=height-2;count++)
	{   printf("%c",186);
		gotoxy(beginx+width-1,beginy+1+count);
	}

/*-------Bottom Horizontal line----*/
	gotoxy(beginx,beginy+height-1);
	printf("%c",200);
	for(count=1;count<=width-2;count++)
		printf("%c",205);
	printf("%c",188);

/*-------Clearing inside the frame---*/
	for(i=1;i<=height-2;i++)
	{
		gotoxy(beginx+1,beginy+i);
		for(j=1;j<=width-2;j++)
			printf(" ");
	}
	gotoxy(currX,currY);	//put the cursor back in place
}

Note that the alternate conio.h library file (which is named as ‘altconio.h’) is in the same directory as my source file, so it is included as:

#include “altconio.h”

I’ll leave you with that for now. Try out the setcolor() function if the altconio.h header file to try out different colors. Experiment with these codes and have fun :)

#include <stdio.h>
#include “altconio.h”void DrawHLine(int x,int y, int length);
void DrawVLine(int x,int y, int height);
void DrawFrame(int beginx,int beginy,int width,int height);int main()
{
clrscr();
DrawFrame(3,3,10,10);
DrawVLine(15,3,10);
DrawHLine(3,15,10);
gotoxy(0,20);
system(“pause”);
return 0;
}void DrawHLine(int x,int y, int length)
/*
* this function draws a horizontal line when
* the x,y values of the starting point and length
* is given.
*/
{
int count;
int currX=getx();    //get the currecnt cursor position
int currY=gety();
gotoxy(x,y);
for(count=0;count<length;count++)
printf(“%c”,196);
gotoxy(currX,currY);    //put the cursor back in place
}void DrawVLine(int x,int y, int height)
/*
* this function draws a verticle line when
* the x,y values of the starting point and height
* is given.
*/
{
int count;
int currX=getx();    //get the currecnt cursor position
int currY=gety();
gotoxy(x,y);
for(count=0;count<height;count++)
{
gotoxy(x,y+count);
printf(“%c”,179);
}
gotoxy(currX,currY);    //put the cursor back in place
}

void DrawFrame(int beginx,int beginy,int width,int height)
/*
* this function draws a box when the
* x,y values of the top left corner
* and hieght and width is given, and
* clears the inside of it.
*/
{
int count,i,j;
int currX=getx();    //get the currecnt cursor position
int currY=gety();
/*——-Top Horizontal line——*/
gotoxy(beginx,beginy);
printf(“%c”,201);
for(count=1;count<=width-2;count++)
printf(“%c”,205);
printf(“%c”,187);

/*——-Left verticle line——-*/
gotoxy(beginx,beginy+1);
for(count=1;count<=height-2;count++)
{   printf(“%c”,186);
gotoxy(beginx,beginy+1+count);
}

/*——-Right verticle line——*/
gotoxy(beginx+width-1,beginy+1);
for(count=1;count<=height-2;count++)
{   printf(“%c”,186);
gotoxy(beginx+width-1,beginy+1+count);
}

/*——-Bottom Horizontal line—-*/
gotoxy(beginx,beginy+height-1);
printf(“%c”,200);
for(count=1;count<=width-2;count++)
printf(“%c”,205);
printf(“%c”,188);

/*——-Clearing inside the frame—*/
for(i=1;i<=height-2;i++)
{
gotoxy(beginx+1,beginy+i);
for(j=1;j<=width-2;j++)
printf(” “);
}
gotoxy(currX,currY);    //put the cursor back in place
}