C# 为什么即使位图设置为Graphics.Clear(Color.Transparent),在调整大小时图像周围也会出现黑色背景
我正在构建一个图像上传工具,它可以调整图像大小以适应固定的大小,但它在图像周围的填充空间中添加了黑色背景,而不是透明背景 我读到位图需要设置为带有Alpha层的像素格式,我可以将图形的清晰颜色设置为透明,但我仍然遇到同样的问题 我的图像大多是JPEG。代码如下:C# 为什么即使位图设置为Graphics.Clear(Color.Transparent),在调整大小时图像周围也会出现黑色背景,c#,image-processing,background,gdi+,transparency,C#,Image Processing,Background,Gdi+,Transparency,我正在构建一个图像上传工具,它可以调整图像大小以适应固定的大小,但它在图像周围的填充空间中添加了黑色背景,而不是透明背景 我读到位图需要设置为带有Alpha层的像素格式,我可以将图形的清晰颜色设置为透明,但我仍然遇到同样的问题 我的图像大多是JPEG。代码如下: private void ResizeImage(Image Original, Int32 newWidth, Int32 newHeight, String pathToSave) { int sourceX
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);
}
}
private void ResizeImage(图像原始、Int32 newWidth、Int32 newHeight、字符串路径保存)
{
int sourceX=0;
int sourceY=0;
int destX=0;
int destY=0;
int originalWidth=原始宽度;
int原始高度=原始高度;
浮动百分比=0;
浮动nPercentW=0;
浮点数nPercentH=0;
nPercentW=((浮动)新宽度/(浮动)原始宽度);
nPercentH=((浮动)新高度/(浮动)原始高度);
如果(nPercentH
图像的输入格式是什么?如果是jpg,那么可能是因为jpg不支持透明度。您可以尝试使用支持透明度的PNG输出格式:
bmp.Save(pathToSave, ImageFormat.Png);
不,你让背景是红色的,不是黑色的。如果要将背景的alpha设置为0,请使用Color.Transparent。或者省略Clear(),它是新位图的默认值。如果在Save()调用中避免使用Original.RawFormat,则不希望使用不支持透明度的图像格式。Png总是好的。并确保使用任何方法显示生成的位图都支持透明度。具有清晰的背景色。你会得到黑色,当它不,颜色。透明的R,G和B在0。黑色。谢谢你的帮助,汉斯。颜色。红色是一个疏忽。我这样做是为了证明位图的背景色默认为黑色,而不是其他颜色,但问题是保存为jpeg。我以为保存透明png会给IE6带来问题?这绝对是最好的格式吗?这是一种非常好的格式,它是默认格式。支持IE6恐怕是你的十字架。它并不完全不支持它。@mancmanomyst:不过,IE有一些修复程序,允许它支持透明PNG。一个是IEPNGFIX。
Graphic.Clear(Color.Red);