C# 将多个图片合并成TIFF文件的两种方法-程序员宅基地

技术标签: navicat  git  svg  nagios  less  

最近需要用到TIF格式的文件,研究了一段时间,终于有点结果了,

发现两种方式,第一种是使用BitMiracle.LibTiff.NET,直接在Nuget上安装即可

,第二种是使用RasterEdge.DocImageSDK,要从官网下载dll包

第一种免费,但是生成的tiff文件大小比原始图片大的多

第二种收费,但是有试用期一个月,效果很好,生成的tiff文件比原图小的多而且不失真。过期之后,只需要到官网下载最新dll,重新引用即可再来一个月试用。。。

先说第二种RasterEdge.DocImageSDK的使用方法:

官网地址:http://www.rasteredge.com/how-to/csharp-imaging/tiff-convert-bmp/
//过期后打开上面 这个网址,重新下载 dll包,重新引用即可 bin x64 4.0

新建一个cmd项目,测试代码如下:

class Program
    {
        private static byte[] CompressionImage(Stream fileStream, long quality)
        {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream))
            {
                using (Bitmap bitmap = new Bitmap(img))
                {
                    ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
                    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameters myEncoderParameters = new EncoderParameters(1);
                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        bitmap.Save(ms, CodecInfo, myEncoderParameters);
                        myEncoderParameters.Dispose();
                        myEncoderParameter.Dispose();
                        return ms.ToArray();
                    }
                }
            }
        }
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                { return codec; }
            }
            return null;
        }
        static void Main(string[] args)
        {
            string[] imagePaths = System.IO.Directory.GetFiles(@"D:\images\","*.jpg");
            
            Bitmap[] bmps = new Bitmap[imagePaths.Count()];
            for (int i = 0; i < imagePaths.Length; i++)
            {
                var stream = new FileStream(imagePaths[i], FileMode.Open);
                var by = CompressionImage(stream, 100);
                stream.Close();


                Bitmap tmpBmp = new Bitmap(new MemoryStream(by));


                if (tmpBmp != null)
                    bmps[i] = tmpBmp;
            }
            ImageOutputOption option = new ImageOutputOption() { Color = ColorType.Color, Compression = ImageCompress.CCITT };
            TIFFDocument tifDoc = new TIFFDocument(bmps, option);
            if (tifDoc == null)
                throw new Exception("Fail to construct TIFF Document");
            tifDoc.Save(@"D:\images\test.tif");
        }
    
    }

下面说说第二种免费的方式:

新建一个TiffHelper帮助类:

