man*_*yst 2 c# transparency gdi+ background image-processing
我正在构建一个图像上传工具,该工具会调整图像的大小以适合固定的大小,但是会在图像周围的填充空间中添加黑色背景而不是透明背景。
我已经读过,位图需要设置为具有Alpha图层的PixelFormat,并且我可以将Graphics的透明色设置为透明,但是仍然遇到相同的问题。
我的图片大多是jpeg。这是代码:
private void ResizeImage(Image Original, Int32 newWidth, Int32 newHeight, String pathToSave)
{
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
int originalWidth = Original.Width;
int originalHeight = Original.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)newWidth / (float)originalWidth);
nPercentH = ((float)newHeight / (float)originalHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((newWidth -
(originalWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((newHeight -
(originalHeight * nPercent)) / 2);
}
int destWidth = (int)(originalWidth * nPercent);
int destHeight = (int)(originalHeight * nPercent);
Bitmap bmp = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
bmp.SetResolution(Original.HorizontalResolution, Original.VerticalResolution);
using (Graphics Graphic = Graphics.FromImage(bmp))
{
Graphic.CompositingQuality = CompositingQuality.HighQuality;
Graphic.Clear(Color.Red);
Graphic.CompositingMode = CompositingMode.SourceCopy;
Graphic.SmoothingMode = SmoothingMode.AntiAlias;
Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
Graphic.DrawImage(
Original,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, originalWidth, originalHeight),
GraphicsUnit.Pixel
);
bmp.Save(pathToSave,Original.RawFormat);
}
}
Run Code Online (Sandbox Code Playgroud)
Graphic.Clear(Color.Red);
Run Code Online (Sandbox Code Playgroud)
不,您将背景设为红色,而不是黑色。如果要将背景的Alpha设置为0,请使用Color.Transparent。或者只是忽略Clear(),它是新位图的默认设置。并避免在Save()调用中使用Original.RawFormat,您不想使用不支持透明度的图像格式。Png总是很好。并且请确保您用于显示结果位图的任何方法也都支持透明度。具有明确定义的背景色。如果没有,您将得到黑色,Color.Transparent在0处具有R,G和B。黑色。
归档时间: |
|
查看次数: |
7796 次 |
最近记录: |