C# 将不同的图片格式(jpg、gif、png等)转换为TIFF格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11840462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert different picture formats (jpg, gif, png, etc.) to TIFF format
提问by user1509
I am working on reading text from an image through OCR. It only supports TIFF format images.
我正在通过 OCR 从图像中读取文本。它仅支持 TIFF 格式的图像。
So, I need to convert other formats to TIFF format. Can it be done? Please help by providing some references.
所以,我需要将其他格式转换为 TIFF 格式。可以做到吗?请提供一些参考资料以提供帮助。
回答by Jacob
If you create an Imageobject in .NET, you can save it as a TIFF. It is one of the many ImageFormatchoices at your disposal.
如果Image在 .NET 中创建对象,则可以将其另存为 TIFF。它是可供您使用的众多ImageFormat选择之一。
Example:
例子:
var png = Image.FromFile("some.png");
png.Save("a.tiff", ImageFormat.Tiff);
You'll need to include the System.Drawingassembly in your project. That assembly will give you a lot of image manipulation capabilities. Hope that helps.
您需要System.Drawing在项目中包含该程序集。该程序集将为您提供许多图像处理功能。希望有帮助。
回答by wbt11a
I tested this with jpg, bmp, png, and gif. Works for single and multipage creation of tiffs. Pass it a full pathname to the file. Hope it helps someone. (extracted from MSDN)
我用 jpg、bmp、png 和 gif 对此进行了测试。适用于单页和多页 tiff 创建。将完整路径名传递给文件。希望它可以帮助某人。(摘自 MSDN)
public static string[] ConvertJpegToTiff(string[] fileNames, bool isMultipage)
{
EncoderParameters encoderParams = new EncoderParameters(1);
ImageCodecInfo tiffCodecInfo = ImageCodecInfo.GetImageEncoders()
.First(ie => ie.MimeType == "image/tiff");
string[] tiffPaths = null;
if (isMultipage)
{
tiffPaths = new string[1];
System.Drawing.Image tiffImg = null;
try
{
for (int i = 0; i < fileNames.Length; i++)
{
if (i == 0)
{
tiffPaths[i] = String.Format("{0}\{1}.tif",
Path.GetDirectoryName(fileNames[i]),
Path.GetFileNameWithoutExtension(fileNames[i]));
// Initialize the first frame of multipage tiff.
tiffImg = System.Drawing.Image.FromFile(fileNames[i]);
encoderParams.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
tiffImg.Save(tiffPaths[i], tiffCodecInfo, encoderParams);
}
else
{
// Add additional frames.
encoderParams.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);
using (System.Drawing.Image frame = System.Drawing.Image.FromFile(fileNames[i]))
{
tiffImg.SaveAdd(frame, encoderParams);
}
}
if (i == fileNames.Length - 1)
{
// When it is the last frame, flush the resources and closing.
encoderParams.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush);
tiffImg.SaveAdd(encoderParams);
}
}
}
finally
{
if (tiffImg != null)
{
tiffImg.Dispose();
tiffImg = null;
}
}
}
else
{
tiffPaths = new string[fileNames.Length];
for (int i = 0; i < fileNames.Length; i++)
{
tiffPaths[i] = String.Format("{0}\{1}.tif",
Path.GetDirectoryName(fileNames[i]),
Path.GetFileNameWithoutExtension(fileNames[i]));
// Save as individual tiff files.
using (System.Drawing.Image tiffImg = System.Drawing.Image.FromFile(fileNames[i]))
{
tiffImg.Save(tiffPaths[i], ImageFormat.Tiff);
}
}
}
return tiffPaths;
}
回答by VDWWD
This is how I convert images that are uploaded to a website. Changed it so it outputs Tiff files. The method input and outputs a byte array so it can easily be used in a variety of ways. But you can easily modify it.
这就是我转换上传到网站的图像的方式。更改它以输出 Tiff 文件。该方法输入和输出一个字节数组,因此可以很容易地以多种方式使用。但是您可以轻松修改它。
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public byte[] ConvertImageToTiff(byte[] SourceImage)
{
//create a new byte array
byte[] bin = new byte[0];
//check if there is data
if (SourceImage == null || SourceImage.Length == 0)
{
return bin;
}
//convert the byte array to a bitmap
Bitmap NewImage;
using (MemoryStream ms = new MemoryStream(SourceImage))
{
NewImage = new Bitmap(ms);
}
//set some properties
Bitmap TempImage = new Bitmap(NewImage.Width, NewImage.Height);
using (Graphics g = Graphics.FromImage(TempImage))
{
g.CompositingMode = CompositingMode.SourceCopy;
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(NewImage, 0, 0, NewImage.Width, NewImage.Height);
}
NewImage = TempImage;
//save the image to a stream
using (MemoryStream ms = new MemoryStream())
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
NewImage.Save(ms, GetEncoderInfo("image/tiff"), encoderParameters);
bin = ms.ToArray();
}
//cleanup
NewImage.Dispose();
TempImage.Dispose();
//return data
return bin;
}
//get the correct encoder info
public ImageCodecInfo GetEncoderInfo(string MimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType.ToLower() == MimeType.ToLower())
return encoders[j];
}
return null;
}
To test
去测试
var oldImage = File.ReadAllBytes(Server.MapPath("OldImage.jpg"));
var newImage = ConvertImageToTiff(oldImage);
File.WriteAllBytes(Server.MapPath("NewImage.tiff"), newImage);
回答by Bibin
To be covert the image in tif format.In the below example to be convert the image and set to a text box.to be see the image in text box is (.tif formate).This sources code is working.
要以 tif 格式隐藏图像。在下面的示例中,要转换图像并设置为文本框。要在文本框中看到图像是(.tif 格式)。此源代码正在工作。
private void btn_Convert(object sender, EventArgs e)
{
string newName = System.IO.Path.GetFileNameWithoutExtension(CurrentFile);
newName = newName + ".tif";
try
{
img.Save(newName, ImageFormat.Tiff);
}
catch (Exception ex)
{
string error = ee.Message.ToString();
MessageBox.Show(MessageBoxIcon.Error);
}
textBox2.Text = System.IO.Path.GetFullPath(newName.ToString());
}
回答by maytham-???????
Intro Note:
- This answer cover the Bounty Question; which is: How do we convert multiple files into 1 tiff? For example, let's say have pdfs, jpegs, pngs, and I'd like to create 1 tiff out of them?
- In this answer I use .net implementation of https://imagemagick.org/index.phpfor image manipulation and and Ghostscript for helping read an AI/EPS/PDF/PS file so we can translate it to image files both are credible and official source.
- After I answered this question I got some extra question in my email asking other merging options, I have therefore extended my answer.
介绍注:
- 这个答案涵盖了赏金问题;即:我们如何将多个文件转换为 1 个 tiff?例如,假设有 pdf、jpeg、png,我想从中创建 1 个 tiff?
- 在这个答案中,我使用https://imagemagick.org/index.php 的.net 实现进行图像处理,使用 Ghostscript 帮助读取 AI/EPS/PDF/PS 文件,以便我们可以将其转换为图像文件,既可靠又可靠官方来源。
- 在我回答这个问题后,我在电子邮件中收到了一些额外的问题,询问其他合并选项,因此我扩展了我的答案。
IMO there are 2 steps to your goal:
IMO 有 2 个步骤可以实现您的目标:
- Install required tools for pdf conversion
- Take all images including pdf formatted files from source and merge them together in one tiff file.
- 安装pdf转换所需的工具
- 从源中获取包括 pdf 格式文件在内的所有图像,并将它们合并到一个 tiff 文件中。
1. Install tools that helps Pdf to Image conversion:
1.安装帮助Pdf转图片的工具:
Step 1 is only required if you intend to convert AI/EPS/PDF/PS file formats. Otherwise just jump to step2.
仅当您打算转换 AI/EPS/PDF/PS 文件格式时才需要执行步骤 1。否则就跳到第2步。
To make it possible converting pdf to any image format, we need a library that can read pdf files and we need a tool to convert it to image type. For this purpose, we will need to install Ghostscript(GNU Affero General Public License).
为了能够将 pdf 转换为任何图像格式,我们需要一个可以读取 pdf 文件的库,我们需要一个将其转换为图像类型的工具。为此,我们需要安装Ghostscript(GNU Affero 通用公共许可证)。
Here after, we need to install ImageMagick.netfor .net in Visual Studio, nuget link.
之后,我们需要在 Visual Studio 中为 .net安装ImageMagick.net,nuget链接。
So far so good.
到现在为止还挺好。
2. Code part
2. 代码部分
Second and Last step is we need to read files (png, jpg, bmp, pdf etc) from folder location and add each file to MagickImageCollection, then we have several options to merge use AppendHorizontally, AppendVertically, Montageor Multiple page Tiff. ImageMagick has tons of features, like resizing, resolution etc, this is just example to demonstrate merging features:
第二个也是最后一步就是我们需要读取的文件夹位置的文件(PNG,JPG,BMP,PDF等),并添加每个文件MagickImageCollection,然后我们有几个选项合并使用AppendHorizontally,AppendVertically,Montage或者多页TIFF。ImageMagick 有很多功能,如调整大小、分辨率等,这只是演示合并功能的示例:
public static void MergeImage(string src, string dest, MergeType type = MergeType.MultiplePage)
{
var files = new DirectoryInfo(src).GetFiles();
using (var images = new MagickImageCollection())
{
foreach (var file in files)
{
var image = new MagickImage(file)
{
Format = MagickFormat.Tif,
Depth = 8,
};
images.Add(image);
}
switch (type)
{
case MergeType.Vertical:
using (var result = images.AppendVertically())
{
result.AdaptiveResize(new MagickGeometry(){Height = 600, Width = 800});
result.Write(dest);
}
break;
case MergeType.Horizontal:
using (var result = images.AppendHorizontally())
{
result.AdaptiveResize(new MagickGeometry(){Height = 600, Width = 800});
result.Write(dest);
}
break;
case MergeType.Montage:
var settings = new MontageSettings
{
BackgroundColor = new MagickColor("#FFF"),
Geometry = new MagickGeometry("1x1<")
};
using (var result = images.Montage(settings))
{
result.Write(dest);
}
break;
case MergeType.MultiplePage:
images.Write(dest);
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, "Un-support choice");
}
images.Dispose();
}
}
public enum MergeType
{
MultiplePage,
Vertical,
Horizontal,
Montage
}
To run the code
运行代码
public static void Main(string[] args)
{
var src = @"C:\temp\Images";
var dest1 = @"C:\temp\Output\MultiplePage.tiff";
var dest2 = @"C:\temp\Output\Vertical.tiff";
var dest3 = @"C:\temp\Output\Horizontal.tiff";
var dest4 = @"C:\temp\Output\Montage.tiff";
MergeImage(src, dest1);
MergeImage(src, dest2, MergeType.Vertical);
MergeImage(src, dest3, MergeType.Horizontal);
MergeImage(src, dest4, MergeType.Montage);
}
Here is 4 input files in C:\temp\Images:
这是 C:\temp\Images 中的 4 个输入文件:
After running the code, we get 4 new files under C:\temp\Output looks like this:
运行代码后,我们在 C:\temp\Output 下得到 4 个新文件,如下所示:
Final note:
- it is possible to merge multiple images to tiff using System.Drawing; and using System.Drawing.Imaging; with out using ImageMagick, but pdf does require a third party conversion library or tool, therefore I use Ghostscript and ImageMagick for C#.
- ImageMagick has many features, so you can change the resolution, size of output file etc. it is well recognized library.
最后说明:
- 可以使用 System.Drawing 将多个图像合并到 tiff;并使用 System.Drawing.Imaging; 不使用 ImageMagick,但 pdf 确实需要第三方转换库或工具,因此我使用 Ghostscript 和 ImageMagick for C#。
- ImageMagick 有很多功能,所以你可以改变分辨率,输出文件的大小等。它是公认的库。
Disclaimer: A part of this answer is taken from my my personal web site https://itbackyard.com/how-to-convert-ai-eps-pdf-ps-to-image-file/with source code to github.
免责声明:此答案的一部分摘自我的个人网站https://itbackyard.com/how-to-convert-ai-eps-pdf-ps-to-image-file/以及 github 的源代码。
回答by fmw42
ImageMagick command line can do that easily. It is supplied on most Linux systems and is available for Mac or Windows also. See https://imagemagick.org/script/download.php
ImageMagick 命令行可以轻松做到这一点。它在大多数 Linux 系统上提供,也可用于 Mac 或 Windows。见https://imagemagick.org/script/download.php
convert image.suffix -compress XXX image.tiff
or you can process a whole folder of files using
或者您可以使用处理整个文件夹的文件
mogrify -format tiff -path path/to/output_directory *
ImageMagick supports combining multiple images into a multi-page TIFF. And the images can be of mixed types even including PDF.
ImageMagick 支持将多个图像组合成多页 TIFF。图像可以是混合类型,甚至包括 PDF。
convert image1.suffix1 image2.suffix2 ... -compress XXX imageN.suffixN output.tiff
You can choose from a number of compression formats or no compression.
您可以选择多种压缩格式或不压缩。
See
看
https://imagemagick.org/script/command-line-processing.php
https://imagemagick.org/script/command-line-processing.php
https://imagemagick.org/Usage/basics/
https://imagemagick.org/Usage/basics/
https://imagemagick.org/Usage/basics/#mogrify
https://imagemagick.org/Usage/basics/#mogrify
https://imagemagick.org/script/command-line-options.php#compress
https://imagemagick.org/script/command-line-options.php#compress
Or you can use Magick.Net for a C# interface. See https://github.com/dlemstra/Magick.NET
或者您可以将 Magick.Net 用于 C# 接口。见https://github.com/dlemstra/Magick.NET
Main ImageMagick page is at https://imagemagick.org.
ImageMagick 主页面位于https://imagemagick.org。
Supported formats are listed at https://imagemagick.org/script/formats.php
支持的格式列于https://imagemagick.org/script/formats.php
You can easily process your images to resize them, convert to grayscale, filter (sharpen), threshold, etc, all in the same command line.
您可以轻松地处理您的图像以调整它们的大小、转换为灰度、过滤(锐化)、阈值等,所有这些都在同一个命令行中。
See
看
https://imagemagick.org/Usage/
https://imagemagick.org/Usage/


