这几天心血来潮做了一个批量图片缩放,转换格式,并且可以根据exif的信息旋转图片,校正exif信息后保存的小程序.根据配置文件 指定需要的功能.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
using System;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Text;
 
namespace PhotoUtil
{
    class Program
    {
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);
        private const String configFile = "Config.ini";
 
        public static void Main(string[] args)
        {
            DirectoryInfo workingDir = new DirectoryInfo(ReadConfig("General", "WorkingDir",Environment.CurrentDirectory));
            if (!workingDir.Exists)
            {
                workingDir = new DirectoryInfo(Environment.CurrentDirectory);
            }
            int quality=int.Parse(ReadConfig("General", "Quality", "85"));
            bool needResize = Boolean.Parse(ReadConfig("ResizeImage", "Enable", "false"));
            int newWidth = int.Parse(ReadConfig("ResizeImage", "NewWidth", "800"));
            int newHeight = int.Parse(ReadConfig("ResizeImage", "NewHeight", "600"));
            bool padding = Boolean.Parse(ReadConfig("ResizeImage", "Padding", "false"));
            bool needRotate = Boolean.Parse(ReadConfig("RotateImage", "Enable", "true"));
            FileInfo[] files = workingDir.GetFiles();
            DirectoryInfo output = workingDir.CreateSubdirectory(DateTime.Now.ToString("yyyyMMdd") + "转换\r
            foreach (FileInfo i in files)
            {
                String type = i.Extension.ToLower();
                if (type.Contains("jpg") || type.Contains("jpeg") || (type.Contains("png")) || type.Contains("tif") || type.Contains("bmp"))
                {
                    Image img = Image.FromFile(i.FullName);
                    if (needResize)
                    {
                        Console.WriteLine("Resizing " + i.FullName);
                        ResizeImage(ref img, newWidth, newHeight, padding);
                    }
                    if (needRotate)
                    {
                        Console.WriteLine("Rotating " + i.FullName);
                        RotateImage(img);
                    }
                    SaveAs(img, output.FullName+"\\\\"+i.Name, quality);
                }
            }
            Console.ReadLine();
        }
 
        private static void SaveAs(Image img, string dest, long quality)
        {
            if (quality > 100 || quality < 1)
            {
                quality = 85;
            }
            EncoderParameters para = new EncoderParameters();
            para.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            String extension = new FileInfo(dest).Extension;
            ImageCodecInfo info = GetImageCodecInfoByExtension(extension);
            if (info != null)
            {
                img.Save(dest, info, para);
            }
            else
            {
                throw new Exception("Unrecognized  format \\"" + extension + "\\"!\r
            }
        }
 
        private static void ResizeImage(ref Image image, int expectDestWidth, int expectDestHeight,bool padding)
        {
            PropertyItem[] exif = image.PropertyItems;
            int targetWidth = 0;
            int targetHeight = 0;
            double srcHWRate = (double)image.Width / (double)image.Height;
            double expectHWRate = (double)expectDestWidth / (double)expectDestHeight;
            if (srcHWRate > expectHWRate)
            {
                targetWidth = expectDestWidth;
                targetHeight = System.Convert.ToInt32(Math.Round(expectDestWidth / srcHWRate, 0));
            }
            else
            {
                targetHeight = expectDestHeight;
                targetWidth = System.Convert.ToInt32(Math.Round(expectDestHeight * srcHWRate, 0));
            }
 
            Image bitmap = null;
            if (!padding)
            {
                bitmap = new Bitmap(targetWidth, targetHeight);
            }
            else
            {
                bitmap = new Bitmap(expectDestWidth, expectDestHeight);
            }
            Graphics g = Graphics.FromImage(bitmap);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
            foreach (PropertyItem i in exif)
            {
                if (i.Id == 40962)
                {
                    i.Value = BitConverter.GetBytes(targetWidth);
                }
                else if (i.Id == 40963)
                {
                    i.Value = BitConverter.GetBytes(targetHeight);
                }
                bitmap.SetPropertyItem(i);
            }
            g.Dispose();
            image.Dispose();
            image = bitmap;
        }
 
        private static string ReadConfig(String Section, String Key, String defaultValue)
        {
            if (File.Exists(configFile))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, String.Empty, temp, 1024, new FileInfo(configFile).FullName);
                if (!String.IsNullOrEmpty(temp.ToString()))
                {
                    return temp.ToString();
                }
                else
                {
                    return defaultValue;
                }
            }
            else
            {
                return defaultValue;
            }
        }
 
