在 C# 中将所有内容转换为 JPG

2024-01-30

我有一个如下所示的函数:

    // Convert To JPG 
    // 
    public string AlltoJPG(FileInfo foo)
    {
        // Get file extension
        string fileExtension = foo.Extension;

        // Get file name without extenstion
        string fileName = foo.Name.Replace(foo.Extension, string.Empty) + ".jpg";

        /*------------------------------------------------------------------------*/

        /// <Check for PNG File Format>
        if (fileExtension == ".png" || fileExtension == ".PNG")
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);

            // Assumes img is the PNG you are converting
            using (Bitmap b = new Bitmap(img.Width, img.Height))
            {
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(b))
                {
                    g.Clear(System.Drawing.Color.White);
                    g.DrawImageUnscaled(img, 0, 0);
                }

                // Save the image as a JPG
                b.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

        }

        /*------------------------------------------------------------------------*/

        /// <Check for GIF File Format>
        if (fileExtension == ".gif" || fileExtension == ".GIF")
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);

            // Construct a bitmap from the image resource.
            Bitmap bmp1 = new Bitmap(img.Width, img.Height);

            // Save the image as a JPG
            bmp1.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        /*------------------------------------------------------------------------*/

        /// <Check for BMP File Format>
        if (fileExtension == ".bmp" || fileExtension == ".BMP")
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);

            // Construct a bitmap from the image resource.
            Bitmap bmp1 = new Bitmap(img.Width, img.Height);

            // Save the image as a JPG
            bmp1.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        /*------------------------------------------------------------------------*/

        /// <Check for TIFF File Format>
        if (fileExtension == ".tiff" || fileExtension == ".TIFF")
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);

            // Construct a bitmap from the image resource.
            Bitmap bmp1 = new Bitmap(img.Width, img.Height);

            // Save the image as a JPG
            bmp1.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        /*------------------------------------------------------------------------*/
        fileName = foo.DirectoryName + "\\" + fileName;
        return fileName;
    }

我正在尝试转换bmp,png,gif,tiff文件格式为jpg, but GDI+如给出:

System.OutOfMemoryException 未处理
消息=Bellek Yetersiz。
来源=系统.绘图
堆栈跟踪:
konum:System.Drawing.Image.FromFile(字符串文件名,布尔值useEmbeddedColorManagement)
konum:System.Drawing.Image.FromFile(字符串文件名)

那么我怎样才能避免这种情况并至少转换PNG and BMP文件到JPG?

这是错误的图片:


我发现问题了!这是由 PNG alpha 通道引起的。

感谢 max,下面的链接解决了我的问题:

如何将透明 PNG 加载到位图并忽略 Alpha 通道 https://stackoverflow.com/questions/6809442/how-to-load-transparent-png-to-bitmap-and-ignore-alpha-channel


