Compress Mat into Jpeg And save the result into memory
Since You did not specify a programming language. I am going to give you the answer in C++.
std::vector<uchar> buff;//buffer for coding
std::vector<int> param(2);
param[0] = cv::IMWRITE_JPEG_QUALITY;
param[1] = 80;//default(95) 0-100
cv::imencode(".jpg", mat, buff, param);