using BitMiracle.LibTiff.Classic;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace JpgToTiff
{
    public class UserErrorHandler : TiffErrorHandler
    {
        public override void WarningHandler(Tiff tif, string method, string format, params object[] args)
        {
            //base.WarningHandler(tif, method, format, args);
        }
        public override void WarningHandlerExt(Tiff tif, object clientData, string method, string format, params object[] args)
        {
            //base.WarningHandlerExt(tif, clientData, method, format, args);
        }
    }
    public class TiffHelper
    {
        public static UserErrorHandler m_errorHandler = new UserErrorHandler();
        static TiffHelper()
        {
            Tiff.SetErrorHandler(m_errorHandler);
        }
        /// <summary>
        /// 合并jpg
        /// </summary>
        /// <param name="bmps">bitmap数组</param>
        /// <param name="tiffSavePath">保存路径</param>
        /// <param name="quality">图片质量,1-100</param>
        /// <returns></returns>
        public static bool Jpegs2Tiff(Bitmap[] bmps, string tiffSavePath, int quality = 15)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                using (Tiff tif = Tiff.ClientOpen(@"in-memory", "w", ms, new TiffStream()))
                {
                    foreach (var bmp in bmps)//
                    {
                        byte[] raster = GetImageRasterBytes(bmp, PixelFormat.Format24bppRgb);
                        tif.SetField(TiffTag.IMAGEWIDTH, bmp.Width);
                        tif.SetField(TiffTag.IMAGELENGTH, bmp.Height);
                        tif.SetField(TiffTag.COMPRESSION, Compression.JPEG);
                        tif.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);
                        tif.SetField(TiffTag.JPEGQUALITY, quality);
                        tif.SetField(TiffTag.ROWSPERSTRIP, bmp.Height);


                        tif.SetField(TiffTag.XRESOLUTION, 90);
                        tif.SetField(TiffTag.YRESOLUTION, 90);


                        tif.SetField(TiffTag.BITSPERSAMPLE, 8);
                        tif.SetField(TiffTag.SAMPLESPERPIXEL, 3);


                        tif.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);


                        int stride = raster.Length / bmp.Height;
                        ConvertSamples(raster, bmp.Width, bmp.Height);


                        for (int i = 0, offset = 0; i < bmp.Height; i++)
                        {
                            tif.WriteScanline(raster, offset, i, 0);
                            offset += stride;
                        }


                        tif.WriteDirectory();
                    }
                    System.IO.FileStream fs = new FileStream(tiffSavePath, FileMode.Create);
                    
                    ms.Seek(0, SeekOrigin.Begin);
                    fs.Write(ms.ToArray(), 0, (int)ms.Length);
                    fs.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        private static byte[] GetImageRasterBytes(Bitmap bmp, PixelFormat format)
        {
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            byte[] bits = null;
            try
            {
                BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
                bits = new byte[bmpdata.Stride * bmpdata.Height];
                System.Runtime.InteropServices.Marshal.Copy(bmpdata.Scan0, bits, 0, bits.Length);
                bmp.UnlockBits(bmpdata);
            }
            catch
            {
                return null;
            }
            return bits;
        }
        private static void ConvertSamples(byte[] data, int width, int height)
        {
            int stride = data.Length / height;
            const int samplesPerPixel = 3;


            for (int y = 0; y < height; y++)
            {
                int offset = stride * y;
                int strideEnd = offset + width * samplesPerPixel;


                for (int i = offset; i < strideEnd; i += samplesPerPixel)
                {
                    byte temp = data[i + 2];
                    data[i + 2] = data[i];
                    data[i] = temp;
                }
            }
        }
    }
}

下面是测试代码:

class Program
    {
        private static byte[] CompressionImage(Stream fileStream, long quality)
        {
            using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream))
            {
                using (Bitmap bitmap = new Bitmap(img))
                {
                    ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
                    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameters myEncoderParameters = new EncoderParameters(1);
                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        bitmap.Save(ms, CodecInfo, myEncoderParameters);
                        myEncoderParameters.Dispose();
                        myEncoderParameter.Dispose();
                        return ms.ToArray();
                    }
                }
            }
        }
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                { return codec; }
            }
            return null;
        }
        static void Main(string[] args)
        {
            string[] imagePaths = System.IO.Directory.GetFiles(@"D:\images\","*.jpg");
            
            Bitmap[] bmps = new Bitmap[imagePaths.Count()];
            for (int i = 0; i < imagePaths.Length; i++)
            {
                var stream = new FileStream(imagePaths[i], FileMode.Open);
                var by = CompressionImage(stream, 100);
                stream.Close();


                Bitmap tmpBmp = new Bitmap(new MemoryStream(by));


                if (tmpBmp != null)
                    bmps[i] = tmpBmp;
            }
            TiffHelper.Jpegs2Tiff(bmps, @"D:\images\test.tif", 100);
        }   
    }

可以看到,两个方式生成的tif文件大小简直天壤之别。。。

7个原图大小4.8M,第一种1.36M,

第二种直接23.5M…

也可能是我没有弄好压缩方式。。。。

那我就不晓得了。

如果喜欢,点个赞呗

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sD7O95O/article/details/116358489

智能推荐

Linux用户管理详解_linux登录qq是什么意思-程序员宅基地

文章浏览阅读448次。Linux用户管理用户基本概念什么是用户用户指的是能够正常登录Linux或Windows系统,比如:登录QQ的用户、登入王者荣耀的用户、等等[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nz1edsjq-1626145230283)(C:\Users\李开开\AppData\Roaming\Typora\typora-user-images\image-20210712171546940.png)]为什么需要用户系统上的每一个进程(运行的程序),都_linux登录qq是什么意思

Unity中协程里Animator获取状态一些笔记_getanimatortransitioninfo-程序员宅基地

