• C# 实现PPT、Word、Excel文件转为图片


    背景:因前有OfficeOnline的搭建,所以搭建完之后领导又提出要求啦,说:小xu,你……你把这文件的缩略图给我整出来吧。经过我历时久远的研究(这个问题跨了个年,随着2020疫情的发展,还过了两个月,放了个大长假)。但终,解决了,心头大患也。

     

    嗯~巴适~

    好啦,正戏正儿八经开始了!现在这里有两种解决方案,且听我细细说来~

     

    使用普通方法截取文件图片

    优点:① 所有文件都可以被截取;

    缺点:① 除PPT外截取的都是文件的图标;

          ② 截取图片比较模糊;

          ③ 截取图片有黑边;

    如下图:

    代码

        [Flags]
        public enum ThumbnailOptions
        {
            None = 0x00,
            BiggerSizeOk = 0x01,
            InMemoryOnly = 0x02,
            IconOnly = 0x04,
            ThumbnailOnly = 0x08,
            InCacheOnly = 0x10,
        }
    
        public class WindowsThumbnailProvider
        {
            private const string IShellItem2Guid = "7E9FB0D3-919F-4307-AB2E-9B1860310C93";
    
            [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
            internal static extern int SHCreateItemFromParsingName(
                [MarshalAs(UnmanagedType.LPWStr)] string path,
                // The following parameter is not used - binding context.
                IntPtr pbc,
                ref Guid riid,
                [MarshalAs(UnmanagedType.Interface)] out IShellItem shellItem);
    
            [DllImport("gdi32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            internal static extern bool DeleteObject(IntPtr hObject);
    
            [ComImport]
            [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
            [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
            internal interface IShellItem
            {
                void BindToHandler(IntPtr pbc,
                    [MarshalAs(UnmanagedType.LPStruct)]Guid bhid,
                    [MarshalAs(UnmanagedType.LPStruct)]Guid riid,
                    out IntPtr ppv);
    
                void GetParent(out IShellItem ppsi);
                void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName);
                void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
                void Compare(IShellItem psi, uint hint, out int piOrder);
            };
    
            internal enum SIGDN : uint
            {
                NORMALDISPLAY = 0,
                PARENTRELATIVEPARSING = 0x80018001,
                PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
                DESKTOPABSOLUTEPARSING = 0x80028000,
                PARENTRELATIVEEDITING = 0x80031001,
                DESKTOPABSOLUTEEDITING = 0x8004c000,
                FILESYSPATH = 0x80058000,
                URL = 0x80068000
            }
    
            internal enum HResult
            {
                Ok = 0x0000,
                False = 0x0001,
                InvalidArguments = unchecked((int)0x80070057),
                OutOfMemory = unchecked((int)0x8007000E),
                NoInterface = unchecked((int)0x80004002),
                Fail = unchecked((int)0x80004005),
                ElementNotFound = unchecked((int)0x80070490),
                TypeElementNotFound = unchecked((int)0x8002802B),
                NoObject = unchecked((int)0x800401E5),
                Win32ErrorCanceled = 1223,
                Canceled = unchecked((int)0x800704C7),
                ResourceInUse = unchecked((int)0x800700AA),
                AccessDenied = unchecked((int)0x80030005)
            }
    
            [ComImportAttribute()]
            [GuidAttribute("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
            [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
            internal interface IShellItemImageFactory
            {
                [PreserveSig]
                HResult GetImage(
                [In, MarshalAs(UnmanagedType.Struct)] NativeSize size,
                [In] ThumbnailOptions flags,
                [Out] out IntPtr phbm);
            }
    
            [StructLayout(LayoutKind.Sequential)]
            internal struct NativeSize
            {
                private int width;
                private int height;
    
                public int Width { set { width = value; } }
                public int Height { set { height = value; } }
            };
    
            [StructLayout(LayoutKind.Sequential)]
            public struct RGBQUAD
            {
                public byte rgbBlue;
                public byte rgbGreen;
                public byte rgbRed;
                public byte rgbReserved;
            }
    
            /// <summary>
            /// 获取缩略图
            /// </summary>
            /// <param name="filePath">文件所在绝对路径</param>
            /// <param name="width">图片宽</param>
            /// <param name="height">图片高</param>
            /// <param name="options"></param>
            public static void GetThumbnail(string filePath, string imgFullPath, int width, int height, ThumbnailOptions options)
            {
                IntPtr hBitmap = GetHBitmap(Path.GetFullPath(filePath), width, height, options);
                try
                {
                    SaveBitmap(hBitmap, imgFullPath);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    DeleteObject(hBitmap);
                }
            }
    
            /// <summary>
            /// 将Bitmap转换成图片,并返回缩略图相对路径
            /// </summary>
            /// <param name="hBitmap"></param>
            /// <param name="fileName">文件名称</param>
            /// <returns></returns>
            public static void SaveBitmap(IntPtr hBitmap, string imgFullPath)
            {
                try
                {
                    Bitmap bmp = GetBitmapFromHBitmap(hBitmap);
                    bmp.Save(imgFullPath, ImageFormat.Jpeg);
                }
                catch (IOException ex)
                {
                    throw ex;
                }
            }
    
            /// <summary>
            /// 将HBitmap转换成Bitmap
            /// </summary>
            /// <param name="nativeHBitmap"></param>
            /// <returns></returns>
            public static Bitmap GetBitmapFromHBitmap(IntPtr nativeHBitmap)
            {
                Bitmap bmp = Bitmap.FromHbitmap(nativeHBitmap);
    
                if (Bitmap.GetPixelFormatSize(bmp.PixelFormat) < 32)
                    return bmp;
    
                return CreateAlphaBitmap(bmp, PixelFormat.Format32bppArgb);
            }
    
            /// <summary>
            /// 创建图片
            /// </summary>
            /// <param name="srcBitmap"></param>
            /// <param name="targetPixelFormat"></param>
            /// <returns></returns>
            public static Bitmap CreateAlphaBitmap(Bitmap srcBitmap, PixelFormat targetPixelFormat)
            {
                Bitmap result = new Bitmap(srcBitmap.Width, srcBitmap.Height, targetPixelFormat);
    
                Rectangle bmpBounds = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height);
    
                BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat);
    
                bool isAlplaBitmap = false;
    
                try
                {
                    for (int y = 0; y <= srcData.Height - 1; y++)
                    {
                        for (int x = 0; x <= srcData.Width - 1; x++)
                        {
                            Color pixelColor = Color.FromArgb(
                                Marshal.ReadInt32(srcData.Scan0, (srcData.Stride * y) + (4 * x)));
    
                            if (pixelColor.A > 0 & pixelColor.A < 255)
                            {
                                isAlplaBitmap = true;
                            }
    
                            result.SetPixel(x, y, pixelColor);
                        }
                    }
                }
                finally
                {
                    srcBitmap.UnlockBits(srcData);
                }
    
                if (isAlplaBitmap)
                {
                    return result;
                }
                else
                {
                    return srcBitmap;
                }
            }
    
            /// <summary>
            /// GetHBitmap
            /// </summary>
            /// <param name="fileName"></param>
            /// <param name="width"></param>
            /// <param name="height"></param>
            /// <param name="options"></param>
            /// <returns></returns>
            private static IntPtr GetHBitmap(string fileName, int width, int height, ThumbnailOptions options)
            {
                IShellItem nativeShellItem;
                Guid shellItem2Guid = new Guid(IShellItem2Guid);
                int retCode = SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem);
    
                if (retCode != 0)
                    throw Marshal.GetExceptionForHR(retCode);
    
                NativeSize nativeSize = new NativeSize();
                nativeSize.Width = width;
                nativeSize.Height = height;
    
                IntPtr hBitmap;
                HResult hr = ((IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap);
    
                Marshal.ReleaseComObject(nativeShellItem);
    
                if (hr == HResult.Ok) return hBitmap;
    
                throw Marshal.GetExceptionForHR((int)hr);
            }
        }

    如何使用

    //string filePath = "E:\File\我就是很开心.txt";//文件所在位置
    //string filePath = "E:\File\我有点不开心.xlsx";//文件所在位置
    //string filePath = "E:\File\你看起来很好吃.docx";//文件所在位置
    string filePath = "E:\File\项目测试使用文件.pptx";//文件所在位置
    
    //自定义图片路径
    string imgName = Path.GetFileName(filePath).Split('.')[0];
    string direcName = Path.GetDirectoryName(filePath);
    string imgFullPath = $"{direcName}\{imgName}.jpg";//重组,获取图片存放位置
    
    int pic_size = 1000;
    WindowsThumbnailProvider.GetThumbnail(filePath, imgFullPath, pic_size, pic_size, ThumbnailOptions.None);
      

    使用Aspose截取文件图片

    注意:Aspose自身可以截取所有文件,但我这里设置的目前只能截取rar、ppt、excel、word这四种格式,其他格式就会报错。你如果需要更多的文件格式截图,就再进行研究就阔以。该dll中的方法可以截取多张图片,不一定就是文件首页。笔芯~

     

     

     

    去水印

    如果没有破解码,直接使用aspose,打印出来的照片就会有水印。如下图:

     所以你需要在App.config中,添加一个节点,如下:

    注:web项目对应的是web.config;控制台项目对应的是app.config,不过下面节点在两种文件里面都通用)

    <add key="AsposeKey" value="PExpY2Vuc2U+DQogIDxEYXRhPg0KICAgIDxMaWNlbnNlZFRvPkFzcG9zZSBTY290bGFuZCBUZWFtPC9MaWNlbnNlZFRvPg0KICAgIDxFbWFpbFRvPmJpbGx5Lmx1bmRpZUBhc3Bvc2UuY29tPC9FbWFpbFRvPg0KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlVHlwZT4NCiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1pdGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+DQogICAgPE9yZGVySUQ+MTQwNDA4MDUyMzI0PC9PcmRlcklEPg0KICAgIDxVc2VySUQ+OTQyMzY8L1VzZXJJRD4NCiAgICA8T0VNPlRoaXMgaXMgYSByZWRpc3RyaWJ1dGFibGUgbGljZW5zZTwvT0VNPg0KICAgIDxQcm9kdWN0cz4NCiAgICAgIDxQcm9kdWN0PkFzcG9zZS5Ub3RhbCBmb3IgLk5FVDwvUHJvZHVjdD4NCiAgICA8L1Byb2R1Y3RzPg0KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4NCiAgICA8U2VyaWFsTnVtYmVyPjlhNTk1NDdjLTQxZjAtNDI4Yi1iYTcyLTdjNDM2OGYxNTFkNzwvU2VyaWFsTnVtYmVyPg0KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+MjAxNTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4NCiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnNlVmVyc2lvbj4NCiAgICA8TGljZW5zZUluc3RydWN0aW9ucz5odHRwOi8vd3d3LmFzcG9zZS5jb20vY29ycG9yYXRlL3B1cmNoYXNlL2xpY2Vuc2UtaW5zdHJ1Y3Rpb25zLmFzcHg8L0xpY2Vuc2VJbnN0cnVjdGlvbnM+DQogIDwvRGF0YT4NCiAgPFNpZ25hdHVyZT5GTzNQSHNibGdEdDhGNTlzTVQxbDFhbXlpOXFrMlY2RThkUWtJUDdMZFRKU3hEaWJORUZ1MXpPaW5RYnFGZkt2L3J1dHR2Y3hvUk9rYzF0VWUwRHRPNmNQMVpmNkowVmVtZ1NZOGkvTFpFQ1RHc3pScUpWUVJaME1vVm5CaHVQQUprNWVsaTdmaFZjRjhoV2QzRTRYUTNMemZtSkN1YWoyTkV0ZVJpNUhyZmc9PC9TaWduYXR1cmU+DQo8L0xpY2Vuc2U+" />

    注:使用此码是对aspose各个dll的版本有要求的,需要在2015年12月30日之前的版本,才可以使用。所以你可以去nuget官网(https://www.nuget.org/packages?q=Aspose.Words)查找相应日期对应的版本。如果你懒,你懒,懒……,不用担心,我给你找好了。

    名称

    版本

    日期

    Aspose.Words

    15.12.0

    2015/12/26

    Aspose.Excel

    8.6.3

    2015/12/23

    Aspose.Slides

    15.10.0.0

    2015/12/10

    Aspose.Pdf

    11.1.1.0

    2015/12/30

    代码

    详见下面的链接中的解决方案吧,不想复制了,实在是太多啦。

    如何使用

    //string filePath = "E:\File\我就是很开心.txt";//文件所在位置
    //string filePath = "E:\File\我有点不开心.xlsx";//文件所在位置
    //string filePath = "E:\File\你看起来很好吃.docx";//文件所在位置
    string filePath = "E:\File\项目测试使用文件.pptx";//文件所在位置
    
    //自定义图片路径
    string imgName = Path.GetFileName(filePath).Split('.')[0];
    string direcName = Path.GetDirectoryName(filePath);
    string imgFullPath = $"{direcName}\{imgName}.jpg";//重组,获取图片存放位置
    
    string extendName = Path.GetExtension(filePath);
    
    //这里运用的是简单工厂模式
    ImageConverterFactory factory = new ImageConverterFactory();
    var imageConvert = factory.CreateImageConverter(extendName);
    imageConvert.ConvertToImage(filePath, imgFullPath);

    代码下载

    两种方法在同一个解决方案里

     百度云盘:链接:https://pan.baidu.com/s/10edFyh1W_6zYjcTVmXFGEQ  提取码:1l4t 

    感谢大佬的热心分享:https://www.cnblogs.com/zhuweisky/p/4774803.html

    有什么不明白的可随时评论,我看到就会回复哦~

    看到这了,小主大人,手留余香,点个赞白~

  • 相关阅读:
    eclipse—Maven项目打包成exe
    netty+proto使用简要记录
    使用Kotlin开发第一个Android应用
    Android——调用高德地图API前期准备
    AndroidStudio更改包名
    Android Studio —— java.lang.VerifyError: Verifier rejected class 问题解决
    Android studio Error occurred during initialization of VM 问题解决
    AndroidStudio下使用 RecyclerView xml文件不显示预览条目并报错类似:NoClassDefFoundError 问题解决
    Genymotion模拟器安装问题及解决(启动失败,模拟器不能联网)
    华为荣耀畅玩5C NEM-UL10 ROOT那些事儿(亲测成功)
  • 原文地址:https://www.cnblogs.com/pukua/p/12965752.html
Copyright © 2020-2023  润新知