将大量(约1000-2000张)JPEG图像合并为一张。

6

我现在使用的代码针对大约300张图像是有效的,但我需要合并超过一千张。

private static void CombineThumbStripImages(string[] imageFiles)
{
    int index = 0;
    using (var result = new Bitmap(192 * imageFiles.Length, 112))
    {
        using (var graphics = Graphics.FromImage(result))
        {
            graphics.Clear(Color.White);
            int leftPosition = 0;
            for (index = 0; index < imageFiles.Length; index++)
            {
                string file = imageFiles[index];
                using (var image = new Bitmap(file))
                {
                    var rect = new Rectangle(leftPosition, 0, 192, 112);
                    graphics.DrawImage(image, rect);
                    leftPosition += 192;
                }
            }
        }
        result.Save("result.jpg", ImageFormat.Jpeg);
    }
}

它会抛出以下异常:
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

Additional information: A generic error occurred in GDI+.

有人可以帮忙吗?


2
它什么时候抛出异常?是在最开始还是在几次迭代后(考虑到您的说法,我倾向于后者)?可能是因为您正在加载不支持的格式,或者在您的图形对象中耗尽了内存。我不太清楚GDI如何处理这个问题,但是一些断点可能有助于识别问题。 - KappaG3
这是一个非常好的想法,谢谢。需要大量的代码修改,但至少它能工作。 有没有办法在不使用GDI的情况下将它们结合起来? - Tamás Varga
2
当您附加342(192像素)个文件时,会抛出异常,但不是341。342张图像的结果位图图像的宽度为65,664。341张图像的位图宽度为65,472。GDI+可能使用无符号短整型来表示宽度和高度,其最大值为65,536。 - astallaslions
@StephenM 不管 GDI+ 使用什么,.jpeg 文件的大小限制为 65,536 x 65,536。 - Loren Pechtel
显示剩余11条评论
2个回答

1

为什么不使用类似XNA或OpenGL的工具来实现这个功能?

我知道你可以使用Texture2D...并且我目前正在学习OpenGL,希望能够用它来实现,但是不知道怎么做。

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d_members.aspx (在公共场合上保存为JPEG)

我曾经做过类似的事情来制作精灵表,基本上你需要使用任何细分或组织算法来优化空间利用,创建一个巨大的Texture2D。当然有很多方法可以做到这一点。

例如http://xbox.create.msdn.com/en-US/education/catalog/sample/sprite_sheet

做这个工作可能只需要几个小时。 XNA非常容易,特别是如果你只是依赖于外部库。 用这种方式做应该会很好。


0

问题出在这行代码。

result.Save("result.jpg", ImageFormat.Jpeg);

看起来保存jpeg/png格式时出现了错误。我已经将您的代码加载到VS2008 + Windows 7中。

如果您想使用相同的代码,请将图像格式更改为bmp或tiff

result.Save("result.bmp", ImageFormat.Bmp); // this works, but the file size is huge

或者

result.Save("result.tiff", ImageFormat.Tiff); // this also works, files is not as big

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接