gpt4 book ai didi

c# - 如何解决在 C# 中从二进制转换后具有透明度的图像?

转载 作者:太空宇宙 更新时间:2023-11-03 16:08:29 25 4
gpt4 key购买 nike

我有一张 .png 格式的图片。它是一个圆球。我必须通过将图像转换为二进制文件将图像插入到我的数据库中。然而,在我取回它之后,它的透明度变成了黑色。有谁知道我该如何解决?

仅供引用:我知道二进制不识别透明度。

应 Corey 的要求:我正在使用 Windows 窗体应用程序将图像插入数据库。

 private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "image files|*.jpg;*.png;*.gif;*.mp3";
DialogResult dr = ofd.ShowDialog();

if (dr == DialogResult.Cancel)
return;
pbImage.Image = Image.FromFile(ofd.FileName);
txtImage.Text = ofd.FileName;
}

至于查询

        SqlConnection cn = new SqlConnection(@"Data Source=localhost;Initial Catalog=Games;Integrated Security=True");
MemoryStream ms = new MemoryStream();
pbImage.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] image = new byte[ms.Length];
ms.Position = 0;
ms.Read(image, 0, image.Length);
SqlCommand cmd = new SqlCommand("INSERT into CorrespondingBall(blueBallImage) values(@image)", cn);
cmd.Parameters.AddWithValue("@image", image);

最佳答案

您使用的代码的数据库部分没有问题。我会用 using block 来编写它,但这只是示例代码:)

数据库表中的二进制字段将存储任意字节集合,通常与数据格式无关。由于数据库插入代码似乎没问题,所以问题比这更早。

在您的代码中,您将图像 (pbImage.Image) 转换为 PNG 文件。这似乎是问题的最可能来源:您的源图像没有透明度,或者转换为 PNG 没有正确处理透明度。

确保您的源图像具有实际透明度。如果您在代码中绘制它,请确保在开始绘制之前先将背景清除为 Color.Transparent。检查您使用的 PixelFormat 是否支持 alpha channel 。

试试这段代码:

byte[] imgData;
using (Bitmap bmp = new Bitmap(100, 100, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.Transparent);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

g.FillEllipse(Brushes.Red, 10, 10, 90, 90);
g.DrawString("Test", SystemFonts.DefaultFont, Brushes.Green, 30, 45);
}

using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
imgData = ms.ToArray();
}
}

这应该在 imgData 中创建一个透明的 PNG 文件,您可以将其保存到数据库并加载回来。将文件也保存到磁盘,看看它是什么样子。

-- 更新...

由于您保留了文件文件名的副本,因此您应该使用它从磁盘加载文件。这样您就不会丢失透明度信息或浪费 CPU 周期再次压缩 PNG。使用 File 类的 ReadAllBytes 方法从磁盘获取数据:

byte[] imgFile = System.IO.File.ReadAllBytes(txtImage.Text);

然后您可以将其直接写入数据库。这样你根本就没有原始文件的转换,它直接加载到数据库中。然后从数据库中读取数据,您将得到与原始文件的逐字节匹配。

关于c# - 如何解决在 C# 中从二进制转换后具有透明度的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18435657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com