【问题标题】:how to store and retrieve a jpg image in oracle database using BLOB datatype in java如何在 Java 中使用 BLOB 数据类型在 oracle 数据库中存储和检索 jpg 图像
【发布时间】:2014-08-02 14:14:51
【问题描述】:

我已尝试使用以下代码检索存储在 Oracle 数据库中的具有 BLOB 数据类型的图像。在 apace tomcat7 服务器上运行它后,我只能看到一个图像图标(可能是损坏的图像),但看不到图像。当我试图打开它被下载的图像图标时。我使用 picasa 打开下载的图像,但显示“图像无效”。 请尝试解决我的问题....!

public class RetrieveInkblot extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Blob photo = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String query = "select img from inkblots where  bid = 23";
        ServletOutputStream out = response.getOutputStream();
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "manager");
            out.println("Connection");
            stmt = conn.createStatement();
            rs = stmt.executeQuery(query);


            if (rs == null) {
                out.print("null except");
            } else if (rs.next()) {
                photo = rs.getBlob(1);

            } else {
                response.setContentType("text/html");
                out.println("<html><head><title>Person Photo</title></head>");
                out.println("<body><h1>No photo found for id= 001 </h1></body></html>");
                return;
            }
            byte[] imgData = photo.getBytes(1, (int) photo.length());
            response.setContentType("image/jpg");
            OutputStream o = response.getOutputStream();
            o.write(imgData);
            o.flush();
            o.close();

        } catch (Exception e) {
            response.setContentType("text/html");
            out.println("<html><head><title>Error: Person Photo</title></head>");
            out.println("<body><h1>Error=" + e.getMessage() + "</h1></body></html>");
            return;
        }


    }
}

【问题讨论】:

  • 不要将图像存储在数据库中。只需将图像路径存储在数据库中即可。

标签: java database servlets


【解决方案1】:

你的错误在这一行:

byte[] imgData = photo.getBytes(1,(int)photo.length());

注意java从0开始计数,所以改成这一行:

byte[] imgData = photo.getBytes(0,(int)photo.length());

如果这给你一个IndexOutOfBoundsException,你还需要减少photo.length()

byte[] imgData = photo.getBytes(0,(int)photo.length()-1);

顺便说一句,我不会将图片保存在数据库中,我会将图像写入您的服务器并将 url 写入数据库,或者使用 base64 对图像进行编码,这样更容易读回。

【讨论】:

  • 非常感谢您的回复。但是将图像保存到服务器不是我的要求,我必须将图像保存在数据库中。是的,我已经尝试过 byte[] imgData = photo.getBytes(0,(int)photo.length()-1 );但这并没有什么不同。
  • @user3888255 那么你的图片看起来有缺陷,尝试插入一个你确定是正确的图片(这样你的浏览器等其他程序可以在没有你的服务器的情况下显示),确保你数据库中的图片数据也是可显示,然后重试
猜你喜欢
  • 2020-09-03
  • 2018-10-10
  • 2023-03-03
  • 2022-12-22
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 2011-03-21
相关资源
最近更新 更多