图像处理:位图旋转(c++ /GDI+)

Image manipulation: bitmap rotation (C++/GDI+)

本文关键字:GDI+ c++ 位图 旋转 图像处理      更新时间:2023-10-16

我花了很多时间试图找到解决方案,但没有找到。我希望你能帮助我。代码有点长,所以我在这里只给出我有问题的部分。我的代码从窗口捕获位图,并保存在HBitmap中。我需要旋转位图。所以我启动GDI+,从HBitmap创建位图pBitmap:

// INIT GDI
ULONG_PTR gdiplusToken;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
if (!gdiplusToken) return 3;
// Gdip_GetRotatedDimensions:
GpBitmap* pBitmap;
int result = Gdiplus::DllExports::GdipCreateBitmapFromHBITMAP(HBitmap, 0, &pBitmap);

然后我计算旋转所需的变量。然后我创建图形对象并尝试旋转图像:

GpGraphics * pG;
result = Gdiplus::DllExports::GdipGetImageGraphicsContext(pBitmap, &pG);
Gdiplus::SmoothingMode smooth = SmoothingModeHighQuality;
result = Gdiplus::DllExports::GdipSetSmoothingMode(pG, smooth);
Gdiplus::InterpolationMode interpolation = InterpolationModeNearestNeighbor;
result = Gdiplus::DllExports::GdipSetInterpolationMode(pG, interpolation);
MatrixOrder MatrixOrder_ = MatrixOrderPrepend;
result = Gdiplus::DllExports::GdipTranslateWorldTransform(pG, xTranslation, yTranslation, MatrixOrder_);
MatrixOrder_ = MatrixOrderPrepend;
result = Gdiplus::DllExports::GdipRotateWorldTransform(pG, ROTATION_ANGLE, MatrixOrder_);
GpImageAttributes * ImgAttributes;
result = Gdiplus::DllExports::GdipCreateImageAttributes(&ImgAttributes); // create an ImageAttribute object
result = Gdiplus::DllExports::GdipDrawImageRectRect(pG,pBitmap,0,0,w,h,0,0,w,h,UnitPixel,ImgAttributes,0,0);  // Draw the original image onto the new bitmap
result = Gdiplus::DllExports::GdipDisposeImageAttributes(ImgAttributes);

最后我想检查图像,所以我添加了:

CLSID pngClsid; 
GetEncoderClsid(L"image/png", &pngClsid);
result = Gdiplus::DllExports::GdipCreateBitmapFromGraphics(w, h, pG, &pBitmap);
result = Gdiplus::DllExports::GdipSaveImageToFile(pBitmap, L"justest.png", &pngClsid, NULL);  // last voluntary? GDIPCONST EncoderParameters* encoderParams

但是我的图像是空白的。我发现GdipCreateBitmapFromGraphics创建空白图像,但我应该如何完成它来检查我所做的图纸?这些步骤是否正确(不仅在这里,但在上面,附近gdipcreatebitmapfrommhbitmap()和GdipGetImageGraphicsContext()或我需要添加一些东西?如何让它工作?

PS:我确定HBitmap包含窗口的图片,我已经检查过了

在我看来,你的做法有些不足。你需要做的是:

  1. 读取你的图像(src)
  2. 找到包含旋转图像的最小边界矩形(即,旋转角,最小和最大之间的距离x和y是尺寸)。
  3. 用这些尺寸和你想要的像素格式(可能与src相同,但也许你想要一个alpha通道)和你想要的背景颜色(dst)创建一个新的图像对象
  4. 创建基于dst (new Graphics(dst))的图形
  5. 在图形
  6. 上设置适当的变换
  7. 绘制src到dst
  8. 出口dst

好消息是,为了确保你做的事情是正确的,你可以把步骤分离出来。例如,您可以制作一个图像和图形,并在其上画一条没有变换的线(或者最好是带有X的框)并保存它。如果你得到了你所期望的,那么你就在正确的道路上。接下来给这个框添加一个变换。在你的例子中,你需要旋转和平移。接下来,获得该旋转的最佳图像的尺寸(提示:不要使用正方形进行测试)。最后,对实际的图像执行此操作。

这将使您一步一步地获得正确的输出,而不是试图在一次拍摄中获得所有内容。