本文实现:QImage可以直接对像素进行操作,因此利用QT的QImage将jpg图片转换为unsigned char*,并生成raw文件。同时将生成的raw数据文件利用QImage加载出来,并显示在界面Label中。
1.源码地址
2.代码分析
- 源图片信息
通过deepCopyImageData函数将图片数据转化为unsigned char*的数据data,
利用SaveBytesToFile函数将data数据进行保存。
bool MainWindow::deepCopyImageData(const char* imagePath){
QImage image(imagePath); // test image
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "JPG");
buffer.close();
unsigned char *data = (unsigned char *) malloc(bytes.size());
qDebug()<<"bytes size:"<<bytes.size()<<endl;
memcpy(data, reinterpret_cast<unsigned char *>(bytes.data()), bytes.size());
int byteSize = bytes.size();
bool IsSaveSuccess =SaveBytesToFile(data,byteSize);
if(!IsSaveSuccess){
return false;
}
delete [] data;
data = nullptr;
return true;
}
bool MainWindow::SaveBytesToFile(unsigned char* srcData,int size)
{
std::ofstream out;
out.open(imageRawData,std::ios::out |std::ios::binary);
if(!out.is_open()){
qDebug()<<"file open failed"<<endl;
return false;
}
out.write((char*)srcData,size);
out.close();
return true;
}
- 产生image.raw数据
接下来将image.raw数据利用ReadByteFromFile进行读取,并将图片在窗口的label中显示出来,通过函数ShowImage实现,并将读取出来的数据进行保存为.jpg图片。
unsigned char* MainWindow::ReadByteFromFile(const char* fileName,int& size)
{
std::ifstream in;
in.open(fileName,std::ios::in);
if(!in.is_open()){
qDebug()<<"file open failed"<<endl;
return nullptr;
}
int firstPostion = in.tellg();
in.seekg(0, std::ios::end);
int endPostion = in.tellg();
int len = endPostion - firstPostion;
qDebug()<<"file length:"<<len<<endl;
size = len;
in.seekg(0, std::ios::beg);
unsigned char* buf = new unsigned char[len];
in.read((char*)buf, len);
in.close();
qDebug()<<"end"<<endl;
return buf;
}
void MainWindow::ShowImage()
{
int size;
unsigned char* data = ReadByteFromFile(imageRawData,size);
if(data == nullptr){
qDebug()<<"read file success,data is NULL"<<endl;
return;
}
QImage image;
if(!image.loadFromData(data,size))
{
qWarning("Image loading failed");
}
//清空内存。
delete []data;
data = nullptr;
//保存图片
image.save(generateImagePath);
QPixmap pixMap = QPixmap::fromImage(image);
//pixMap size:358,441(像素大小)
//label size:358,441
ui->label->setGeometry(20,20,pixMap.width(),pixMap.height());
qDebug()<<"PixMap size:"<<pixMap.width()<<","<<pixMap.height()<<endl;
ui->label->setPixmap(pixMap);
ui->label->setScaledContents(true);//自适应图片大小
}
3.显示效果