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
VARCHARfor image = corrupt (use BLOB!).setBytes(bytes)loads ALL to RAM (small only!).setBinaryStreamstreams (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.