How to save, retrieve and draw an image in a web application using Java and PostgreSQL?

For object X; I want this object to have an image. The image must be stored in a database. I cannot save the path, the actual image must be in the database.

My question can be answered by answering the following subqueries:

and). What type of field should I put into the database? (e.g. VARCHAR)

b) What type of object should I use to store and manage the image (at the object level)? (for example java.awt.Image)

c) How to create an object of the selected type (answer to question b) from the data obtained from the database?

d) How to save an object of the selected type (answer to question b) to the database?

e) How do I make an image on a web page?

I am using PostgreSQL, Java and this is a web application.

Thanks!

+2


a source to share


2 answers


a) Which field should be placed in the database? (e.g. VARCHAR)

The image is binary data. Just use a binary field. In PostgreSQL, it is bytea

.

b) What type of object should I use to store and manage the image (at the object level)? (for example java.awt.Image)

Use InputStream

or byte[]

to save it. Java 2D API has classes / methods that can accept / return any of these types.

c) How to create an object of the selected type (answer to question b) from the data obtained from the database?

Use ResultSet#getBinaryStream()

to get InputStream

from him or ResultSet#getBytes()

to get byte[]

from him.



d) How to save an object of the selected type (answer to question b) to the database?

Use PreparedStatement#setBinaryStream()

or PreparedStatement#setBytes()

. Note: if you are new to JDBC / PreparedStatement

then I recommend you go through the Sun basic JDBC tutorial .

e) How do I make an image on a web page?

Use an HTML element <img>

whose src

URL specifies the matching url-pattern

Servlet

. You can pass the image id as a request parameter or pathinfo. Inside, Servlet

you simply write received InputStream

in OutputStream

response a common way Java IO. You can find some sample code in this answer that I posted a while ago.


However, storing only raw images in a database is generally not a good idea. You also have to store some metadata along it, such as the type of content (eg image/jpeg

, image/gif

etc.) that you need after all in the response header to the browser know what to do with it.

+5


a source


You can save the object as a PostGreSQL blob. They can be stored as binary data in a database. http://www.postgresql.org/files/documentation/books/aw_pgsql/node96.html might help. Then you can write the binary input using Servlet OutputStream. This link might help.



0


a source







All Articles