Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

c++ - Transfer images on websocket by using boost library

I want to transfer image data on websocket by using boost library.

How should I resolve below error?

At first, I confirmed to be able to transfer and receive text data by referring following URL. https://www.boost.org/doc/libs/1_68_0/libs/beast/doc/html/beast/quick_start.html

And next, although I tried to transfer image, I got following error message.

 websocket_client.cpp:563:38: error: no matching function for call to 'buffer(cv::Mat&)'

 ws.write(boost::asio::buffer(img));

What I did are below.

  1. read image file as 'img' by using opencv.

  2. Change the code for transfer data

    // Send the message
    
    // ws.write(boost::asio::buffer(std::string(text)));
    
    ws.write(boost::asio::buffer(img));
    
question from:https://stackoverflow.com/questions/65930664/transfer-images-on-websocket-by-using-boost-library

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

cv::Mat is not a buffer type or adaptable as such. If you have POD data, then you can "cast" it like the commenter says:

 // don't do this:
 buffer(&img, sizeof(img));

However, that's not safe:

static_assert(std::is_standard_layout_v<cv::Mat>);
static_assert(std::is_trivial_v<cv::Mat>);

The type is actually not bitwise copyable. But since there's a matrix, there is likely a contiguous region of data that is:

ws.write(net::buffer(img.data, img.total() * img.elemSize()));

This uses total() and elemSize(), links to the documentation.

Now, this will be enough if the receiving end already knows the dimensions. If not, send them first, e.g.:

uint32_t dimensions[] { htonl(image_witdh), htonl(image_height) };

std::vector<net::const_buffer> buffers {
    net::buffer(dimensions),
    net::buffer(img.data, img.total() * img.elemSize())
};
ws.write(buffers);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...