文章浏览阅读4.5k次,点赞4次,收藏7次。最近用Animator获取状态各种获取错误,所以记一下笔记Animator中可以获取三种不同的状态:GetCurrentAnimatorStateInfo 获取正确的状态机状态GetNextAnimatorStateInfo 获取下一个状态机的状态GetAnimatorTransitionInfo 获取状态机的过渡状态动画同步是在帧最前,而协程是在帧的最后调用。所以切换状态后在协程获取状..._getanimatortransitioninfo

LATEX 中参考文献顺序_spphys.bst-程序员宅基地

文章浏览阅读924次。\bibliography{report} % bibliography data in report.bib\bibliographystyle{unsrt} % makes bibtex use spphys.bstunsrt 表示按照引用的先后顺序进行排序_spphys.bst

Linux下部署maven-web项目,包括JDK安装、TOMCAT安装、MYSQL安装详细解释-程序员宅基地

文章浏览阅读335次。为什么80%的码农都做不了架构师?>>> ..._linux系统搭建maven+tomcat+mysql

effective stl 第18条: 避免使用vector<bool>-程序员宅基地

文章浏览阅读354次。vector不是容器,并且它不存储bool,因为他是按照位来存储的,即一个bool只占一个二进制位。假设有vector v;则&v[0]会引起编译错误。如果不使用&v[0]可以使用vector,否则,可以用deque 和bitset来替代_避免使用vector

Bug的严重程度(缺陷程度)有哪几种。。。。_bug严重程度-程序员宅基地

文章浏览阅读6.8k次,点赞2次,收藏20次。Bug程度分为四种,分别为:致命S0:致命缺陷是指会造成安全问题的各类缺陷。在测试中很少出现,一旦出现立即中止版本测试。系统崩溃,数据丢失,数据毁坏,无法运行等Bug。严重S1:是指可以引起易于纠正的异常情况,可能引起易于修复的故障或对产品外观造成难以接受的缺陷。不影响其他功能的情况下可以继续版本测试。功能和性能不能实现。 次要功能全部丧失。 功能遗漏等等。 一般S2:一般缺陷是指不影响产品的..._bug严重程度

随便推点

《iOS 9 开发指南》——第1章,第1.3节工欲善其事,必先利其器——搭建开发环境...-程序员宅基地

文章浏览阅读202次。本节书摘来自异步社区《iOS 9 开发指南》一书中的第1章,第1.3节工欲善其事,必先利其器——搭建开发环境,作者 管蕾,更多章节内容可以访问云栖社区“异步社区”公众号查看1.3 工欲善其事,必先利其器——搭建开发环境iOS 9 开发指南图片 2 知识点讲解:光盘:视频知识点第1章搭建开发环境.mp4学习iOS 9开发也离不开好的开发工具的帮助,如果使..._(1)下载完成后单击打开下载的“.dmg”格式文件,然后双击xcode文件开始安装。

iView 3.3.2 发布,基于 Vue.js 的企业级 UI 组件库-程序员宅基地

文章浏览阅读115次。开发四年只会写业务代码,分布式高并发都不会还做程序员? iView 3.3.2 发布了,iView 是一套基于 Vue..._iview 3.2.2

详解not in与not exists的区别与用法(not in的性能并不差!)-程序员宅基地

文章浏览阅读93次。2019独角兽企业重金招聘Python工程师标准>>> ..._predicate not in查询

SpringBoot整合Spring Data JPA、MySQL、Druid并使用Mockito实现单元测试_spring jpa mock-程序员宅基地

文章浏览阅读4.7k次,点赞3次,收藏7次。SpringBoot整合Spring Data JPA、MySQL、Druid并使用Mockito实现单元测试_spring jpa mock

java 解析excel金额_java解析Excel(xls、xlsx两种格式)-程序员宅基地

文章浏览阅读441次。package poi;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.LinkedHashMap;import j..._java getcellformatvalue

50个漂亮免费的 WordPress 主题(下)_wordpressbo'ke 免费-程序员宅基地

文章浏览阅读170次。50个漂亮免费的 WordPress 主题(上)Minimatica( Demo | Download )Placeholder( Demo | Download )Navly( Demo | Download )Cobera( Demo | Download )The Blog( Demo | Download )Gabi..._wordpressbo'ke 免费

推荐文章

热门文章

相关标签