2017-02-23 22 views
0

有沒有辦法將圖像保存爲「文本」,然後再讀回來?事實上,我正在使用Qt,我試圖保存/讀取像素映射的base64編碼表示,但沒有按預期工作。這裏是我目前的實施灑了幾個意見:Qt - QPixmap轉換爲XML,相反

/* 
* the culprit pixmap 
*/ 

QPixmap pixmap = QPixmap(a_given_jpg_filepath); 

/* 
* pixmap to array of bytes 
*/ 

QByteArray bytes; 
QBuffer buffer(&bytes); 
buffer.open(QIODevice::WriteOnly); 
pixmap.save(&buffer, "jpg"); // writes pixmap into bytes in jpg format 

/* 
* byte array to text 
* this string is saved to xml (among others) and then read back 
*/ 
const QString &str(bytes.toBase64()); // a base64-encoded version of the pixmap 

/* 
* now trying to construct the pixmap (having it encoded as base64) 
*/ 

const auto wantConversion = true; 
if(wantConversion) { 
    const QByteArray &bytes = QByteArray::fromBase64(str.toLatin1()); 
    QPixmap(bytes); // this pixmap is not the same as the previous one 
} 

我做錯了什麼?我是否在通往解決方案的正確途徑?任何修正/評論是值得歡迎的。

+0

你在正確的軌道上。我沒有使用QBuffer,但是你的代碼與文檔中的示例相匹配。我會嘗試比較字節數組之前和之後的數組,以查看進入的數據是否與數據完全匹配。我懷疑轉換中出現了問題,但我沒有看到任何明顯的錯誤。我已經完成了這項技術,但是使用了我自己的Base64編碼例程,所以我知道這個概念有效。 – goug

+0

我確實需要調用'QPixmap :: loadFromData' - >請參閱下面的@tntxtnt註釋。現在一切正常。 – misterFad

+0

啊,我也在誤讀你正在使用的構造函數的目的。只是沒有仔細閱讀。 – goug

回答

0

你需要調用loadFromData()

const QByteArray &bytes = QByteArray::fromBase64(str.toLatin1()); 
QPixmap fromBase64; 
fromBase64.loadFromData(bytes);