我对Graphics.DrawImage方法有一个非常奇怪的问题.
我在Panel控件中有PictureBox控件,AllowScroll属性= true.程序根据用户选择的区域在小部件上剪切图像.
我加载图像300x547并选择区域(红色矩形):
alt text http://img341.imageshack.us/img341/8796/63796391.png
程序正确切割图像:
替代文字http://img689.imageshack.us/img689/6459/69242903.png
然后,我加载另一个图像427x640:
alt text http://img34.imageshack.us/img34/7950/56727000.png
然后,结果我看到图像没有正确切割.每个img.jpg文件都有适当的宽度和高度,但绘制的图像太小: alt text http://img641.imageshack.us/img641/1977/25643796.png
这是代码片段 - 它保存用户选择的位图区域:
Image OriginalIMG= (Image)((PictureBox)panel1.Controls["picBox"]).Image.Clone()
Bitmap bmp = new Bitmap(selectedAreaRECT.Width, selectedAreaRECT.Height);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(OriginalIMG, 0,0, selectedAreaRECT, GraphicsUnit.Pixel);
g.Save();
g.Dispose();
bmp.Save(AppDomain.CurrentDomain.BaseDirectory + @"\Temp\" + "img1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Run Code Online (Sandbox Code Playgroud)
如您所见,图像A和图像B的img1.jpg的代码是相同的.我试图解决这个愚蠢的问题太久了,我不知道这个问题的原因是什么.我尝试了DrawImage方法的不同重载,但没有成功
解决!System.Drawing.Bitmap的dafault DPI值是= 96,如果我用DPI!= 96打开图像,则会出现上述问题.要摆脱它,我需要使用SetResolution方法:
Bitmap result = new Bitmap(width, height);
result.SetResolution(OriginalIMG.HorizontalResolution, OriginalIMG.VerticalResolution);
Run Code Online (Sandbox Code Playgroud)
这解决了问题:)感谢大家的帮助!:)
我会尝试:(已编辑)
g.DrawImage(
OriginalIMG,
new Rectangle( Point.Empty, bmp.Size ),
selectedAreaRECT.X, selectedAreaRECT.Y,
selectedAreaRECT.Width, selectedAreaRECT.Height,
GraphicsUnit.Pixel);
Run Code Online (Sandbox Code Playgroud)
看看它是否有所作为。
尽管它与您的问题无关:您忘记了 .Dispose() 一些事情,而且我不确定为什么您必须 .Clone() 图像。