You are on page 1of 1

Subject:

How do I insert an image into a database using the Database Toolbox in MATLAB?

Problem Description:
I would like to put a .jpg image into my database from MATLAB using the Database Toolbox.

Solution:
The following example assumes that you have set up a ODBC data source called "myDatabase". The connection "myDatabase" connects to a database which contains a table called "MyImageDataTable" with a column "ImageData". The " ImageData " field must be setup to hold binary data. For information on setting up a database source, refer to the "Setting Up a Data Source" section in the "Getting Started" chapter of the Database Toolbox documentation. If you have an image "myimage.jpg", this must first be read into MATLAB using the command:
I = imread('myimage.jpg');

To view this variable in the MATLAB workspace, please enter:


whos I

Since the database binary objects accepts single dimensional array, you need to reshape your variable I. Save the size of your variable to reshape it back to original size.
s = size(I); bdata = reshape(I,[],1);

You can use one of the two following methods to insert this binary data into database: 1. Using FASTINSERT command, you can insert the data bdata (image data) into MyImageDataTable.
conn = database('myDatabase','','') fastinsert(conn,'MyImageDataTable',{'ImageData'},{bdata}) close(conn)

2. By using Java objects, you can insert bdata into MyImageDataTable


conn = database('myDatabase','','') x = conn.Handle insertcommand = ['INSERT INTO MyImageDataTable (ImageData) values (?)']; %The following commands are Java methods StatementObject = x.prepareStatement(insertcommand); StatementObject.setObject(1,bdata) StatementObject.execute close(StatementObject)

For more information on the Java methods used in this example, consult the Java API documentation available at: http://www.javasoft.com

You might also like