我有一百个JPG图像块,想把它们合并成一个大的JPG。为了实现这一点,我使用以下代码:
using (var combinedBitmap = new Bitmap(combinedWidth, combinedHeights)) {
combinedBitmap.SetResolution(96, 96);
using (var g = Graphics.FromImage(combinedBitmap))
{
g.Clear(Color.White);
foreach (var imagePiece in imagePieces)
{
var imagePath = Path.Combine(slideFolderPath, imagePiece.FileName);
using (var image = Image.FromFile(imagePath))
{
var x = columnXs[imagePiece.Column];
var y = rowYs[imagePiece.Row];
g.DrawImage(image, new Point(x, y));
}
}
}
combinedBitmap.Save(combinedImagePath, ImageFormat.Jpeg);
}一切都很好,直到尺寸(combinedWidth,combinedHeights)超过窗帘阈值,就像这里说的https://stackoverflow.com/a/29175905/623190
合并后的JPG文件的大小为23170 x 23170像素,大小约为50MB -不会太大而不会占用内存。
但是Bitmap不能用更大的维度创建--只是用错误的参数异常中断。
有没有其他方法可以使用C#将JPG图像合并到一个尺寸大于23170 x 23170的大型JPG中?
发布于 2019-06-20 22:33:28
这里有一个使用libvips的解决方案。这是一个流式图像处理库,所以它不是在内存中操作巨大的对象,而是构建管道,然后并行运行它们,在一系列小区域中流式处理图像。
这个例子使用了net-vips,libvip的C#绑定。
using System;
using System.Linq;
using NetVips;
class Merge
{
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: [output] [images]");
return;
}
var image = Image.Black(60000, 60000);
var random = new Random();
foreach (var filename in args.Skip(1))
{
var tile = Image.NewFromFile(filename, access: Enums.Access.Sequential);
var x = random.Next(0, image.Width - tile.Width);
var y = random.Next(0, image.Height - tile.Height);
image = image.Insert(tile, x, y);
}
image.WriteToFile(args[0]);
}
}我制作了一组1000个jpg的图像,每个1450 x 2048 RGB,使用:
for ($i = 0; $i -lt 1000; $i++)
{
# https://commons.wikimedia.org/wiki/File:Taiaroa_Head_-_Otago.jpg
Copy-Item "$PSScriptRoot\..\Taiaroa_Head_-_Otago.jpg" -Destination "$PSScriptRoot\$i.jpg"
}为了测量执行上述代码所需的时间,我使用了PowerShell内置的" measure -Command“(类似于Bash的" time”命令):
$fileNames = (Get-ChildItem -Path $PSScriptRoot -Recurse -Include *.jpg).Name
$results = Measure-Command { dotnet Merge.dll x.jpg $fileNames }
$results | Format-List *使用准备好的图像和上面的脚本,我看到了以下内容:
C:\merge>.\merge.ps1
Ticks : 368520029
Days : 0
Hours : 0
Milliseconds : 852
Minutes : 0
Seconds : 36
TotalDays : 0.000426527811342593
TotalHours : 0.0102366674722222
TotalMilliseconds : 36852.0029
TotalMinutes : 0.614200048333333
TotalSeconds : 36.8520029因此,在我的第8代Intel Core i5 Windows PC上,它在36秒内将1000jpg图像合并成60kx60kjpg的大图像。
https://stackoverflow.com/questions/56598015
复制相似问题