我保存的图像显示为黑色-更改图像的不透明度

本文关键字:图像 不透明度 保存 显示 黑色 | 更新日期: 2023-09-27 18:14:02

我想保存一个图像后,改变它的不透明度,这里是我的代码:

protected void bntChangeOpacity_Click(object sender, EventArgs e) {
        String saveDir = mydir;
        Image watermarkImage = Image.FromFile(Server.MapPath(mydir + "imgname.jpg"));

        Graphics gr = Graphics.FromImage(watermarkImage);
        Rectangle r2 = new Rectangle(new Point(0, 0), new Size(watermarkImage.Width, watermarkImage.Height));
        float opacityvalue = 0.5f;
        ImageUtils.ImageTransparency.ChangeOpacity(watermarkImage, opacityvalue);
        Bitmap b1 = new Bitmap(watermarkImage.Width, watermarkImage.Height);
        gr.DrawImage(watermarkImage, r2);
        b1.Save(Server.MapPath(saveDir + "sasf.jpg"));

} 

类代码为:

public class ImageTransparency {
    public static Bitmap ChangeOpacity(Image img, float opacityvalue)
    {
       Bitmap bmp = new Bitmap(img.Width,img.Height);
        Graphics graphics = Graphics.FromImage(bmp);
        ColorMatrix colormatrix = new ColorMatrix();
        colormatrix.Matrix33 = opacityvalue;
        ImageAttributes imgAttribute = new ImageAttributes();
        imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
        graphics.Dispose();
        return bmp;
    }
}

有什么问题吗?请帮助

我保存的图像显示为黑色-更改图像的不透明度

你可以这样做:

private void button1_Click(object sender, EventArgs e)
{
    float opacityvalue = 0.5f;
    var img= ImageTransparency.ChangeOpacity(Image.FromFile(@"PathToYourImage.png"), opacityvalue);
    img.Save(@"PathToYourImage-Opacity.png");
}

class ImageTransparency
{
    public static Bitmap ChangeOpacity(Image img, float opacityvalue)
    {
        Bitmap bmp = new Bitmap(img.Width,img.Height); // Determining Width and Height of Source Image
        Graphics graphics = Graphics.FromImage(bmp);
        ColorMatrix colormatrix = new ColorMatrix();
        colormatrix.Matrix33 = opacityvalue;
        ImageAttributes imgAttribute = new ImageAttributes();
        imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
        graphics.Dispose();   // Releasing all resource used by graphics 
        return bmp;
    }
}
基于c#中图像不透明度变化的