GDIplus缩放位图

7

你好,我正在尝试改变GDIplus :: Bitmap的比例并将其保存在缩放的BItmap中,但遇到了问题。我尝试了许多不同的示例,但我的结果是NULL。例如,我尝试更改图像的分辨率,使用SetResolution,还尝试从image-> graphic转换位图并使用其中一个构造函数GDIplus :: Bitmap scale,但我没有结果。例如,我尝试下面的代码:

Bitmap *bitmap = new Bitmap((int32)width, (int32)height,PixelFormat32bppARGB);
bitmap=bmp.Clone(0,0,W,H,PixelFormat32bppPARGB);
mBitmap=(void *)bitmap->Clone(0.0f,0.0f,width,height,PixelFormat32bppPARGB);
3个回答

16

计算新的宽度和高度(如果您已经有缩放因子)

float newWidth = horizontalScalingFactor * (float) originalBitmap->GetWidth();
float newHeight = verticalScalingFactor * (float) originalBitmap->GetHeight();

或者如果新的尺寸已知,则为缩放因子

float horizontalScalingFactor = (float) newWidth / (float) originalBitmap->GetWidth();
float verticalScalingFactor = (float) newHeight / (float) originalBitmap->GetHeight();
创建一个足够空间来缩放图像的新空位图。
Image* img = new Bitmap((int) newWidth, (int) newHeight);

创建一个新的Graphics以在已创建的位图上绘制:

Graphics g(img);

对图像应用比例变换并绘制图像

g.ScaleTransform(horizontalScalingFactor, verticalScalingFactor);
g.DrawImage(originalBitmap, 0, 0);

img现在是原始图像缩放版本的另一个位图。


谢谢!经过几个小时的搜索,我找到了这个方法,它完美地解决了问题。 - user814412

1

除非原始图片具有特定的分辨率(例如通过读取图像文件创建的图像),否则mhcuervo提出的解决方案效果很好。

在这种情况下,您必须将原始图像的分辨率应用于缩放因子:

Image* img = new Bitmap((int) newWidth, (int) newHeight);
horizontalScalingFactor *= originalBitmap->GetHorizontalResolution() / img->GetHorizontalResolution();
verticalScalingFactor *= originalBitmap->GetVerticalResolution() / img->GetVerticalResolution();

(注意:在我的计算机上,新的Bitmap默认分辨率似乎为96 ppi)

或者更简单地说,您可以更改新图像的分辨率:

Image* img = new Bitmap((int) newWidth, (int) newHeight);
img->SetResolution(originalBitmap->GetHorizontalResolution(),  originalBitmap->GetVerticalResolution());    

0

http://msdn.microsoft.com/en-us/library/e06tc8a5.aspx

Bitmap myBitmap = new Bitmap("Spiral.png");
Rectangle expansionRectangle = new Rectangle(135, 10,
   myBitmap.Width, myBitmap.Height);

Rectangle compressionRectangle = new Rectangle(300, 10,
   myBitmap.Width / 2, myBitmap.Height / 2);

myGraphics.DrawImage(myBitmap, 10, 10);
myGraphics.DrawImage(myBitmap, expansionRectangle);
myGraphics.DrawImage(myBitmap, compressionRectangle);

1
问题是关于如何从现有的位图中获取一个缩放后的位图,而不是在不同的比例下绘制相同的位图。 - mhcuervo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接