Aspose组件下载连接:http://pan.baidu.com/s/1slG2SdJ
1.所有的转换图片都要调用Aspose组件,在执行线程之前要先加上 LicenseHelper.ModifyInMemory.ActivateMemoryPatching();
//进入线程执行转换图片的方法
UploaderCalculators.Add(filePath, fileType, Id.ToString(), UId.ToString(), Server.MapPath(imgUrl), imgUrl);
类名:UploaderCalculators
public class UploaderCalculators { //存入任务的队列 private static Queue<string> _urlQueue; private static Queue<string> _typeQueue; private static Queue<string> _KcidQueue; private static Queue<string> _UserIdQueue; private static Queue<string> _imgUrlQueue; private static Queue<string> _imgQueue; private static ManualResetEvent _hasNew; private static bool isFirst = true; static UploaderCalculators() { _urlQueue = new Queue<string>(); _typeQueue = new Queue<string>(); _KcidQueue = new Queue<string>(); _UserIdQueue = new Queue<string>(); _imgUrlQueue = new Queue<string>(); _imgQueue = new Queue<string>(); _hasNew = new ManualResetEvent(false); //这里创建一个线程,使其执行Process方法。 Thread thread = new Thread(Process); //设置当前线程为后台线程。 thread.IsBackground = true; //开启线程 thread.Start(); } private static void Process() { while (true) { //等待接受信号,阻塞线程 _hasNew.WaitOne(); //接收信号,重置 信号器,信号关闭。 _hasNew.Reset(); threadStart(); } } private static void threadStart() { CommonBll comm = new CommonBll(); BaseController Base = new BaseController(); while (true) { if (_urlQueue.Count > 0 && _typeQueue.Count > 0 && _KcidQueue.Count > 0 && _UserIdQueue.Count > 0) { try { //文件路径 string Url = _urlQueue.Count > 0 ? _urlQueue.Dequeue() : "";//从队列的开始出返回一个对象; //文件后缀名 string fileType = _typeQueue.Count > 0 ? _typeQueue.Dequeue() : "";//从队列的开始出返回一个对象;//转换图片后的存入路径 string imgUrl = _imgUrlQueue.Count > 0 ? _imgUrlQueue.Dequeue() : "";//从队列的开始出返回一个对象; // string img = _imgQueue.Count > 0 ? _imgQueue.Dequeue() : "";//从队列的开始出返回一个对象; PictureConversion pc = new PictureConversion(); string imgName = string.Empty; if (fileType == "docx" || fileType == "doc") { imgName = pc.ConvertToImage_Words(Url, imgUrl, 0, 0, null, 145, img); } if (fileType == "pptx" || fileType == "xlsx" || fileType == "xls" || fileType == "excel" || fileType == "excelx" || fileType == "ppt") { imgName = pc.ConvertToImage_PPT(Url, imgUrl, 0, 0, 145, fileType, img); } if (fileType == "pdf") { imgName = pc.ConvertToImage_PDF(Url, imgUrl, 0, 0, 145, img); } if (imgName != null && imgName != "") { // } } catch (Exception e) { Console.Write(e); } } } } public static void Add(string Url, string Type, string KcId, string UserId, string imgUrl, string img) { _urlQueue.Enqueue(Url); _typeQueue.Enqueue(Type); _KcidQueue.Enqueue(KcId); _UserIdQueue.Enqueue(UserId); _imgUrlQueue.Enqueue(imgUrl); _imgQueue.Enqueue(img); if (isFirst) { isFirst = false; _hasNew.Set(); } } }
类名:PictureConversion
public class PictureConversion
{
/// <summary>
/// 将Word文档转换为图片的方法
/// </summary>
/// <param name="wordInputPath">Word文件路径</param>
/// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param>
/// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public string ConvertToImage_Words(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution, string imgUrl)
{
try
{
Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
if (doc == null)
{
throw new Exception("Word文件无效或者Word文件被加密!");
}
if (imageOutputDirPath.Trim().Length == 0)
{
imageOutputDirPath = Path.GetDirectoryName(wordInputPath);
}
if (!Directory.Exists(imageOutputDirPath))
{
Directory.CreateDirectory(imageOutputDirPath);
}
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum > doc.PageCount || endPageNum <= 0)
{
endPageNum = doc.PageCount;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
}
if (imageFormat == null)
{
imageFormat = ImageFormat.Png;
}
if (resolution <= 0)
{
resolution = 128;
}
string imageName = Path.GetFileNameWithoutExtension(wordInputPath);
Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png);
imageSaveOptions.Resolution = resolution;
string imgName = string.Empty;
for (int i = startPageNum; i <= endPageNum; i++)
{
MemoryStream stream = new MemoryStream();
imageSaveOptions.PageIndex = i - 1;
string imgPath = Path.Combine(imageOutputDirPath, imageName) + "_" + i.ToString("000") + "." + imageFormat.ToString();
imgName += imgUrl + "/" + imageName + "_" + i.ToString("000") + "." + imageFormat.ToString() + "|";
doc.Save(stream, imageSaveOptions);
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
System.Drawing.Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f);
bm.Save(imgPath, imageFormat);
img.Dispose();
stream.Dispose();
bm.Dispose();
System.Threading.Thread.Sleep(200);
}
if (!string.IsNullOrEmpty(imgName))
{
imgName = imgName.Substring(0, imgName.Length - 1);
}
return imgName;
}
catch (Exception ex)
{
ErrorHandler.WriteError(ex);
throw;
}
}
/// <summary>
/// 将PPT、Excel、Txt文档转换为图片的方法
/// </summary>
/// <param name="originFilePath">ppt文件路径</param>
/// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param>
/// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public string ConvertToImage_PPT(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution, string Format, string imgUrl)
{
try
{
//先将文件转换为pdf临时文件
string tmpPdfPath = originFilePath.Replace(Format, "") + "pdf";
if (Format == ".xls" || Format == ".xlsx" || Format == ".txt")
{
Workbook wb = new Workbook(originFilePath);
wb.Save(tmpPdfPath, SaveFormat.Pdf);
}
else
{
Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(originFilePath);
if (doc == null)
{
throw new Exception("ppt文件无效或者ppt文件被加密!");
}
if (imageOutputDirPath.Trim().Length == 0)
{
imageOutputDirPath = Path.GetDirectoryName(originFilePath);
}
if (!Directory.Exists(imageOutputDirPath))
{
Directory.CreateDirectory(imageOutputDirPath);
}
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum > doc.Slides.Count || endPageNum <= 0)
{
endPageNum = doc.Slides.Count;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
}
if (resolution <= 0)
{
resolution = 128;
}
if (doc != null)
{
doc.Save(tmpPdfPath, Aspose.Slides.Export.SaveFormat.Pdf);
}
}
//再将pdf转换为图片
string imgName = ConvertToImage_PDF(tmpPdfPath, imageOutputDirPath, startPageNum, endPageNum, resolution, imgUrl);
//删除pdf临时文件
File.Delete(tmpPdfPath);
return imgName;
}
catch (Exception ex)
{
ErrorHandler.WriteError(ex);
return "888";
throw;
}
}
/// <summary>
/// 将pdf文档转换为图片的方法
/// </summary>
/// <param name="originFilePath">pdf文件路径</param>
/// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param>
/// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public string ConvertToImage_PDF(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution, string imgUrl)
{
try
{
Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath);
if (doc == null)
{
throw new Exception("pdf文件无效或者pdf文件被加密!");
}
if (imageOutputDirPath.Trim().Length == 0)
{
imageOutputDirPath = Path.GetDirectoryName(originFilePath);
}
if (!Directory.Exists(imageOutputDirPath))
{
Directory.CreateDirectory(imageOutputDirPath);
}
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum > doc.Pages.Count || endPageNum <= 0)
{
endPageNum = doc.Pages.Count;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
}
if (resolution <= 0)
{
resolution = 128;
}
string imageNamePrefix = Path.GetFileNameWithoutExtension(originFilePath);
string imgName = string.Empty;
for (int i = startPageNum; i <= endPageNum; i++)
{
MemoryStream stream = new MemoryStream();
string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + ".jpg";
imgName += imgUrl + "/" + imageNamePrefix + "_" + i.ToString("000") + ".jpg|";
Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution);
Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100);
jpegDevice.Process(doc.Pages[i], stream);
Image img = Image.FromStream(stream);
Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f);
bm.Save(imgPath, ImageFormat.Jpeg);
img.Dispose();
stream.Dispose();
bm.Dispose();
System.Threading.Thread.Sleep(200);
}
if (!string.IsNullOrEmpty(imgName))
{
imgName = imgName.Substring(0, imgName.Length - 1);
}
return imgName;
}
catch (Exception ex)
{
ErrorHandler.WriteError(ex);
throw;
}
}
}
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Xml; namespace LicenseHelper { public static class ModifyInMemory { private static string AsposeList = "Aspose.3D.dll, Aspose.BarCode.dll, Aspose.BarCode.Compact.dll, Aspose.BarCode.WPF.dll, Aspose.Cells.GridDesktop.dll, Aspose.Cells.GridWeb.dll, Aspose.CAD.dll, Aspose.Cells.dll, Aspose.Diagram.dll, Aspose.Email.dll, Aspose.Imaging.dll, Aspose.Note.dll, Aspose.OCR.dll, Aspose.Pdf.dll, Aspose.Slides.dll, Aspose.Tasks.dll, Aspose.Words.dll"; public static void ActivateMemoryPatching() { Assembly[] arr = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in arr) { if (AsposeList.IndexOf(assembly.FullName.Split(‘,‘)[0] + ".dll") != -1) ActivateForAssembly(assembly); } AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(ActivateOnLoad); } private static void ActivateOnLoad(object sender, AssemblyLoadEventArgs e) { if (AsposeList.IndexOf(e.LoadedAssembly.FullName.Split(‘,‘)[0] + ".dll") != -1) ActivateForAssembly(e.LoadedAssembly); } private static void ActivateForAssembly(Assembly assembly) { MethodInfo miLicensed1 = typeof(ModifyInMemory).GetMethod("InvokeMe1", BindingFlags.NonPublic | BindingFlags.Static); MethodInfo miLicensed2 = typeof(ModifyInMemory).GetMethod("InvokeMe2", BindingFlags.NonPublic | BindingFlags.Static); MethodInfo miEvaluation = null; Dictionary<string, MethodInfo> miDict = new Dictionary<string, MethodInfo>() { {"System.DateTime" , miLicensed1}, {"System.Xml.XmlElement", miLicensed2} }; Type[] arrType = null; bool isFound = false; int nCount = 0; try { arrType = assembly.GetTypes(); } catch (ReflectionTypeLoadException err) { arrType = err.Types; } foreach (Type type in arrType) { if (isFound) break; if (type == null) continue; MethodInfo[] arrMInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static); foreach (MethodInfo info in arrMInfo) { if (isFound) break; try { string strMethod = info.ToString(); if ((strMethod.IndexOf("(System.Xml.XmlElement, System.String)") > 0) && (miDict.ContainsKey(info.ReturnType.ToString()))) { miEvaluation = info; MemoryPatching(miEvaluation, miDict[miEvaluation.ReturnType.ToString()]); nCount++; if (((assembly.FullName.IndexOf("Aspose.Pdf") == -1) && (nCount == 2)) || ((assembly.FullName.IndexOf("Aspose.Pdf") != -1) && (nCount == 6))) { isFound = true; break; } } } catch { throw new InvalidOperationException("MemoryPatching for \"" + assembly.FullName + "\" failed !"); } } } String[] aParts = assembly.FullName.Split(‘,‘); string fName = aParts[0]; if (fName.IndexOf("Aspose.BarCode.") != -1) fName = "Aspose.BarCode"; else if (fName.IndexOf("Aspose.3D") != -1) fName = "Aspose.ThreeD"; try { Type type2 = assembly.GetType(fName + ".License"); MethodInfo mi = type2.GetMethod("SetLicense", new Type[] { typeof(Stream) }); string LData = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5MaWNlbnNlZTwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPmxpY2Vuc2VlQGVtYWlsLmNvbTwvRW1haWxUbz4KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlVHlwZT4KICAgIDxMaWNlbnNlTm90ZT5MaW1pdGVkIHRvIDEwMDAgZGV2ZWxvcGVyLCB1bmxpbWl0ZWQgcGh5c2ljYWwgbG9jYXRpb25zPC9MaWNlbnNlTm90ZT4KICAgIDxPcmRlcklEPjc4NDM3ODU3Nzg1PC9PcmRlcklEPgogICAgPFVzZXJJRD4xMTk3ODkyNDM3OTwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIFByb2R1Y3QgRmFtaWx5PC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+e0YyQjk3MDQ1LTFCMjktNEIzRi1CRDUzLTYwMUVGRkExNUFBOX08L1NlcmlhbE51bWJlcj4KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+MjA5OTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4KICAgIDxMaWNlbnNlVmVyc2lvbj4zLjA8L0xpY2Vuc2VWZXJzaW9uPgogIDwvRGF0YT4KICA8U2lnbmF0dXJlPlFYTndiM05sTGxSdmRHRnNJRkJ5YjJSMVkzUWdSbUZ0YVd4NTwvU2lnbmF0dXJlPgo8L0xpY2Vuc2U+"; Stream stream = new MemoryStream(Convert.FromBase64String(LData)); stream.Seek(0, SeekOrigin.Begin); mi.Invoke(Activator.CreateInstance(type2, null), new Stream[] { stream }); } catch { //throw new InvalidOperationException("SetLicense for \"" + assembly.FullName + "\" failed !"); } } private static DateTime InvokeMe1(XmlElement element, string name) { return DateTime.MaxValue; } private static XmlElement InvokeMe2(XmlElement element, string name) { if (element.LocalName == "License") { string License64 = "PERhdGE+PExpY2Vuc2VkVG8+R3JvdXBEb2NzPC9MaWNlbnNlZFRvPjxMaWNlbnNlVHlwZT5TaXRlIE9FTTwvTGljZW5zZVR5cGU+PExpY2Vuc2VOb3RlPkxpbWl0ZWQgdG8gMTAgZGV2ZWxvcGVyczwvTGljZW5zZU5vdGU+PE9yZGVySUQ+MTMwNzI0MDQwODQ5PC9PcmRlcklEPjxPRU0+VGhpcyBpcyBhIHJlZGlzdHJpYnV0YWJsZSBsaWNlbnNlPC9PRU0+PFByb2R1Y3RzPjxQcm9kdWN0PkFzcG9zZS5Ub3RhbDwvUHJvZHVjdD48L1Byb2R1Y3RzPjxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT48U2VyaWFsTnVtYmVyPjliNTc5NTAxLTUyNjEtNDIyMC04NjcwLWZjMmQ4Y2NkZDkwYzwvU2VyaWFsTnVtYmVyPjxTdWJzY3JpcHRpb25FeHBpcnk+MjAxNDA3MjQ8L1N1YnNjcmlwdGlvbkV4cGlyeT48TGljZW5zZVZlcnNpb24+Mi4yPC9MaWNlbnNlVmVyc2lvbj48L0RhdGE+PFNpZ25hdHVyZT5udFpocmRoL3I0QS81ZFpsU2dWYnhac0hYSFBxSjZ5UVVYa0RvaW4vS2lVZWhUUWZET0lQdHdzUlR2NmRTUVplOVdXekNnV3RGdkdROWpmR2QySmF4YUQvbkx1ZEk2R0VVajhqeVhUMG4vbWRrMEF1WVZNYlBXRjJYd3dSTnFlTmRrblYyQjhrZVFwbDJ2RzZVbnhxS2J6VVFxS2Rhc1pzZ2w1Q0xqSFVEWms9PC9TaWduYXR1cmU+"; element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(License64)); } if (element.LocalName == "BlackList") { string BlackList64 = "PERhdGE+PC9EYXRhPjxTaWduYXR1cmU+cUJwMEx1cEVoM1ZnOWJjeS8vbUVXUk9KRWZmczRlY25iTHQxYlNhanU2NjY5RHlad09FakJ1eEdBdVBxS1hyd0x5bmZ5VWplYUNGQ0QxSkh2RVUxVUl5eXJOTnBSMXc2NXJIOUFyUCtFbE1lVCtIQkZ4NFMzckFVMnd6dkxPZnhGeU9DQ0dGQ2UraTdiSHlGQk44WHp6R1UwdGRPMGR1RTFoRTQ5M1RNY3pRPTwvU2lnbmF0dXJlPg=="; element.InnerXml = new UTF8Encoding().GetString(Convert.FromBase64String(BlackList64)); } XmlNodeList elementsByTagName = element.GetElementsByTagName(name); if (elementsByTagName.Count <= 0) { return null; } return (XmlElement)elementsByTagName[0]; } private static unsafe void MemoryPatching(MethodBase miEvaluation, MethodBase miLicensed) { IntPtr IntPtrEval = GetMemoryAddress(miEvaluation); IntPtr IntPtrLicensed = GetMemoryAddress(miLicensed); if (IntPtr.Size == 8) *((long*)IntPtrEval.ToPointer()) = *((long*)IntPtrLicensed.ToPointer()); else *((int*)IntPtrEval.ToPointer()) = *((int*)IntPtrLicensed.ToPointer()); } private static unsafe IntPtr GetMemoryAddress(MethodBase mb) { RuntimeHelpers.PrepareMethod(mb.MethodHandle); if ((Environment.Version.Major >= 4) || ((Environment.Version.Major == 2) && (Environment.Version.MinorRevision >= 3053))) { return new IntPtr(((int*)mb.MethodHandle.Value.ToPointer() + 2)); } UInt64* location = (UInt64*)(mb.MethodHandle.Value.ToPointer()); int index = (int)(((*location) >> 32) & 0xFF); if (IntPtr.Size == 8) { ulong* classStart = (ulong*)mb.DeclaringType.TypeHandle.Value.ToPointer(); ulong* address = classStart + index + 10; return new IntPtr(address); } else { uint* classStart = (uint*)mb.DeclaringType.TypeHandle.Value.ToPointer(); uint* address = classStart + index + 10; return new IntPtr(address); } } } }