Introduction to Java Database Connectivity · Introduction to Java Programming

Retrieving Images from a Database

Watch lectures

Retrieving Images from a Database

1. Same as Files + Show! (beginner)

Images retrieve like files (BLOB → stream → file!) PLUS display option (ImageIO → JLabel!). Beginners: save to file first (simplest!), display next!

// SAVE to file (same as files topic!)
PreparedStatement ps = con.prepareStatement("SELECT img FROM photos WHERE id=?");
ps.setInt(1, 1);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
    try (InputStream in = rs.getBinaryStream("img");
         FileOutputStream out = new FileOutputStream("out.jpg")) {
        byte[] buf = new byte[4096]; int n;
        while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
    }
    // DISPLAY in Swing (bonus!)
    BufferedImage img = ImageIO.read(new File("out.jpg"));
    JFrame f = new JFrame("photo");
    f.add(new JLabel(new ImageIcon(img)));
    f.setSize(400, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
}

4. Traps

  • Corrupt (half-saved BLOB) → ImageIO.read returns null (check!).
  • Big photos → scale (getScaledInstance) before display (else huge window!).
  • getBytes for tiny only (memory!); stream for real!

5. Exam Points

  • Retrieve + display program — 5-7 marks, frequent.
  • Stream vs bytes + null-check — 3 marks, frequent.
Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

← All Introduction to Java Programming modules