You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带Alpha通道的PNG图片元数据修改异常问题排查与解决咨询

带Alpha通道的PNG图片元数据修改异常问题排查与解决咨询

我正在开发一个C#控制台应用,目的是用AI生成的文本修改图片元数据(标题、评论、标签),以此提升图片在文件夹中的可搜索性。不过最近遇到了一个棘手的问题——带Alpha通道的PNG图片,我好像没法正常修改它的元数据。

具体情况是:只要我尝试编辑带透明背景的PNG元数据,要么图片背景会变成白色,要么透明度保留住了但元数据根本没改动。我现在都不确定这事到底能不能实现了。

下面是我保存图片的代码:

var originalBytes = await File.ReadAllBytesAsync(imagePath);
using var originalMs = new MemoryStream(originalBytes);
using var originalImage = new Bitmap(originalMs);

using var resizedImage = ResizeImage(originalImage, 400, 400);
using var msResized = new MemoryStream();
resizedImage.Save(msResized, ImageFormat.Jpeg);
var b64 = Convert.ToBase64String(msResized.ToArray());

在把数据传给AI之前,我会先将图片缩小,这是我的ResizeImage方法:

var destRect = new Rectangle(0, 0, width, height);

var destImage = Image.IsAlphaPixelFormat(image.PixelFormat)
    ? new Bitmap(width, height, PixelFormat.Format32bppArgb)
    : new Bitmap(width, height);

destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

using var graphics = Graphics.FromImage(destImage);
if (Image.IsAlphaPixelFormat(image.PixelFormat))
{
    graphics.Clear(Color.Transparent);
}

graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

using var wrapMode = new ImageAttributes();
wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);

return destImage;

另外,我用System.Drawing.Imaging处理图片,修改元数据的逻辑是这样的:

// Get data from AI response
var categories = responseContent["Category"]?.ToString() ?? "Unknown";
var description = responseContent["Description"]?.ToString() ?? "No description available";

var newTitleProperty = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
newTitleProperty.Id = 0x010E;
newTitleProperty.Type = 2;
newTitleProperty.Value = Encoding.UTF8.GetBytes(categories + "\0");
newTitleProperty.Len = newTitleProperty.Value.Length;
originalImage.SetPropertyItem(newTitleProperty);
// Create and set a new Comment property item.
var newCommentProperty = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
newCommentProperty.Id = 0x9286;
newCommentProperty.Type = 2;
newCommentProperty.Value = Encoding.UTF8.GetBytes(description + "\0");
newCommentProperty.Len = newCommentProperty.Value.Length;
originalImage.SetPropertyItem(newCommentProperty);

我几乎搜遍了全网,都没找到能解决这个问题的办法,希望有人能指点一下。

备注:内容来源于stack exchange,提问作者SebastianK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 12:04:33