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

6 次查看(过去 30 天)

采纳的回答

MathWorks Support Team
编辑:MathWorks Support Team 2020-5-27
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:
indata = imread('myimage.jpg');
Alternatively, if you have a figure and want to save a snapshot of it, use the command below:
a = getframe(h);
indata = a.cdata;
where "h" is the figure handle. It is also possible to save the whole figure data into a file and get the binary data from it, thus preserving the functionality of the figure such as UI controls (with certain limitations such as loss of persistent variables created in callbacks):
hgsave(h, 'tempfile.fig')
fid = fopen('tempfile.fig', 'r')
indata = fread(fid, inf, '*uint8')
fclose(fid)
where "h" is the figure handle again.
Since the database binary objects accepts single dimensional array, you need to reshape your variable “indata”. Save the size of your variable to reshape it back to original size. The size need not be saved if "indata" is already one dimensional.
s = size(indata);
bdata = reshape(indata,[],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:

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Convert Image Type 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by