qt传输图片无法显示
使用UDP传输图片,但是接收之后无法正常显示,只显示一块黑色的图片
发送图片的代码:
QByteArray buffer( 6+3*image->width(), 0 );
QDataStream stream( &buffer, QIODevice::WriteOnly );
stream.setVersion( QDataStream::Qt_4_6 );
stream << (quint16)image->width() << (quint16)image->height();
quint16 y = qrand() % image->height();
stream << y;
for( int x=0; x<image->width(); ++x )
{
QRgb rgb = image->pixel( x, y );
stream << (quint8)qRed( rgb ) << (quint8)qGreen( rgb ) << (quint8)qBlue( rgb );
}
socket->writeDatagram( buffer.data(),buffer.size(), QHostAddress::Broadcast, 8888 );
接收图片的代码:
while( socket->hasPendingDatagrams() )
{
QByteArray buffer( socket->pendingDatagramSize(), 0 );
socket->readDatagram( buffer.data(), buffer.size() );
QDataStream stream( buffer );
stream.setVersion( QDataStream::Qt_4_6 );
quint16 width, height, y;
stream >> width >> height >> y;
if( !image )
image = new QImage( width, height, QImage::Format_RGB32 );
else if( image->width() != width || image->height() != height )
{
delete image;
image = new QImage( width, height, QImage::Format_RGB32 );
}
for( int x=0; x<width; ++x )
{
quint8 red, green, blue;
stream >> red >> green >> blue;
ui->textEdit->append("ddd");
image->setPixel( x, y, qRgb( red, green, blue ) );
}
}
接收之后显示
找了好久没找出哪错了,请各位帮个忙呀
[解决办法]
一张图片,数据量也大不到哪去
可以在For循环外层打个断点,检查一下字节数组的值是否有效?
另外,QImage有个函数可以直接提取图像数据为char数组,你看下两个函数:
int QImage::byteCount () //返回图象数据的总字节数
uchar* QImage::bits ()////返回图像数据的首地址
有了这两个参数,可以直接发送:
socket->writeDatagram(image->bits(),image->byteCount(), QHostAddress::Broadcast, 8888 );
接收方可以利用这个字节数组直接构造一个图象:
QImage ( uchar * data, int width, int height, int bytesPerLine, Format format )
图像的长宽及格式信息也可以一起随图像数据一起发到客户端解析