我保存的图像出现黑 - 图像的改变不透明度

问题描述 投票:1回答:1

我试着在这里改变其不透明度后保存的图像是我的代码:

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;

    }
}

有什么问题 ??请帮忙

c# .net gdi+
1个回答
1
投票

你可以这样来做:

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;
    }
}

基于Change Opacity of Image in C#

© www.soinside.com 2019 - 2024. All rights reserved.