不使用graphics函数库
时间: 2024-03-23 15:40:01 浏览: 18
如果不使用`graphics.h`图形库,可以使用第三方库(如OpenCV)或自己编写代码来处理图像。以下是一个使用标准C语言库函数(`stdio.h`和`stdlib.h`)和Windows API函数(`windows.h`和`gdiplus.h`)来导入和显示图片的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <gdiplus.h>
int main()
{
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
OPENFILENAME ofn;
char file_name[MAX_PATH] = "";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = "Image Files (*.bmp;*.jpg;*.png)\0*.bmp;*.jpg;*.png\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = file_name;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = "";
if (GetOpenFileName(&ofn) != TRUE) {
printf("Error: Failed to open image file.\n");
return 1;
}
Gdiplus::Bitmap* bitmap = Gdiplus::Bitmap::FromFile(file_name);
if (bitmap == NULL) {
printf("Error: Failed to load image.\n");
return 1;
}
UINT width = bitmap->GetWidth();
UINT height = bitmap->GetHeight();
BYTE* data = (BYTE*)malloc(width * height * 3);
Gdiplus::Rect rect(0, 0, width, height);
Gdiplus::BitmapData bitmapData;
bitmap->LockBits(&rect, Gdiplus::ImageLockModeRead, PixelFormat24bppRGB, &bitmapData);
BYTE* src = (BYTE*)bitmapData.Scan0;
for (UINT y = 0; y < height; y++) {
BYTE* dst = data + y * width * 3;
for (UINT x = 0; x < width; x++) {
dst[2] = *src++;
dst[1] = *src++;
dst[0] = *src++;
dst += 3;
}
}
bitmap->UnlockBits(&bitmapData);
HWND hwnd = GetDesktopWindow();
HDC hdc = GetDC(hwnd);
HDC memdc = CreateCompatibleDC(hdc);
BITMAPINFOHEADER bmih = { 0 };
bmih.biSize = sizeof(BITMAPINFOHEADER);
bmih.biWidth = width;
bmih.biHeight = -height;
bmih.biPlanes = 1;
bmih.biBitCount = 24;
bmih.biCompression = BI_RGB;
bmih.biSizeImage = 0;
BITMAPINFO bminfo = { 0 };
bminfo.bmiHeader = bmih;
HBITMAP hbitmap = CreateDIBitmap(hdc, &bmih, CBM_INIT, data, &bminfo, DIB_RGB_COLORS);
SelectObject(memdc, hbitmap);
RECT rect2;
GetClientRect(hwnd, &rect2);
int x = (rect2.right - width) / 2;
int y = (rect2.bottom - height) / 2;
BitBlt(hdc, x, y, width, height, memdc, 0, 0, SRCCOPY);
free(data);
DeleteObject(hbitmap);
DeleteDC(memdc);
ReleaseDC(hwnd, hdc);
delete bitmap;
GdiplusShutdown(gdiplusToken);
return 0;
}
```
这个示例程序使用了Windows API中的`GetOpenFileName`函数来让用户选择图像文件,使用GDI+库函数(`GdiplusStartup`、`Gdiplus::Bitmap::FromFile`等)来读取图像数据和显示图像,使用Windows API中的`CreateDIBitmap`和`BitBlt`函数来将图像绘制到窗口中。注意,这个程序只在Windows操作系统上运行。