c#如何调整图片透明度

如题,请问达人,如何使用C#代码对图片的透明度进行调整?
就好像ps里面一样,可以对图片的透明度进行调整.
5楼的,我说过了.是用C#代码实现的..不是用css
smoking dog很不错.谢谢了

一楼的写了一大堆无用的代码 却没有说到关键点上
对图片的透明度的调整可以通过重绘并且对颜色进行调整得到实现
C#中对颜色的调整是通过一个ColorMatrix的对象实现的 这个对象表示一个5X5的矩阵 用于对颜色进行线性的变换 作为一般的理解 只需要指定一个如下的矩阵即可实现对颜色的变换:
1,0,0,0,0
0,1,0,0,0
0,0,1,0,0
0,0,0,透明度,0
0,0,0,0,1

简单的代码如下:
//注意using System.Drawing名字空间 opacity是想要设定的透明度

float[][] nArray ={ new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, opacity, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix matrix = new ColorMatrix(nArray);
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap )
Image srcImage = Image.FromFile("aaa.jpg");
Bitmap resultImage = new Bitmap(srcImage.Width, srcImage.Height);
Graphics g = Graphics.FromImage(resultImage);
g.DrawImage( srcImage, new Rectangle( 0, 0, srcImage.Width, srcImage.Height ), 0, 0, srcImage.Width, srcImage.Height, GraphicsUnit.Pixel, attributes);

//resultImage就是楼主想要的结果了
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-05-25
smokingdog的方法经本人测试,本身有透明区域的图片比如一些抠图的png,在处理时,原本透明的地方会变黑。矩阵中设置透明度的从44改成33即可
这里提供两个方法,留给后来人。

方法一:提取点像素法
public static Image ToTransparent(this Image image, float opacity) {
if (opacity >= 1 || opacity <= 0) return image;//透明度应在0 - 1之间
Bitmap bitmap = new Bitmap(image);
for (int i = 0; i < image.Width; i++) {
for (int j = 0; j < image.Height; j++) {
Color color = bitmap.GetPixel(i, j);
int alpha = (int)(color.A * opacity);
Color newColor = Color.FromArgb(alpha, color);
bitmap.SetPixel(i, j, newColor);
}
}
return bitmap;
}

方法二:ColorMatrix法
public static Image ToTransparent(this Image image, float opacity) {
if (opacity >= 1 || opacity <= 0) return image;//透明度应在0 - 1之间
Bitmap bitmap = new Bitmap(image.Width, image.Height);
using (var g = Graphics.FromImage(bitmap)) {
var matrix = new ColorMatrix { Matrix33 = opacity };
var attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
var rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
g.DrawImage(image, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bitmap;
}
第2个回答  2008-10-22
在asp.net下用style的filter
在winform下用System.Drawing下的工具类
在wpf下每个控件有专门处理图像效果的属性,任何效果,只要添加属性就行。
第3个回答  2008-10-22
收藏一下。
第4个回答  2008-10-22
控件属性有吧