天天看點

QWidget繪制圖檔

在qt代碼中圖像操作及顯示,如果不加入opencv的話,很多情況下都是使用QImage類管理圖像。

QImage圖檔格式

QImage類中圖檔格式類型枚舉:

enum Format {
        Format_Invalid,
        Format_Mono,
        Format_MonoLSB,
        Format_Indexed8,
        Format_RGB32,
        Format_ARGB32,
        Format_ARGB32_Premultiplied,
        Format_RGB16,
        Format_ARGB8565_Premultiplied,
        Format_RGB666,
        Format_ARGB6666_Premultiplied,
        Format_RGB555,
        Format_ARGB8555_Premultiplied,
        Format_RGB888,
        Format_RGB444,
        Format_ARGB4444_Premultiplied,
        Format_RGBX8888,
        Format_RGBA8888,
        Format_RGBA8888_Premultiplied,
        Format_BGR30,
        Format_A2BGR30_Premultiplied,
        Format_RGB30,
        Format_A2RGB30_Premultiplied,
        Format_Alpha8,
        Format_Grayscale8,
#if 0
        // reserved for future use
        Format_Grayscale16,
#endif
#ifndef Q_QDOC
        NImageFormats
#endif
    };
           

Format_RGB32

Format_RGB888

Format_Alpha8

為我們最常用的圖像格式。

  1. Format_RGB32

    : 一個像素占四位元組記憶體(剛好quint32類型,是以為RGB32),前三位元組為RGB值,第四位元組為灰階值。
  2. Format_RGB888

    :一個像素占三位元組,即RGB值,每個占一位元組。
  3. Format_Alpha8

    :此格式為灰階圖像,一個像素占一個位元組。(Alpha8可以為RGB32像素最後一位灰階值)

建立QImage

建立一張大小為40*40,格式為Format_RGB888的圖檔:

QImage *mImage;
    mImage = new QImage(40,40,QImage::Format_RGB888);
           

其他格式圖檔也是此方法,隻是不同格式,QImage中資料大小不一樣,Format_RGB888格式占記憶體大小為 W * H * 3 位元組,其他格式類似計算 。

指派QImage

  1. 直接記憶體拷貝(速度快,效率高)

此方法需要知道圖像的格式,然後确認對應占用的記憶體大小,最後就是依據記憶體大小拷貝資料。Format_RGB888格式為 W * H * 3 位元組,是以拷貝函數第三參數為 width * height * 3 。

  1. 像素級指派操作
for(int w = 0;w < width;w ++)     //像素級指派操作
    {
        for(int h = 0;h < height;h ++)
        {
            int pos = (h*40 + w)*3;
            int r = data.at(pos);
            int g = data.at(pos+1);
            int b = data.at(pos+2);
            mImage->setPixel(w,h,qRgb(r,g,b));
        }
    }
           

此方法可相容

Format_RGB32

Format_RGB888

格式,因為直接指派像素的rgb,是以隻要有rgb記憶體就可以被操作。

繪制QImage

基本操作就是在

QWidget

中繪制使用重寫

paintEvent

函數進行圖檔的繪制,這裡需要注意

QWidget

和圖檔的長寬比例。

void Class_Name::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QRect rect(0,0,this->width(),this->height());
    painter.drawImage(rect,*mImage);
    painter.end();
}
           

QImage顯示的方法有很多,但是為什麼使用重寫

paintEvent

函數的方法,個人認為是效率和占用記憶體此方法都是最小。

繼續閱讀