CQREncode.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "CQREncode.h"
  2. #include "qrencode.h"
  3. #include <QPainter>
  4. //生成二维码图片
  5. QPixmap CQREncode::GenerateQRcode(QString tempstr, int nWidth)
  6. {
  7. if(tempstr.isEmpty())
  8. {
  9. return QPixmap();
  10. }
  11. QRcode *qrcode; //二维码数据
  12. //QR_ECLEVEL_Q 容错等级
  13. qrcode = QRcode_encodeString(tempstr.toStdString().c_str(), 2, QR_ECLEVEL_Q, QR_MODE_8, 1);
  14. qint32 temp_width = nWidth; //二维码图片的大小
  15. qint32 temp_height = nWidth;
  16. qint32 qrcode_width = qrcode->width > 0 ? qrcode->width : 1;
  17. double scale_x = (double)temp_width / (double)qrcode_width; //二维码图片的缩放比例
  18. double scale_y =(double) temp_height / (double) qrcode_width;
  19. QImage mainimg = QImage(temp_width,temp_height,QImage::Format_ARGB32);
  20. QPainter painter(&mainimg);
  21. QColor background(Qt::white);
  22. painter.setBrush(background);
  23. painter.setPen(Qt::NoPen);
  24. painter.drawRect(0, 0, temp_width, temp_height);
  25. QColor foreground(Qt::black);
  26. painter.setBrush(foreground);
  27. for( qint32 y = 0; y < qrcode_width; y ++)
  28. {
  29. for(qint32 x = 0; x < qrcode_width; x++)
  30. {
  31. unsigned char b = qrcode->data[y * qrcode_width + x];
  32. if(b & 0x01)
  33. {
  34. QRectF r(x * scale_x, y * scale_y, scale_x, scale_y);
  35. painter.drawRects(&r, 1);
  36. }
  37. }
  38. }
  39. QPixmap mainmap = QPixmap::fromImage(mainimg);
  40. return mainmap;
  41. }
  42. CQREncode::CQREncode()
  43. {
  44. }
  45. CQREncode::~CQREncode()
  46. {
  47. }