传入文件路径,返回临时文件中缩略图的路径,jpg,pdf,office,rar都行

  1. string path = ThumbnailHelper.GetInstance().GetJPGThumbnail("D:\\1.jpg");

ThumbnailHelper

  1. public class Win32Helper
  2. {
  3. internal const string IShellItem2Guid = "7E9FB0D3-919F-4307-AB2E-9B1860310C93";
  4.  
  5. [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  6. internal static extern int SHCreateItemFromParsingName(
  7. [MarshalAs(UnmanagedType.LPWStr)] string path,
  8. // The following parameter is not used - binding context.
  9. IntPtr pbc,
  10. ref Guid riid,
  11. [MarshalAs(UnmanagedType.Interface)] out IShellItem shellItem);
  12.  
  13. [DllImport("gdi32.dll")]
  14. [return: MarshalAs(UnmanagedType.Bool)]
  15. internal static extern bool DeleteObject(IntPtr hObject);
  16.  
  17. [ComImport]
  18. [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  19. [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
  20. internal interface IShellItem
  21. {
  22. void BindToHandler(IntPtr pbc,
  23. [MarshalAs(UnmanagedType.LPStruct)]Guid bhid,
  24. [MarshalAs(UnmanagedType.LPStruct)]Guid riid,
  25. out IntPtr ppv);
  26.  
  27. void GetParent(out IShellItem ppsi);
  28. void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName);
  29. void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
  30. void Compare(IShellItem psi, uint hint, out int piOrder);
  31. };
  32. public enum ThumbnailOptions : uint
  33. {
  34. None = ,
  35. ReturnOnlyIfCached = ,
  36. ResizeThumbnail = ,
  37. UseCurrentScale =
  38. }
  39. internal enum SIGDN : uint
  40. {
  41. NORMALDISPLAY = ,
  42. PARENTRELATIVEPARSING = 0x80018001,
  43. PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
  44. DESKTOPABSOLUTEPARSING = 0x80028000,
  45. PARENTRELATIVEEDITING = 0x80031001,
  46. DESKTOPABSOLUTEEDITING = 0x8004c000,
  47. FILESYSPATH = 0x80058000,
  48. URL = 0x80068000
  49. }
  50.  
  51. internal enum HResult
  52. {
  53. Ok = 0x0000,
  54. False = 0x0001,
  55. InvalidArguments = unchecked((int)0x80070057),
  56. OutOfMemory = unchecked((int)0x8007000E),
  57. NoInterface = unchecked((int)0x80004002),
  58. Fail = unchecked((int)0x80004005),
  59. ElementNotFound = unchecked((int)0x80070490),
  60. TypeElementNotFound = unchecked((int)0x8002802B),
  61. NoObject = unchecked((int)0x800401E5),
  62. Win32ErrorCanceled = ,
  63. Canceled = unchecked((int)0x800704C7),
  64. ResourceInUse = unchecked((int)0x800700AA),
  65. AccessDenied = unchecked((int)0x80030005)
  66. }
  67.  
  68. [ComImportAttribute()]
  69. [GuidAttribute("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
  70. [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  71. internal interface IShellItemImageFactory
  72. {
  73. [PreserveSig]
  74. HResult GetImage(
  75. [In, MarshalAs(UnmanagedType.Struct)] NativeSize size,
  76. [In] ThumbnailOptions flags,
  77. [Out] out IntPtr phbm);
  78. }
  79.  
  80. [StructLayout(LayoutKind.Sequential)]
  81. internal struct NativeSize
  82. {
  83. private int width;
  84. private int height;
  85.  
  86. public int Width { set { width = value; } }
  87. public int Height { set { height = value; } }
  88. };
  89.  
  90. [StructLayout(LayoutKind.Sequential)]
  91. public struct RGBQUAD
  92. {
  93. public byte rgbBlue;
  94. public byte rgbGreen;
  95. public byte rgbRed;
  96. public byte rgbReserved;
  97. }
  98. }
  99. public class ThumbnailHelper
  100. {
  101. #region instance
  102. private static object ooo = new object();
  103. private static ThumbnailHelper _ThumbnailHelper;
  104. private ThumbnailHelper() { }
  105. public static ThumbnailHelper GetInstance()
  106. {
  107. if (_ThumbnailHelper == null)
  108. {
  109. lock (ooo)
  110. {
  111. if (_ThumbnailHelper == null)
  112. _ThumbnailHelper = new ThumbnailHelper();
  113. }
  114. }
  115. return _ThumbnailHelper;
  116. }
  117. #endregion
  118.  
  119. #region public methods
  120.  
  121. public string GetJPGThumbnail(string filename, int width = , int height = , Win32Helper.ThumbnailOptions options = Win32Helper.ThumbnailOptions.None)
  122. {
  123. if (!File.Exists(filename))
  124. return string.Empty;
  125. Bitmap bit = GetBitmapThumbnail(filename, width, height, options);
  126. if (bit == null)
  127. return string.Empty;
  128. return GetThumbnailFilePath(bit);
  129. }
  130. #endregion
  131.  
  132. #region private methods
  133. private Bitmap GetBitmapThumbnail(string fileName, int width = , int height = , Win32Helper.ThumbnailOptions options = Win32Helper.ThumbnailOptions.None)
  134. {
  135. IntPtr hBitmap = GetHBitmap(System.IO.Path.GetFullPath(fileName), width, height, options);
  136.  
  137. try
  138. {
  139. Bitmap bmp = Bitmap.FromHbitmap(hBitmap);
  140.  
  141. if (Bitmap.GetPixelFormatSize(bmp.PixelFormat) < )
  142. return bmp;
  143.  
  144. return CreateAlphaBitmap(bmp, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  145. }
  146. finally
  147. {
  148. // delete HBitmap to avoid memory leaks
  149. Win32Helper.DeleteObject(hBitmap);
  150. }
  151. }
  152. private Bitmap CreateAlphaBitmap(Bitmap srcBitmap, System.Drawing.Imaging.PixelFormat targetPixelFormat)
  153. {
  154. Bitmap result = new Bitmap(srcBitmap.Width, srcBitmap.Height, targetPixelFormat);
  155.  
  156. System.Drawing.Rectangle bmpBounds = new System.Drawing.Rectangle(, , srcBitmap.Width, srcBitmap.Height);
  157.  
  158. BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat);
  159.  
  160. bool isAlplaBitmap = false;
  161.  
  162. try
  163. {
  164. for (int y = ; y <= srcData.Height - ; y++)
  165. {
  166. for (int x = ; x <= srcData.Width - ; x++)
  167. {
  168. System.Drawing.Color pixelColor = System.Drawing.Color.FromArgb(
  169. Marshal.ReadInt32(srcData.Scan0, (srcData.Stride * y) + ( * x)));
  170.  
  171. if (pixelColor.A > & pixelColor.A < )
  172. {
  173. isAlplaBitmap = true;
  174. }
  175.  
  176. result.SetPixel(x, y, pixelColor);
  177. }
  178. }
  179. }
  180. finally
  181. {
  182. srcBitmap.UnlockBits(srcData);
  183. }
  184.  
  185. if (isAlplaBitmap)
  186. {
  187. return result;
  188. }
  189. else
  190. {
  191. return srcBitmap;
  192. }
  193. }
  194.  
  195. private IntPtr GetHBitmap(string fileName, int width, int height, Win32Helper.ThumbnailOptions options)
  196. {
  197. Win32Helper.IShellItem nativeShellItem;
  198. Guid shellItem2Guid = new Guid(Win32Helper.IShellItem2Guid);
  199. int retCode = Win32Helper.SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem);
  200.  
  201. if (retCode != )
  202. throw Marshal.GetExceptionForHR(retCode);
  203.  
  204. Win32Helper.NativeSize nativeSize = new Win32Helper.NativeSize();
  205. nativeSize.Width = width;
  206. nativeSize.Height = height;
  207.  
  208. IntPtr hBitmap;
  209. Win32Helper.HResult hr = ((Win32Helper.IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap);
  210.  
  211. Marshal.ReleaseComObject(nativeShellItem);
  212.  
  213. if (hr == Win32Helper.HResult.Ok) return hBitmap;
  214.  
  215. throw Marshal.GetExceptionForHR((int)hr);
  216. }
  217.  
  218. /// <summary>
  219. /// 获取临时文件
  220. /// </summary>
  221. /// <returns></returns>
  222. private FileStream GetTemporaryFilePath(ref string filePath)
  223. {
  224. string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName());
  225. var index = path.IndexOf('.');
  226. string temp = path.Substring(, index) + ".li";
  227.  
  228. var fileStream = File.Create(temp);
  229. filePath = temp;
  230. return fileStream;
  231. }
  232. /// <summary>
  233. /// 参数
  234. /// </summary>
  235. /// <param name="mimeType"></param>
  236. /// <returns></returns>
  237. private ImageCodecInfo GetEncoderInfo(String mimeType)
  238. {
  239. int j;
  240. ImageCodecInfo[] encoders;
  241. encoders = ImageCodecInfo.GetImageEncoders();
  242. for (j = ; j < encoders.Length; ++j)
  243. {
  244. if (encoders[j].MimeType == mimeType)
  245. return encoders[j];
  246. }
  247. return null;
  248. }
  249. const int ExpectHeight = ;
  250. const int ExpectWidth = ;
  251. /// <summary>
  252. /// 得到图片缩放后的大小 图片大小过小不考虑缩放了
  253. /// </summary>
  254. /// <param name="originSize">原始大小</param>
  255. /// <returns>改变后大小</returns>
  256. private System.Drawing.Size ScalePhoto(System.Drawing.Size originSize, bool can)
  257. {
  258. if (originSize.Height * originSize.Width < ExpectHeight * ExpectWidth)
  259. {
  260. can = false;
  261. }
  262. if (can)
  263. {
  264. bool isportrait = false;
  265.  
  266. if (originSize.Width <= originSize.Height)
  267. {
  268. isportrait = true;
  269. }
  270.  
  271. if (isportrait)
  272. {
  273. double ratio = (double)ExpectHeight / (double)originSize.Height;
  274. return new System.Drawing.Size((int)(originSize.Width * ratio), (int)(originSize.Height * ratio));
  275. }
  276. else
  277. {
  278. double ratio = (double)ExpectWidth / (double)originSize.Width;
  279. return new System.Drawing.Size((int)(originSize.Width * ratio), (int)(originSize.Height * ratio));
  280. }
  281. }
  282. else
  283. {
  284. return new System.Drawing.Size(originSize.Width, originSize.Height);
  285. }
  286.  
  287. }
  288. /// <summary>
  289. /// 获取缩略图文件
  290. /// </summary>
  291. /// <param name="BitmapIcon">缩略图</param>
  292. /// <returns>路径</returns>
  293. private string GetThumbnailFilePath(Bitmap bitmap)
  294. {
  295. var filePath = "";
  296. var fileStream = GetTemporaryFilePath(ref filePath);
  297.  
  298. //bitmap.Save(filePath);
  299.  
  300. ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg"); //image code info 图形图像解码压缩
  301. System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
  302. EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
  303. EncoderParameters encoderParameters = new EncoderParameters { Param = new EncoderParameter[] { myEncoderParameter } };
  304. var sizeScaled = ScalePhoto(bitmap.Size, true);
  305. //去黑色背景
  306. var finalBitmap = ClearBlackBackground(bitmap);
  307. finalBitmap.Save(fileStream, myImageCodecInfo, encoderParameters);
  308. fileStream.Dispose();
  309. return filePath;
  310. }
  311.  
  312. private Bitmap ClearBlackBackground(Bitmap originBitmap)
  313. {
  314. using (var tempBitmap = new Bitmap(originBitmap.Width, originBitmap.Height))
  315. {
  316. tempBitmap.SetResolution(originBitmap.HorizontalResolution, originBitmap.VerticalResolution);
  317.  
  318. using (var g = Graphics.FromImage(tempBitmap))
  319. {
  320. g.Clear(System.Drawing.Color.White);
  321. g.DrawImageUnscaled(originBitmap, , );
  322. }
  323. return new Bitmap(tempBitmap);
  324. }
  325. }
  326.  
  327. #endregion
  328. }

C#选择文件返回缩略图的更多相关文章

  1. 使用input:file控件在微信内置浏览器上传文件返回未显示选择的文件

    使用input:file控件在微信内置浏览器上传文件返回未显示选择的文件 原来的写法: <input type="file" accept="image/x-png ...

  2. 获取文件的缩略图Thumbnail和通过 AQS - Advanced Query Syntax 搜索本地文件

    演示如何获取文件的缩略图 FileSystem/ThumbnailAccess.xaml <Page x:Class="XamlDemo.FileSystem.ThumbnailAcc ...

  3. android 中获取视频文件的缩略图(非原创)

    在android中获取视频文件的缩略图有三种方法: 1.从媒体库中查询 2. android 2.2以后使用ThumbnailUtils类获取 3.调用jni文件,实现MediaMetadataRet ...

  4. VC中打开对话框选择文件和文件夹

    1.选择文件               CFileDialogdlg(true, NULL, NULL, NULL, "所有文件 | *.*", this);           ...

  5. 琐碎--选择文件夹(路径)+生产txt格式的log+数据库操作方式

    记录日常工作常用到的一些方法: 1 选择文件操作,并将文件的路径记录下来: OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = f ...

  6. Java按位置解析文本文件(使用Swing选择文件)

    工作中遇到这样的一个需求,按位置解析一些文本文件,它们由头部.详情.尾部组成,并且每一行的长度可能不一样,每一行代表的意思也可能不一样,但是每一行各个位置代表的含义已经确定了. 例如有下面这样一段文本 ...

  7. Jquery调用从ashx文件返回的jsonp格式的数据处理实例

    开发环境:vs2010+jquery-1.4.min.js 解决问题:网上代码比较少,好多调试不通,返回数据不用json而用jsonp主要考虑解决跨域问题 开发步骤:打开VS2010,新建一web站点 ...

  8. EXCEL VBA 选择文件对话框

    Sub XXX() Dim arr() arr = Application.GetOpenFilename("所有支付文件 (*.xls;*.xlsx;*.csv),*.xls;*.xlsx ...

  9. windows API实现用户选择文件路径的对话框

    在编写应用程序时,有时需要用户选择某个文件,以供应用程序使用,比如在某些管理程序中需要打开某一个进程,这个时候需要弹出一个对话框来将文件路径以树形图的形式表示出来,以图形化的方式供用户选择文件路径,而 ...

随机推荐

  1. tensorflow的变量作用域

    一.由来 深度学习中需要使用大量的变量集,以往写代码我们只需要做全局限量就可以了,但在tensorflow中,这样做既不方便管理变量集,有不便于封装,因此tensorflow提供了一种变量管理方法:变 ...

  2. 一个优雅的图片裁剪插件vue-cropper

    github:  https://github.com/xyxiao001/vue-cropper

  3. 8.Python标识符命名规范

    简单地理解,标识符就是一个名字,就好像我们每个人都有属于自己的名字,它的主要作用就是作为变量.函数.类.模块以及其他对象的名称. Python 中标识符的命名不是随意的,而是要遵守一定的命令规则,比如 ...

  4. hibernate一对一单项关联映射

    一.主键关联 1.两个实体对象的主键一样,以表明它们之间的一一对应关系: 2.不需要多余的外键字段来维护关系,仅通过主键来关联,即Person的主键要依赖IdCard的主键,他们共用一个主键值. Pe ...

  5. @清晰掉 qsort()

    qsort函数描述: http://www.cnblogs.com/sooner/archive/2012/04/18/2455011.html qsort()函数实现: /*** *qsort.c ...

  6. SpringMvc中ModelAndView模型的应用

    /** * 目标方法的返回值可以是 ModelAndView 类型. * 其中可以包含视图和模型信息 * SpringMVC 会把 ModelAndView 的 model 中数据放入到 reques ...

  7. nginx请求转发配置

    以下为无ssl证书配置的请求转发 server { listen ; server_name api.****.com; #以下为指定请求域名匹配到某一个端口 #location ~* /union ...

  8. Openstack_单元测试工具 tox

    目录 目录 扩展阅读 Openstack 的单元测试工具 单元测试工具使用流程 tox toxini 参考文章 扩展阅读 Python Mock的入门 Openstack 的单元测试工具 unitte ...

  9. Gradle之Gradle 源码分析(四)

    Gradle 的启动 constructTaskGraph runTasks finishBuild gradle 脚本如何编译和执 插件调用流程 一.Gradle 的启动 1.1 整体实现图 1.2 ...

  10. linux防火墙iptables简单介绍

    --append  -A chain        Append to chain  --delete  -D chain        Delete matching rule from chain ...