QT--TCP ----传输图片(buf型)

客户端代码:

 void Client::picSend()
{
        QPixmap pic(":/images/1.png");
        QBuffer buffer;
        buffer.open(QIODevice::ReadWrite);
        pic.save(&buffer,"PNG");
          
        QByteArray dataStr;
        QDataStream out(&dataStr,QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_3);
        out << (quint32) buffer.data().size();
        dataStr.append(buffer.data());
        tcpSocket->write(dataStr);
        dataStr.resize(0);
}
服务器端代码:

void Server::socketReadyRead()   
{   
      if(dataSize ==0)   
      {   
	 QDataStream in(tcpSocket);   
	 in.setVersion(QDataStream::Qt_4_3);   
	 if(tcpSocket->bytesAvailable() < sizeof(quint32))   
		return;   
	 in >>dataSize;   
       }   
      if(dataSize > tcpSocket->bytesAvailable())   
            return;   
      QByteArray array = tcpSocket->read(dataSize);   
      QBuffer buffer(&array);   
      buffer.open(QIODevice::ReadOnly);   
      QImageReader reader(&buffer,"PNG");   
      QImage image = reader.read();   
      if(!image.isNull())   
      {   
        ...
      }   
      else  
      {   
       ...
      } 
}



你可能感兴趣的:(编程)