        public static void RotateImage(Image img)
        {
            PropertyItem[] exif = img.PropertyItems;
            byte orientation = 0;
            foreach (PropertyItem i in exif)
            {
                if (i.Id == 274)
                {
                    orientation = i.Value[0];
                    i.Value[0] = 1;
                    img.SetPropertyItem(i);
                }
            }
 
            switch (orientation)
            {
                case 2:
                    img.RotateFlip(RotateFlipType.RotateNoneFlipX);
                    break;
                case 3:
                    img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    break;
                case 4:
                    img.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    break;
                case 5:
                    img.RotateFlip(RotateFlipType.Rotate90FlipX);
                    break;
                case 6:
                    img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    break;
                case 7:
                    img.RotateFlip(RotateFlipType.Rotate270FlipX);
                    break;
                case 8:
                    img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    break;
                default:
                    break;
            }
            foreach (PropertyItem i in exif)
            {
                if (i.Id == 40962)
                {
                    i.Value = BitConverter.GetBytes(img.Width);
                }
                else if (i.Id == 40963)
                {
                    i.Value = BitConverter.GetBytes(img.Height);
                }
            }
        }
 
        private static ImageCodecInfo GetImageCodecInfoByExtension(String extension)
        {
            ImageCodecInfo[] list = ImageCodecInfo.GetImageEncoders();
            foreach(ImageCodecInfo i in list)
            {
                if (i.FilenameExtension.ToLower().Contains(extension.ToLower()))
                {
                    return i;
                }
            }
            return null;
        }
    }
}

配置文件名称:Config.ini,放在和程序同目录下,格式如下:
[General]
#工作目录
WorkingDir=.
#输出质量,1-100范围内的整数
Quality=80

[ResizeImage]
#是否启用
Enable=true
#新的宽值和高值
NewWidth=1024
NewHeight=768
#是否对超出原来比例的部分进行填充
Padding=false

#是否使用Exif中的旋转信息对图片进行旋转
[RotateImage]
Enable=true

1.保留exif信息的技巧是获取原始的Image.PropertyItems,对新图片添加即可.
2.关于Exif Orientation标志的定义 http://sylvana.net/jpegcrop/exif_orientation.html
3.变更jpeg输出质量的方法:
EncoderParameters para = new EncoderParameters();
para.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
//这里的quality是从1-100的long值,一开始想当然的以为1-100的值就用了byte,结果出错了.
最后调用Image.Save(String, ImageCodecInfo, EncoderParameters)来进行输出.
4.进行缩放/旋转后需要调整原始的exif信息,id查文档可知.列出一些
id=40962,width
id=40963,height
id=274,orientation type
对PropertyItem信息设置完了别忘了Image.SetPropertyItem(PropertyItem)添加到image中,我出一个很 傻的bug,就是在修改了orientation type=1之后没有SetPropertyItem,于是导致图片实际被旋转至正确角度了,但是用ACDSee打开后可以看到exif的旋转信息依旧是 原来的值.

