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

智能推荐

RK3399运行瑞芯微官方yolov5 C++代码_yolov9 rk3399-程序员宅基地

文章浏览阅读5.8k次。RK3399编译调试瑞芯微官方yolov5 C++代码yolov5 C++代码代码地址https://github.com/rockchip-linux/rknpu.git /rknn/rknn_api/example/rknn_yolov5_demorknn 模型使用rknpu/rknn/rknn_api/examples)/rknn_yolov5_demo/model/rk180x/yolov5s_relu_rk180x_out_opt.rknn 地址yolov5s_relu_rk180_yolov9 rk3399

mmdetection3d 源码学习 mvxnet(多模态融合)-程序员宅基地

文章浏览阅读5k次。mmdetection3d 源码学习 mvxnet(多模态融合)配置文件dv_mvx-fpn_second_secfpn_adamw_2x8_80e_kitti-3d-3class.py模型# model settingsvoxel_size = [0.05, 0.05, 0.1]point_cloud_range = [0, -40, -3, 70.4, 40, 1]##模型 图像:主干 ResNet,neck FPN;点云:voxel编码,主干second(稀疏编码),neck secon_mvxnet

C++操作Mysql数据库/Linux下_c++ 操作mysql数据库-程序员宅基地

文章浏览阅读3.3k次,点赞14次,收藏36次。想用C++写项目,数据库是必须的,所以这两天学了一下C++操作Mysql数据库的方法。也没有什么教程,就是在网上搜的知识,下面汇总一下。 连接MySQL数据库有两种方法:第一种是使用ADO连接,不过这种只适合Windows平台;第二种是使用MySQL自己的C API函数连接数据库。我是在Linux平台下开发,所以就采用第二种方法,有很多Api函数,但是常用的就几个,我也是就用到其中的几个。API函_c++ 操作mysql数据库

在Watir中调用JavaScript脚本_watir执行脚本-程序员宅基地

文章浏览阅读3.9k次。如何在Watir中调用JavaScript脚本?下面的脚本实现了此功能,主要原理是通过IE访问Document,再访问parentWindow,最终还是由IE在执行JavaScript脚本: require watir#定义调用JS的类方法class Watir::IE def run_script(js) ie.Document.parentWindow.execS_watir执行脚本

为什么不能使用Thread.stop()方法?_禁止使用thread.stop()来终止线程-程序员宅基地

文章浏览阅读2.1k次。从SUN的官方文档可以得知,调用Thread.stop()方法是不安全的,这是因为当调用Thread.stop()方法时,会发生下面两件事:1. 即刻抛出ThreadDeath异常,在线程的run()方法内,任何一点都有可能抛出ThreadDeath Error,包括在catch或finally语句中。2. 释放该线程所持有的所有的锁 当线程抛出ThreadDeath异常时,会导致_禁止使用thread.stop()来终止线程

神秘魔术动作能量冲击波特效音效Arcane Forces第一套 MAGIC - ARCANE FORCES DESIGNED_magic – arcane forces-程序员宅基地

文章浏览阅读222次。神秘魔术动作能量冲击波特效音效Arcane Forces第一套 MAGIC - ARCANE FORCES DESIGNED原文地址:https://www.aeziyuan.com/t-20646.html文件格式:.WAV文件大小:1.26 GB(解压包大小)文件数量:124音频码率:96kHz, 24-bit音效适用于任何音/视频后期编辑软件,直接导入即可使用包含:酸,奥术,障壁,呼吸,增益,诅咒,减伤,神圣,电,能量,火,玻璃,冰,冲击,光,液体,金属,加工,抛射,隆隆声,序,召唤,._magic – arcane forces

随便推点

Linux压缩解压tar.gz和zip包命令汇总_加压gz包命令-程序员宅基地

文章浏览阅读3.5k次。Linux压缩解压tar.gz和zip包命令汇总_加压gz包命令

c语言基础: L1-016 查验身份证_c语言检验身份照-程序员宅基地

文章浏览阅读1.5k次。一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得到值Z;最后按照以下关系对应Z值与校验码M现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。_c语言检验身份照

CI867AK01丨Modbus TCP接口模件丨3BSE092689R1-程序员宅基地

文章浏览阅读450次,点赞4次,收藏6次。CI867AK013BSE092689R1Modbus TCP接口模件模块,通过无线或有线的方式,实现设备之间的数据传输和通信连接。

PySide2入门--PySide2介绍与配置-程序员宅基地

文章浏览阅读2w次,点赞16次,收藏96次。前言 因为有对GUI界面开发的需求,我前些阵子接触过Qt,一套著名的跨平台的C++图形界面框架。Qt开发最有效的Qt creator,跨平台且集成多款工具,上手体验十分友好。但是,由于C++导入第三方库相对麻烦,而且现有的代码都基于Python实现。此处将介绍Qt相应的Python模块——PySide。为什么不选择PyQt? PySide2和PyQt5同样对应的Qt5框架,PyQt甚至要比PySide出现更早,社区更完备、中文文档更丰富。但是,值得注意的是:二者的许可证存在着差异。 PyQ_pyside2

Jupyter Notebook如何调试?JupyterLab作为DeBug调试工具及调试教程_jupyterlab怎么debug-程序员宅基地

文章浏览阅读2.9w次,点赞30次,收藏107次。引言xeus-python是2020年新出的Jupyter notebook调试工具,参考机器之心的文章首款 Jupyter 官方可视化 Debug 工具,JupyterLab 未来可默认支持 Debug安装过程安装JupyterLab 前端插件jupyter labextension install @jupyterlab/debugger安装xeus-python作为后端kernelconda install xeus-python -c conda-forge调试教程只要装好前端与_jupyterlab怎么debug

如何将xml转换为json_xml转json-程序员宅基地

文章浏览阅读3.8k次。<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160807</version> </dependency>导入 json-20160807.jar jar包 直接调用 XML.toJSONObject(“xml内容”) 就可以把XML._xml转json

推荐文章

热门文章

相关标签