c# - 将 PNG 转换为 GIF 或 JPG
问题描述
我正在尝试将 png 图像转换为 gif 和 jpg 格式。我正在使用在Microsoft 文档中找到的代码。
我通过将此代码修改为以下代码创建了git-hub 示例:
public static void Main(string[] args)
{
// Load the image.
using (Image png = Image.FromFile("test-image.png"))
{
var withBackground = SetWhiteBackground(png);
// Save the image in JPEG format.
withBackground.Save("test-image.jpg");
// Save the image in GIF format.
withBackground.Save("test-image.gif");
withBackground.Dispose();
}
}
private static Image SetWhiteBackground(Image img)
{
Bitmap imgWithBackground = new Bitmap(img.Width, img.Height);
Rectangle rect = new Rectangle(Point.Empty, img.Size);
using (Graphics g = Graphics.FromImage(imgWithBackground))
{
g.Clear(Color.White);
g.DrawImageUnscaledAndClipped(img, rect);
}
return imgWithBackground;
}
所以我的问题是:有没有办法从看起来相同的 png 中获取 gif 格式?
编辑: Hans Passant指出根本问题是透明背景。经过一番挖掘,我在这里找到了答案。我使用链接中提到的代码将背景设置为白色:
private Image SetWhiteBackground(Image img)
{
Bitmap imgWithBackground = new Bitmap(img.Width, img.Height);
Rectangle rect = new Rectangle(Point.Empty, img.Size);
using (Graphics g = Graphics.FromImage(imgWithBackground))
{
g.Clear(Color.White);
g.DrawImageUnscaledAndClipped(img, rect);
}
return imgWithBackground;
}
解决方案
类似(https://docs.sixlabors.com/articles/imagesharp/gettingstarted.html):
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
// Open the file and detect the file type and decode it.
// Our image is now in an uncompressed, file format agnostic, structure in-memory as a series of pixels.
using (Image image = Image.Load("test-image.png"))
{
// The library automatically picks an encoder based on the file extensions then encodes and write the data to disk.
image.Save("test.gif");
}
推荐阅读
- sql - 案例计数未返回预期信息
- javascript - Javascript文件API读入缓冲区
- github - 我从哪里获得公钥来验证 GitHub 的访问令牌?
- python - 使用 DateTimeIndex 作为 x 轴创建折线图/条形图(双轴 = 月/年)
- javascript - 支持所有类型参数的 Memoize 函数
- python - pandas read_sql 后用逗号分隔的列名字符。(1 个单列名称中的每个字符后都有一个逗号)
- c++ - 如何在现代 OpenGL 中画一个圆?
- java - 如何为 ConnectionPool 配置类编写 JUnit TestClass
- solr - Solr 软提交需要 1.5 秒才能更新文档
- google-bigquery - 我们如何才能发现维护物化视图的成本?