void CMy001Dlg::OnBnClickedOk()
{
cv::Mat image = cv::imread("605x780_P1_GRAY.tif", cv::IMREAD_UNCHANGED);
if (image.empty()) {
AfxMessageBox(_T("无法加载图像!"));
return;
}
int width = image.cols;
int height = image.rows;
int blockSize = 100;
HANDLE hPrinter = NULL;
BYTE* pPrinterInfo = NULL;
PRINTER_INFO_2* pInfo2 = NULL;
DEVMODE* pDevMode = NULL;
CDC printerDC;
int dpi = 1200;
CString strPrintDevice = _T("HP Designjet T730");
cv::Mat result = cv::Mat::zeros(height, width, image.type());//创建拼接大图尺寸
for (int y = 0; y < height; y += blockSize) {//按blackheight指定调试加载图像
for (int x = 0; x < width; x += image.cols) {//按图像宽度分割加载
int currentBlockHeight = std::min(blockSize, image.rows - y);
cv::Rect roi(x, y, std::min(image.cols, width - x), std::min(blockSize, height - y));//定义切割矩形块区域
cv::Mat block = image(roi);//按roi区域分割图像
cv::Mat bgr;
cv::cvtColor(block , bgr, cv::COLOR_BGR2BGRA); // Make sure type is correct
// Step 2: Create bitmap info
BITMAPINFO bitmapInfo = { 0 };
bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfo.bmiHeader.biWidth = bgr.cols;
bitmapInfo.bmiHeader.biHeight = -bgr.rows; // Flip image vertically
bitmapInfo.bmiHeader.biPlanes = 1;
bitmapInfo.bmiHeader.biBitCount = 32;
bitmapInfo.bmiHeader.biCompression = BI_RGB;
// 打开打印机
LPWSTR ptName = strPrintDevice.GetBuffer();
if (!OpenPrinter(ptName, &hPrinter, NULL)) {
AfxMessageBox(_T("打印机端口打开失败!"));
return;
}
// 获取打印机信息
DWORD needed;
GetPrinter(hPrinter, 2, NULL, 0, &needed);
pPrinterInfo = new BYTE[needed];
if (!GetPrinter(hPrinter, 2, pPrinterInfo, needed, &needed)) {
AfxMessageBox(_T("打印机信息获取失败!"));
delete[] pPrinterInfo;
ClosePrinter(hPrinter);
return;
}
pInfo2 = (PRINTER_INFO_2*)pPrinterInfo;
int posX = 30; // 偏移位置
int posY = 30;
// 设置 DEVMODE
pDevMode = (DEVMODE*)GlobalLock(pInfo2->pDevMode);
if (pDevMode) {
// 设置自定义纸张
pDevMode->dmFields |= DM_PAPERWIDTH | DM_PAPERLENGTH | DM_PRINTQUALITY | DM_PAPERSIZE;
pDevMode->dmPaperSize = DMPAPER_USER;
pDevMode->dmPaperWidth = width / dpi * 25.4 * 10; // 1/10 mm
pDevMode->dmPaperLength = height / dpi * 25.4 * 10; // 1/10 mm LcinkRIP不能超过32740
pDevMode->dmPrintQuality = dpi; // DPI
// 释放 DEVMODE
GlobalUnlock(pInfo2->pDevMode);
}
// 创建和启动打印机上下文
if (y == 0) {
// 准备 DOCINFO
DOCINFO docInfo;
memset(&docInfo, 0, sizeof(DOCINFO));
docInfo.cbSize = sizeof(DOCINFO);
docInfo.lpszDocName = _T("test");
docInfo.lpszOutput = NULL;
printerDC.Attach(CreateDC(NULL, pInfo2->pPrinterName, NULL, pDevMode));
printerDC.StartDoc(&docInfo);
printerDC.StartPage();
SetStretchBltMode(printerDC, HALFTONE);
::StretchDIBits(printerDC, x + posX, y + posY, bgr.cols, bgr.rows, 0, 0, bgr.cols, bgr.rows,
bgr.data, &bitmapInfo, DIB_RGB_COLORS, SRCCOPY);
}
else {
SetStretchBltMode(printerDC, HALFTONE);
::StretchDIBits(printerDC, x + posX, y + posY, bgr.cols, bgr.rows, 0, 0, bgr.cols, bgr.rows,
bgr.data, &bitmapInfo, DIB_RGB_COLORS, SRCCOPY);
}
}
}
printerDC.EndPage();
printerDC.EndDoc();
// 释放资源
delete[] pPrinterInfo;
printerDC.DeleteDC();
ClosePrinter(hPrinter);
}