Introduction to Java Database Connectivity · Introduction to Java Programming

Storing Images in a Database

Watch lectures

Storing Images in a Database

1. Same as Files, Image Twist! (beginner)

Photos = bytes too (BLOB!). Extra: validate type/size, maybe thumbnail. Never trust extension (check magic bytes!).

2. Code — Save Photo (exam program!)

// table: photos(id INT AUTO_INCREMENT, title VARCHAR(100), img MEDIUMBLOB)
File img = new File("cat.jpg");
if (img.length() > 5 * 1024 * 1024) throw new IllegalArgumentException(">5MB!");
String sql = "INSERT INTO photos(title, img) VALUES(?, ?)";
try (PreparedStatement ps = con.prepareStatement(sql);
     FileInputStream fis = new FileInputStream(img)) {
    ps.setString(1, "cat");
    ps.setBinaryStream(2, fis, (int) img.length());
    ps.executeUpdate();
    System.out.println("photo saved!");
}

BLOB sizes (MySQL!): BLOB 64KB, MEDIUMBLOB 16MB, LONGBLOB 4GB! Photos → MEDIUMBLOB!

3. Checks (production taste!)

Extension .jpg + magic (FF D8 JPEG!) + size cap + resize thumbnail (save both!).

4. Traps

  • VARCHAR for image = corrupt (use BLOB!).
  • setBytes(bytes) loads ALL to RAM (small only!). setBinaryStream streams (big!).
  • Commit per photo (transaction! else half-saved!).

5. Exam Points

  • Photo-save program + BLOB sizes — 5-7 marks, frequent.
  • Validation + stream need — 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