public static void SetAlpha(this Bitmap bmp, byte alpha)
{
    if(bmp == null) throw new ArgumentNullException("bmp");

    var data = bmp.LockBits(
        new Rectangle(0, 0, bmp.Width, bmp.Height),
        System.Drawing.Imaging.ImageLockMode.ReadWrite,
        System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    var line = data.Scan0;
    var eof = line + data.Height * data.Stride;
    while(line != eof)
    {
        var pixelAlpha = line + 3;
        var eol = pixelAlpha + data.Width * 4;
        while(pixelAlpha != eol)
        {
            System.Runtime.InteropServices.Marshal.WriteByte(
                pixelAlpha, alpha);
            pixelAlpha += 4;
        }
        line += data.Stride;
    }
    bmp.UnlockBits(data);
}

Usage:

var pngImage = new Bitmap("filename.png");
pngImage.SetAlpha(255);

设置 alpha 后,它开始正常工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中将所有内容转换为 JPG 的相关文章

  • 将复选框添加到 UniformGrid

    我正在尝试将复选框动态添加到 wpf 中的统一网格中 但看起来网格没有为它们分配足够的空间 所以它们都有点互相重叠 这就是我将它们添加到后面的代码中的方法 foreach string folder in subfolders PathCh
  • 是否可以强制 XMLWriter 将元素写入单引号中?

    这是我的代码 var ptFirstName tboxFirstName Text writer WriteAttributeString first ptFirstName 请注意 即使我使用 ptFirstName 也会以双引号结束 p
  • 获取按下的按钮的返回值

    我有一个在特定事件中弹出的表单 它从数组中提取按钮并将标签值设置为特定值 因此 如果您要按下或单击此按钮 该函数应返回标签值 我怎样才能做到这一点 我如何知道点击了哪个按钮 此时代码返回 DialogResult 但我想从函数返回 Tag
  • UML类图:抽象方法和属性是这样写的吗?

    当我第一次为一个小型 C 项目创建 uml 类图时 我在属性方面遇到了一些麻烦 最后我只是将属性添加为变量 lt
  • 使闭包捕获的变量变得易失性

    闭包捕获的变量如何与不同线程交互 在下面的示例代码中 我想将totalEvents 声明为易失性的 但C 不允许这样做 是的 我知道这是错误的代码 这只是一个例子 private void WaitFor10Events volatile
  • 实时服务器上的 woff 字体 MIME 类型错误

    我有一个 asp net MVC 4 网站 我在其中使用 woff 字体 在 VS IIS 上运行时一切正常 然而 当我将 pate 上传到 1and1 托管 实时服务器 时 我得到以下信息 网络错误 404 未找到 http www co
  • Json.NET - 反序列化接口属性引发错误“类型是接口或抽象类,无法实例化”

    我有一个类 其属性是接口 public class Foo public int Number get set public ISomething Thing get set 尝试反序列化Foo使用 Json NET 的类给我一条错误消息
  • Web API - 访问 DbContext 类中的 HttpContext

    在我的 C Web API 应用程序中 我添加了CreatedDate and CreatedBy所有表中的列 现在 每当在任何表中添加新记录时 我想填充这些列 为此目的我已经覆盖SaveChanges and SaveChangesAsy
  • 如何将图像路径保存到Live Tile的WP8本地文件夹

    我正在更新我的 Windows Phone 应用程序以使用新的 WP8 文件存储 API 本地文件夹 而不是 WP7 API 隔离存储文件 旧的工作方法 这是我如何成功地将图像保存到 共享 ShellContent文件夹使用隔离存储文件方法
  • C# 中的递归自定义配置

    我正在尝试创建一个遵循以下递归结构的自定义配置部分
  • 从路径中获取文件夹名称

    我有一些路c server folderName1 another name something another folder 我如何从那里提取最后一个文件夹名称 我尝试了几件事 但没有成功 我只是不想寻找最后的 然后就去休息了 Thank
  • Github Action 在运行可执行文件时卡住

    我正在尝试设置运行google tests on a C repository using Github Actions正在运行的Windows Latest 构建过程完成 但是当运行测试时 它被卡住并且不执行从生成的可执行文件Visual
  • for循环中计数器变量的范围是多少?

    我在 Visual Studio 2008 中收到以下错误 Error 1 A local variable named i cannot be declared in this scope because it would give a
  • 如何将单个 char 转换为 int [重复]

    这个问题在这里已经有答案了 我有一串数字 例如 123456789 我需要提取它们中的每一个以在计算中使用它们 我当然可以通过索引访问每个字符 但是如何将其转换为 int 我研究过 atoi 但它需要一个字符串作为参数 因此 我必须将每个字
  • 将 xml 反序列化为类,list<> 出现问题

    我有以下 XML
  • 插入记录后如何从SQL Server获取Identity值

    我在数据库中添加一条记录identity价值 我想在插入后获取身份值 我不想通过存储过程来做到这一点 这是我的代码 SQLString INSERT INTO myTable SQLString Cal1 Cal2 Cal3 Cal4 SQ
  • 为什么 C# Math.Ceiling 向下舍入?

    我今天过得很艰难 但有些事情不太对劲 在我的 C 代码中 我有这样的内容 Math Ceiling decimal this TotalRecordCount this PageSize Where int TotalRecordCount
  • mysql-connector-c++ - “get_driver_instance”不是“sql::mysql”的成员

    我是 C 的初学者 我认为学习的唯一方法就是接触一些代码 我正在尝试构建一个连接到 mysql 数据库的程序 我在 Linux 上使用 g 没有想法 我运行 make 这是我的错误 hello cpp 38 error get driver
  • C 中的异或运算符

    在进行按位操作时 我在确定何时使用 XOR 运算符时遇到一些困难 按位与和或非常简单 当您想要屏蔽位时 请使用按位 AND 常见用例是 IP 寻址和子网掩码 当您想要打开位时 请使用包含或 然而 XOR 总是让我明白 我觉得如果在面试中被问
  • 使用 libcurl 检查 SFTP 站点上是否存在文件

    我使用 C 和 libcurl 进行 SFTP FTPS 传输 在上传文件之前 我需要检查文件是否存在而不实际下载它 如果该文件不存在 我会遇到以下问题 set up curlhandle for the public private ke

随机推荐