使用C#进行图片转换格式,缩放,自动旋转,保留exif(转载)的更多相关文章

  1. 23.Quick QML-简单且好看的图片浏览器-支持多个图片浏览、缩放、旋转、滑轮切换图片

    之前我们已经学习了Image.Layout布局.MouseArea.Button.GroupBox.FileDialog等控件. 所以本章综合之前的每章的知识点,来做一个图片浏览器,使用的Qt版本为Q ...

  2. android 图片的平移,缩放和旋转

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools= ...

  3. ABBYY如何把图片转换成pdf格式

    在制作工作文件的时候,有时候会遇到需要进行文件格式转换的情况,比较常见的文件格式转换就包含了Office与pdf格式之间的转换.但除此之外,图片与pdf格式也是可以进行转换的,那么图片要怎么操作,才能 ...

  4. Android代码中动态设置图片的大小(自动缩放),位置

    项目中需要用到在代码中动态调整图片的位置和设置图片大小,能自动缩放图片,用ImageView控件,具体做法如下: 1.布局文件 <RelativeLayout xmlns:android=&qu ...

  5. jpg、png格式的图片转换成webp后颜色失真的问题

    今天简单的试用了一下 cweb.exe 将 jpg, png 格式的图片转换成 webp 格式. 我今天下载的是当前最新版:1.0.0 cwebp 3.jpg  -q 85 -o 3.webp 发现图 ...

  6. 如何将.jpg图片 转换成.eps 格式图片

    在使用latex写作论文的时候,需要插入一些图片,但是往往有些图片不是eps格式的.虽然网上有如何插入jpg格式的图片方法,但是经过我实验后发现都不太管用.最后找到一个比较靠谱的方法,使用latx本身 ...

  7. centos下 将(jgp、png)图片转换成webp格式

    由于项目要求需要将jpg.png类型的图片  转换成webp格式,最开始使用了php gd类库里 imagewebp 方法实现,结果发现转换成的webp格式文件会偶尔出现空白内容的情况.像创建了一个透 ...

  8. Android动画及图片的缩放和旋转

    Android动画有2种,一种是Tween Animation,另一种是Frame Animation,先说说Tween动画吧. Tween动画是对视图对象中的内容进行一系列简单的转换,比如位置的移动 ...

  9. xnconvert 图片转换工具

    xnconvert是一款简单高效的图片转换工具.xnconvert能够批量地进行图片格式转换,并具有一定的图片处理功能,可以增加水印.特效,支持放大缩小.旋转等. xnconvert功能介绍: 你可以 ...

随机推荐

  1. eclipse使用

    Eclipse 是一个开放源代码的.基于 Java 的可扩展开发平台. Eclipse 是 Java 的集成开发环境(IDE),当然 Eclipse 也可以作为其他开发语言的集成开发环境,如C,C++ ...

  2. 这些HTML、CSS知识点,面试和平时开发都需要 (转)

    http://www.cnblogs.com/w-wanglei/p/5414979.html No1.HTML 1.网页结构 网页结构一般都包含文档声明DOCTYPE,并且在head中的meta应该 ...

  3. 20145215《Java程序设计》实验一实验报告

    实验一 Java开发环境的熟悉 实验内容及步骤 使用JDK编译.运行简单的Java程序 命令行下程序开发: 在命令行下建立实验目录,进入该目录后创建exp1目录 敲入以下代码: package exp ...

  4. iOS端给unity发送消息,实现两者交互。

    上一篇我们简单说了一下unity发消息给iOS端.现在我们就来说一下iOS端给unity发送消息的简单使用. 首先iOS端做得事情其实很简单就一句话,直接上代码 /** * 第一个参数:是unity那 ...

  5. 我最优惠网系列(1)——HTML 解析类库HtmlAgilityPack

    0. 序言 在开发我最优惠网的过程中,遇到一些问题和技术点,写出来和大家分享,也是我自己对近期工作的整理和记录,预计会有解析HTML类库.本地缓存.链接跳转和C#中执行js代码技巧等方面. 1. Ht ...

  6. Android--自动搜索提示

    一. 效果图 在Google或者百度搜索的时候,在输入关键词都会出现自动搜索的提示内容,类似如下的效果,输入b 则出现包含b的相关词条 二. 布局代码 <?xml version="1 ...

  7. Javascript基础系列之(五)条件语句(if条件语句)

    if 是flash的常用语法之一,其格式如下 if(coditon) statement1 (else statement2) 其中,coditon可以是任何表达式,甚至不比是真正的布尔值,因为Jav ...

  8. 每天一个linux命令(45):route命令

    Linux系统的route 命令用于显示和操作IP路由表(show / manipulate the IP routing table).要实现两个不同的子网之间的通信,需 要一台连接两个网络的路由器 ...

  9. WCF学习(二)对控件简单了解以及4个文本控件的简介

    WPF基础控件 系统默认提供的基础控件: 文本控件介绍与用法 Label控件 label控件:一般用户描述性文字显示. 在Label控件使用时,一般给予用户提示.用法上没有什么很特殊的,label控件 ...

  10. Cas_Server端安装

        一.Cas Server版本:3.5.2 下载地址:http://download.csdn.net/detail/xiaohuzi1987/5262980   二.安装步骤: 1.解压cas ...