问题描述
我正在尝试将数据矩阵制定为字符串以发送到服务器。但是在将数据附加到字符串时出现错误。为什么会发生这种情况?
我要发送的数据是位图图像像素。
我的代码:
string getPixelsFromBitmap(Bitmap& bitmap) {
//Pass up the width and height,as these are useful for accessing pixels in the vector o' vectors.
int width = bitmap.GetWidth();
int height = bitmap.GetHeight();
auto* bitmapData = new Gdiplus::BitmapData;
//Lock the whole bitmap so we can read pixel data easily.
Gdiplus::Rect rect(0,width,height);
bitmap.LockBits(&rect,Gdiplus::ImageLockModeRead,PixelFormat32bppARGB,bitmapData);
//Get the individual pixels from the locked area.
auto* pixels = static_cast<unsigned*>(bitmapData->Scan0);
//Vector of vectors; each vector is a column.
//std::vector<std::vector<unsigned>> resultPixels(width,std::vector<unsigned>(height));
//todo fix string
string matrix("");
const int stride = abs(bitmapData->Stride);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
//Get the pixel colour from the pixels array which we got earlier.
const unsigned pxColor = pixels[y * stride / 4 + x];
//Get each individual colour component. Bitmap colours are in reverse order.
const unsigned red = (pxColor & 0xFF0000) >> 16;
const unsigned green = (pxColor & 0xFF00) >> 8;
const unsigned blue = pxColor & 0xFF;
//Combine the values in a more typical RGB format (as opposed to the bitmap way).
const int rgbValue = RGB(red,green,blue);
//Assign this RGB value to the pixel location in the vector o' vectors.
//resultPixels[x][y] = rgbValue;
matrix += string(rgbValue + ",");
}
matrix += string(".");
}
//Unlock the bits that we locked before.
bitmap.UnlockBits(bitmapData);
return matrix;
}
解决方法
在本声明中
matrix += string(rgbValue + ",");
参数表达式表示一个带有指针算术的表达式,在 const char *
(","
) 类型的指针表达式中添加了整数值 rgbValue
,这显然会导致访问内存超出字符串文字 ","
。
你的意思好像是这样的
matrix += string( std::to_string( rgbValue ) + ",");