A pratical example of how write and read images into MySQL tables,using Trolltech Qt4/C++


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. First: Create a table, for example:
  2. CREATE TABLE picture (
  3. ID INTEGER AUTO_INCREMENT,
  4. IMAGE BLOB,
  5. PRIMARY KEY (ID)
  6. ) ENGINE=InnoDB;
  7.  
  8.  
  9. 2) To read a image to a QByteArray
  10.  
  11. QString fileName = "IMAGE.JPG";
  12.  
  13. QImage image(filaName);
  14. LBL_IMAGE->setPixmap(QPixmap::fromImage(image)); // Put image into QLabel object (optional)
  15.  
  16. // load image to bytearray
  17. QByteArray ba;
  18. QFile f(fileName);
  19. if(f.open(QIODevice::ReadOnly))
  20. {
  21. ba = f.readAll();
  22. f.close();
  23. }
  24.  
  25. // Writing the image into table
  26. QSqlDatabase::database().transaction();
  27. QSqlQuery query;
  28. query.prepare( "INSERT INTO picture ( IMAGE ) VALUES (:IMAGE)" );
  29. query.bindValue(":IMAGE", ba);
  30. query.exec();
  31. if( query.lastError().isValid()) {
  32. qDebug() << query.lastError().text();
  33. QSqlDatabase::database().rollback();
  34. } else
  35. QSqlDatabase::database().commit();
  36.  
  37. 3) Now, recovery the field with the image
  38.  
  39. int idx = 1; // The records ID to recover
  40.  
  41. QSqlDatabase::database().transaction();
  42. QSqlQuery query;
  43. query.prepare("SELECT ID, IMAGE FROM picture WHERE ID=:ID");
  44. query.bindValue(":ID", idx);
  45. query.exec();
  46. query.next();
  47. if( query.lastError().isValid()) {
  48. qDebug() << query.lastError().text();
  49. QSqlDatabase::database().rollback();
  50. } else {
  51. QByteArray ba1 = query.value(1).toByteArray();
  52. QPixmap pic;
  53. pic.loadFromData( ba1);
  54.  
  55. // Show the image into a QLabel object
  56. LBL_IMAGE->setPixmap(pic);
  57. QSqlDatabase::database().commit();
  58. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.