How to solve grayish frame issue when Scaling a bitmap using GDI+

我的未来我决定 提交于 2019-12-24 06:25:09

问题


I'm trying to scale down a Bitmap using GDI+ by doing the following:

Bitmap newImage = new Bitmap(NewWidth, NewHeight, Im.PixelFormat);           
Graphics g = Graphics.FromImage(newImage);

g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

g.ScaleTransform(0.1, 0.1); // 10%
g.DrawImage(Im, 0, 0, Im.Width, Im.Height);

Im is the original image, NewWidth and NewHeight are 10% or the original image. I've tested this on a 1000x1000 image (shrinking it down to 100x100)

The scaling is done correctly with high quality as promised but for some reason there is a gray border on the left, right and top borders (none on the bottom).

I assume this is due to the fact the all the image borders are white and the color "outside" of the bitmap is by default black so some of the default black get mixed into the scaling interpolation.

I looked for a way to set the default background color to white (white will do just fine) but couldn't find it anywhere..

My alternative is to pad the border with a white frame, scale the image down and the crop it but I was wondering if there is a simpler and less CPU consuming way?

Any ideas?


回答1:


Well. After some more digging I found it..

System.Drawing.Imaging.ImageAttributes Att = new System.Drawing.Imaging.ImageAttributes();
Att.SetWrapMode(System.Drawing.Drawing2D.WrapMode.Clamp, System.Drawing.Color.White); 
g.DrawImage(Im, new Rectangle(0,0,Im.Width,Im.Height), 0, 0, Im.Width, Im.Height, GraphicsUnit.Pixel, Att);



回答2:


Try adding an alpha overlay with an extra transparent pixel or two on all sides. This should get a better result than using either an explicit or implied solid color frame. Though converting to RGBA and adding the frame has a higher execution cost, if you are really interested in high quality and don't want to switch graphics libraries it may be the way to go.



来源:https://stackoverflow.com/questions/2024757/how-to-solve-grayish-frame-issue-when-scaling-a-bitmap-using-gdi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!