10

I have a code to show a chart o employees.

The data (name, phone, photo etc) are stored in SQLServer and displayed through JSP. Showing the data is ok, except the image .jpg (stored in IMAGE=BLOB column).

By the way, I've already got the image displayed (see code below), but I dont't know how to put it in the area defined in a .css (see code below, too), since the image got through the resultSet is loaded in the whole page in the browser.

Does anyone knows how can I 'frame' the image ?

<%
Connection con = FactoryConnection_SQL_SERVER.getConnection("empCHART");
Statement stSuper = con.createStatement();
Statement stSetor = con.createStatement();

Blob image = null;
byte[] imgData = null;

ResultSet rsSuper = stSuper.executeQuery("SELECT * FROM funChart WHERE dept = 'myDept'");

if (rsSuper.next()) {
image = rsSuper.getBlob(12);
imgData = image.getBytes(1, (int) image.length());
response.setContentType("image/gif");
OutputStream o = response.getOutputStream();
//o.write(imgData); // even here we got the same as below.
//o.flush();
//o.close();

--[...]

<table style="margin: 0px; margin-top: 15px;">
<tr>
<td id="photo">
<img title="<%=rsSuper.getString("empName").trim()%>" src="<%= o.wite(imageData); o.flush(); o.close(); %>" />
</td>
</td>

<td id="empData">
<h3><%=rsSuper.getString("empName")%></h3>
<p><%=rsSuper.getString("Position")%></p>
<p>Id:<br/><%=rsSuper.getString("id")%></p>
<p>Phone:<br/><%=rsSuper.getString("Phone")%></p>
<p>E-Mail:<br/><%=rsSuper.getString("Email")%></p>
</td>
</table>

And here is the fragment supposed to frame the image:

#photo
{
    padding: 0px;
    vertical-align: middle;
    text-align: center;
    width: 170px;
    height: 220px;
}

Thanks in advance !

jMarcel
  • 958
  • 5
  • 24
  • 54
  • The standard solution is to separate the HTML (here) from the image, usually served by another servlet responding to a request of the browser. So the JSP page only contains something like `` and you have a servlet in which you respond the binary of the image. An alternate solution (I don't recommend it) would be to send the image as base64 in the JSP page. – Denys Séguret Jun 25 '12 at 15:19

4 Answers4

18

You're making some fundamental mistakes here. The <img src> must point to an URL, not contain the image's binary content. The content type of the JSP page itself should not be set to image/gif. It should be kept default to text/html. It is not true that the webserver is supposed to include the concrete images in the HTML result as you seemed to expect. It's the webbrowser who downloads the images individually based on the URL found in src attribute and then presents them accordingly.

Easiest is to create a separate servlet which streams the image from the DB to the response body. You can uniquely identify the image by a request parameter or path info. Here's an example which uses a request parameter for that:

<img src="imageServlet?id=<%=rsSuper.getString("id")%>" />

The doGet() method should then basically perform this job:

String id = request.getParameter("id");

// ...

InputStream input = resultSet.getBinaryStream("imageColumnName");
OutputStream output = response.getOutputStream();
response.setContentType("image/gif");
// Now write input to output the usual way.

Unrelated to the concrete problem, using scriptlets this way is officially strongly discouraged since a decade. Perhaps you were reading completely outdated books/tutorials or are maintaining an ancient JSP web application. For some insights, see also the answers of the following questions for some hints:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Alternatively, the OP can override the `service()` method and not worry about the HTTP methods. :p – Buhake Sindi Jun 25 '12 at 15:19
  • 1
    @Elite: It's not the servlet's fault if a client uses semantically the wrong method to retrieve an image idempotently. It's always GET. Anything else is just wrong. – BalusC Jun 25 '12 at 15:21
  • @BalusC, exactly. I have seen tons abuse on using Servlets. – Buhake Sindi Jun 25 '12 at 15:23
  • @thinksteep: In the webbrowser, yes. Not in the webserver. I only don't understand why you asked this. Do you understand how HTML works? – BalusC Jun 25 '12 at 15:39
  • @thinksteep: Yes, how else would it retrieve the image? Press F12 in Chrome/IE9/Firebug and study the HTTP traffic in "Network" tab. – BalusC Jun 25 '12 at 15:46
  • I really appreciate your help. And yes, I´m 'maintaining an ancient JSP web application', unfortunately. Thank you. – jMarcel Jun 25 '12 at 16:36
2

If you want to display the image through a HTML tag, you will have to point the image to a resource in the server that loads the image, so that the client browser can load it. That way, you can style the <img /> tag.

To accomplish this, most people write an ImageServlet that loads the binary data of the image and write a <img src = "/source/to/someImageServlet?id=<%=rsSuper.getString("id")%>" id = "photo"/>.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
2
  Connection con = new DBConnection().getConnection();
        String sql = " SELECT * FROM tea ";
        PreparedStatement ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            byte[] imgData = rs.getBytes("img"); // blob field 
            request.setAttribute("rvi", "Ravinath");
            rs.getString("teatitle");

            String encode = Base64.getEncoder().encodeToString(imgData);
            request.setAttribute("imgBase", encode);
        }

then used jstl for extract attributes on jsp page

 <img src="data:image/jpeg;base64,${imgBase}" />
Ravinath
  • 1,620
  • 1
  • 14
  • 8
  • Noted should be that this approach is extremely inefficient. Use this at most as preview feature of image uploads. In a decently designed web application those temporary images are already not yet stored in DB in first place. In other words, this approach is absolutely not recommended for displaying static images. – BalusC Dec 07 '16 at 10:46
0
//globle variable
List listmap = new ArrayList();//with getter/setter

//method
Connection con = conn.getConnection();
PreparedStatement ps = null;
String query="select img from tablename";
ps = con.prepareStatement(query);
resultSet = ps.executeQuery();
while (resultSet.next()) {
PackagePojo p1=new PackagePojo();
// pojo class with field private String imagePath with getter/setter;
byte[] img = resultSet.getBytes("PTOIMAGE");//PTOIMAGE db column name
String encode=Base64.encodeBase64String(img );
p1.setImagePath(encode);
listmap.add(p1);
}

//in jsp with struts2

<s:iterator value="listmap">
<img src="data:image/jpeg;base64,${imagePath}" alt="bhudutt" title="bhudutt" />
</s:iterator>
  • user3773686, thanks for your time, but your solution is not recommended, as BalusC commented below in a solution (very similar to yours) answered by Ravinath. – jMarcel Mar 26 '18 at 13:49