Commit d3ef1d69 authored by liudong1993's avatar liudong1993

主项目 移除aspose引用

parent ceb29aa4
......@@ -15,9 +15,6 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aspose.PDF" Version="20.9.0" />
<PackageReference Include="Aspose.Slides.NET" Version="20.8.0" />
<PackageReference Include="Aspose.Words" Version="20.9.0" />
<PackageReference Include="BarcodeLib" Version="2.2.5" />
<PackageReference Include="CoreHtmlToImage" Version="1.0.6" />
<PackageReference Include="LumenWorks.Framework.IO.Core" Version="1.0.1" />
......
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
using Schematrix;
namespace Mall.Common.Plugin
{
/*
*
* 将pdf、ppf、word转换给图片的组件有很多,这里仅使用Aspose组件(试用版)作为示例。
*
* Aspose官网:www.aspose.com, 请支持和购买正版Aspose组件。
*
*/
#region word文档转换为图片
public class Word2ImageConverter
{
private bool cancelled = false;
public void Cancel()
{
if (this.cancelled)
{
return;
}
this.cancelled = true;
}
public void ConvertToImage(string originFilePath, string imageOutputDirPath)
{
this.cancelled = false;
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, null, 200);
}
/// <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>
private void ConvertToImage(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution)
{
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;
for (int i = startPageNum; i <= endPageNum; i++)
{
if (this.cancelled)
{
break;
}
MemoryStream stream = new MemoryStream();
imageSaveOptions.PageIndex = i - 1;
string imgPath = Path.Combine(imageOutputDirPath, imageName) + "_" + i.ToString("000") + "." + imageFormat.ToString();
doc.Save(stream, imageSaveOptions);
Image img = Image.FromStream(stream);
Bitmap bm = (Bitmap)img;
bm.Save(imgPath, imageFormat);
img.Dispose();
stream.Dispose();
bm.Dispose();
System.Threading.Thread.Sleep(200);
}
if (this.cancelled)
{
return;
}
}
catch (Exception ex)
{
LogHelper.Write(ex, "word转图片");
}
}
}
#endregion
#region pdf文档转换为图片
public class Pdf2ImageConverter
{
private bool cancelled = false;
public void Cancel()
{
if (this.cancelled)
{
return;
}
this.cancelled = true;
}
public void ConvertToImage(string originFilePath, string imageOutputDirPath)
{
this.cancelled = false;
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200);
}
/// <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>
private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
{
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);
for (int i = startPageNum; i <= endPageNum; i++)
{
if (this.cancelled)
{
break;
}
MemoryStream stream = new MemoryStream();
string imgPath = Path.Combine(imageOutputDirPath, 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 = (Bitmap)img;
bm.Save(imgPath, ImageFormat.Jpeg);
img.Dispose();
stream.Dispose();
bm.Dispose();
System.Threading.Thread.Sleep(200);
}
if (this.cancelled)
{
return;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
LogHelper.Write(ex, "pdf转图片");
}
}
}
#endregion
#region ppt文档转换为图片
public class Ppt2ImageConverter
{
private Pdf2ImageConverter pdf2ImageConverter;
public void Cancel()
{
if (this.pdf2ImageConverter != null)
{
this.pdf2ImageConverter.Cancel();
}
}
public void ConvertToImage(string originFilePath, string imageOutputDirPath)
{
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200);
}
/// <summary>
/// 将pdf文档转换为图片的方法
/// </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>
private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
{
try
{
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;
}
//先将ppt转换为pdf临时文件
string tmpPdfPath = originFilePath + ".pdf";
doc.Save(tmpPdfPath ,Aspose.Slides.Export.SaveFormat.Pdf);
//再将pdf转换为图片
Pdf2ImageConverter converter = new Pdf2ImageConverter();
converter.ConvertToImage(tmpPdfPath, imageOutputDirPath);
//删除pdf临时文件
File.Delete(tmpPdfPath);
}
catch (Exception ex)
{
LogHelper.Write(ex, "ppt转图片");
}
this.pdf2ImageConverter = null;
}
}
#endregion
#region 将图片压缩包解压。(如果课件本身就是多张图片,那么可以将它们压缩成一个rar,作为一个课件)
/// <summary>
/// 将图片压缩包解压。(如果课件本身就是多张图片,那么可以将它们压缩成一个rar,作为一个课件)
/// </summary>
public class Rar2ImageConverter
{
private bool cancelled = false;
public void Cancel()
{
this.cancelled = true;
}
public void ConvertToImage(string rarPath, string imageOutputDirPath)
{
try
{
Unrar tmp = new Unrar(rarPath);
tmp.Open(Unrar.OpenMode.List);
string[] files = tmp.ListFiles();
tmp.Close();
int total = files.Length;
int done = 0;
Unrar unrar = new Unrar(rarPath);
unrar.Open(Unrar.OpenMode.Extract);
unrar.DestinationPath = imageOutputDirPath;
while (unrar.ReadHeader() && !cancelled)
{
if (unrar.CurrentFile.IsDirectory)
{
unrar.Skip();
}
else
{
unrar.Extract();
++done;
}
}
unrar.Close();
}
catch (Exception ex)
{
LogHelper.Write(ex, "转图片压缩失败");
}
}
}
#endregion
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Schematrix;
using System.Runtime.InteropServices;
using System.Collections;
/* Author: Michael A. McCloskey
* Company: Schematrix
* Version: 20040714
*
* Personal Comments:
* I created this unrar wrapper class for personal use
* after running into a number of issues trying to use
* another COM unrar product via COM interop. I hope it
* proves as useful to you as it has to me and saves you
* some time in building your own products.
*/
// Modified 2009 by Blue Mirror
namespace Schematrix
{
#region Event Delegate Definitions
/// <summary>
/// Represents the method that will handle data available events
/// </summary>
public delegate void DataAvailableHandler(object sender, DataAvailableEventArgs e);
/// <summary>
/// Represents the method that will handle extraction progress events
/// </summary>
public delegate void ExtractionProgressHandler(object sender, ExtractionProgressEventArgs e);
/// <summary>
/// Represents the method that will handle missing archive volume events
/// </summary>
public delegate void MissingVolumeHandler(object sender, MissingVolumeEventArgs e);
/// <summary>
/// Represents the method that will handle new volume events
/// </summary>
public delegate void NewVolumeHandler(object sender, NewVolumeEventArgs e);
/// <summary>
/// Represents the method that will handle new file notifications
/// </summary>
public delegate void NewFileHandler(object sender, NewFileEventArgs e);
/// <summary>
/// Represents the method that will handle password required events
/// </summary>
public delegate void PasswordRequiredHandler(object sender, PasswordRequiredEventArgs e);
#endregion
/// <summary>
/// Wrapper class for unrar DLL supplied by RARSoft.
/// Calls unrar DLL via platform invocation services (pinvoke).
/// DLL is available at http://www.rarlab.com/rar/UnRARDLL.exe
/// </summary>
public class Unrar : IDisposable
{
#region Unrar DLL enumerations
/// <summary>
/// Mode in which archive is to be opened for processing.
/// </summary>
public enum OpenMode
{
/// <summary>
/// Open archive for listing contents only
/// </summary>
List = 0,
/// <summary>
/// Open archive for testing or extracting contents
/// </summary>
Extract = 1
}
private enum RarError : uint
{
EndOfArchive = 10,
InsufficientMemory = 11,
BadData = 12,
BadArchive = 13,
UnknownFormat = 14,
OpenError = 15,
CreateError = 16,
CloseError = 17,
ReadError = 18,
WriteError = 19,
BufferTooSmall = 20,
UnknownError = 21
}
private enum Operation : uint
{
Skip = 0,
Test = 1,
Extract = 2
}
private enum VolumeMessage : uint
{
Ask = 0,
Notify = 1
}
[Flags]
private enum ArchiveFlags : uint
{
Volume = 0X1, // Volume attribute (archive volume)
CommentPresent = 0X2, // Archive comment present
Lock = 0X4, // Archive lock attribute
SolidArchive = 0X8, // Solid attribute (solid archive)
NewNamingScheme = 0X10, // New volume naming scheme (‘volname.partN.rar’)
AuthenticityPresent = 0X20, // Authenticity information present
RecoveryRecordPresent = 0X40, // Recovery record present
EncryptedHeaders = 0X80, // Block headers are encrypted
FirstVolume = 0X100 // 0X0100 – First volume (set only by RAR 3.0 and later)
}
private enum CallbackMessages : uint
{
VolumeChange = 0,
ProcessData = 1,
NeedPassword = 2
}
#endregion
#region Unrar DLL structure definitions
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct RARHeaderData
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string ArcName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string FileName;
public uint Flags;
public uint PackSize;
public uint UnpSize;
public uint HostOS;
public uint FileCRC;
public uint FileTime;
public uint UnpVer;
public uint Method;
public uint FileAttr;
[MarshalAs(UnmanagedType.LPStr)]
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
public void Initialize()
{
this.CmtBuf = new string((char)0, 65536);
this.CmtBufSize = 65536;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct RARHeaderDataEx
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string ArcName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string ArcNameW;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string FileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string FileNameW;
public uint Flags;
public uint PackSize;
public uint PackSizeHigh;
public uint UnpSize;
public uint UnpSizeHigh;
public uint HostOS;
public uint FileCRC;
public uint FileTime;
public uint UnpVer;
public uint Method;
public uint FileAttr;
[MarshalAs(UnmanagedType.LPStr)]
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
public uint[] Reserved;
public void Initialize()
{
this.CmtBuf = new string((char)0, 65536);
this.CmtBufSize = 65536;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct RAROpenArchiveData
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string ArcName;
public uint OpenMode;
public uint OpenResult;
[MarshalAs(UnmanagedType.LPStr)]
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
public void Initialize()
{
this.CmtBuf = new string((char)0, 65536);
this.CmtBufSize = 65536;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct RAROpenArchiveDataEx
{
[MarshalAs(UnmanagedType.LPStr)]
public string ArcName;
[MarshalAs(UnmanagedType.LPWStr)]
public string ArcNameW;
public uint OpenMode;
public uint OpenResult;
[MarshalAs(UnmanagedType.LPStr)]
public string CmtBuf;
public uint CmtBufSize;
public uint CmtSize;
public uint CmtState;
public uint Flags;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public uint[] Reserved;
public void Initialize()
{
this.CmtBuf = new string((char)0, 65536);
this.CmtBufSize = 65536;
this.Reserved = new uint[32];
}
}
#endregion
#region Unrar function declarations
[DllImport("unrar.dll")]
private static extern IntPtr RAROpenArchive(ref RAROpenArchiveData archiveData);
[DllImport("UNRAR.DLL")]
private static extern IntPtr RAROpenArchiveEx(ref RAROpenArchiveDataEx archiveData);
[DllImport("unrar.dll")]
private static extern int RARCloseArchive(IntPtr hArcData);
[DllImport("unrar.dll")]
private static extern int RARReadHeader(IntPtr hArcData, ref RARHeaderData headerData);
[DllImport("unrar.dll")]
private static extern int RARReadHeaderEx(IntPtr hArcData, ref RARHeaderDataEx headerData);
[DllImport("unrar.dll")]
private static extern int RARProcessFile(IntPtr hArcData, int operation,
[MarshalAs(UnmanagedType.LPStr)] string destPath,
[MarshalAs(UnmanagedType.LPStr)] string destName);
[DllImport("unrar.dll")]
private static extern void RARSetCallback(IntPtr hArcData, UNRARCallback callback, int userData);
[DllImport("unrar.dll")]
private static extern void RARSetPassword(IntPtr hArcData,
[MarshalAs(UnmanagedType.LPStr)] string password);
// Unrar callback delegate signature
private delegate int UNRARCallback(uint msg, int UserData, IntPtr p1, int p2);
#endregion
#region Public event declarations
/// <summary>
/// Event that is raised when a new chunk of data has been extracted
/// </summary>
public event DataAvailableHandler DataAvailable;
/// <summary>
/// Event that is raised to indicate extraction progress
/// </summary>
public event ExtractionProgressHandler ExtractionProgress;
/// <summary>
/// Event that is raised when a required archive volume is missing
/// </summary>
public event MissingVolumeHandler MissingVolume;
/// <summary>
/// Event that is raised when a new file is encountered during processing
/// </summary>
public event NewFileHandler NewFile;
/// <summary>
/// Event that is raised when a new archive volume is opened for processing
/// </summary>
public event NewVolumeHandler NewVolume;
/// <summary>
/// Event that is raised when a password is required before continuing
/// </summary>
public event PasswordRequiredHandler PasswordRequired;
#endregion
#region Private fields
private string archivePathName = string.Empty;
private IntPtr archiveHandle = new IntPtr(0);
private bool retrieveComment = true;
private string password = string.Empty;
private string comment = string.Empty;
private ArchiveFlags archiveFlags = 0;
private RARHeaderDataEx header = new RARHeaderDataEx();
private string destinationPath = string.Empty;
private RARFileInfo currentFile = null;
private UNRARCallback callback = null;
#endregion
#region Object lifetime procedures
public Unrar()
{
this.callback = new UNRARCallback(RARCallback);
}
public Unrar(string archivePathName)
: this()
{
this.archivePathName = archivePathName;
}
~Unrar()
{
if (this.archiveHandle != IntPtr.Zero)
{
Unrar.RARCloseArchive(this.archiveHandle);
this.archiveHandle = IntPtr.Zero;
}
}
public void Dispose()
{
if (this.archiveHandle != IntPtr.Zero)
{
Unrar.RARCloseArchive(this.archiveHandle);
this.archiveHandle = IntPtr.Zero;
}
}
#endregion
#region Public Properties
/// <summary>
/// Path and name of RAR archive to open
/// </summary>
public string ArchivePathName
{
get
{
return this.archivePathName;
}
set
{
this.archivePathName = value;
}
}
/// <summary>
/// Archive comment
/// </summary>
public string Comment
{
get
{
return (this.comment);
}
}
/// <summary>
/// Current file being processed
/// </summary>
public RARFileInfo CurrentFile
{
get
{
return (this.currentFile);
}
}
/// <summary>
/// Default destination path for extraction
/// </summary>
public string DestinationPath
{
get
{
return this.destinationPath;
}
set
{
this.destinationPath = value;
}
}
/// <summary>
/// Password for opening encrypted archive
/// </summary>
public string Password
{
get
{
return (this.password);
}
set
{
this.password = value;
if (this.archiveHandle != IntPtr.Zero)
RARSetPassword(this.archiveHandle, value);
}
}
#endregion
#region Public Methods
/// <summary>
/// Close the currently open archive
/// </summary>
/// <returns></returns>
public void Close()
{
// Exit without exception if no archive is open
if (this.archiveHandle == IntPtr.Zero)
return;
// Close archive
int result = Unrar.RARCloseArchive(this.archiveHandle);
// Check result
if (result != 0)
{
processFileError(result);
}
else
{
this.archiveHandle = IntPtr.Zero;
}
}
/// <summary>
/// Opens archive specified by the ArchivePathName property for testing or extraction
/// </summary>
public void Open()
{
if (this.ArchivePathName.Length == 0)
throw new IOException("Archive name has not been set.");
this.Open(this.ArchivePathName, OpenMode.Extract);
}
/// <summary>
/// Opens archive specified by the ArchivePathName property with a specified mode
/// </summary>
/// <param name="openMode">Mode in which archive should be opened</param>
public void Open(OpenMode openMode)
{
if (this.ArchivePathName.Length == 0)
throw new IOException("Archive name has not been set.");
this.Open(this.ArchivePathName, openMode);
}
/// <summary>
/// Opens specified archive using the specified mode.
/// </summary>
/// <param name="archivePathName">Path of archive to open</param>
/// <param name="openMode">Mode in which to open archive</param>
public void Open(string archivePathName, OpenMode openMode)
{
IntPtr handle = IntPtr.Zero;
// Close any previously open archives
if (this.archiveHandle != IntPtr.Zero)
this.Close();
// Prepare extended open archive struct
this.ArchivePathName = archivePathName;
RAROpenArchiveDataEx openStruct = new RAROpenArchiveDataEx();
openStruct.Initialize();
openStruct.ArcName = this.archivePathName + "\0";
openStruct.ArcNameW = this.archivePathName + "\0";
openStruct.OpenMode = (uint)openMode;
if (this.retrieveComment)
{
openStruct.CmtBuf = new string((char)0, 65536);
openStruct.CmtBufSize = 65536;
}
else
{
openStruct.CmtBuf = null;
openStruct.CmtBufSize = 0;
}
// Open archive
handle = Unrar.RAROpenArchiveEx(ref openStruct);
// Check for success
if (openStruct.OpenResult != 0)
{
switch ((RarError)openStruct.OpenResult)
{
case RarError.InsufficientMemory:
throw new OutOfMemoryException("Insufficient memory to perform operation.");
case RarError.BadData:
throw new IOException("Archive header broken");
case RarError.BadArchive:
throw new IOException("File is not a valid archive.");
case RarError.OpenError:
throw new IOException("File could not be opened.");
}
}
// Save handle and flags
this.archiveHandle = handle;
this.archiveFlags = (ArchiveFlags)openStruct.Flags;
// Set callback
Unrar.RARSetCallback(this.archiveHandle, this.callback, this.GetHashCode());
// If comment retrieved, save it
if (openStruct.CmtState == 1)
this.comment = openStruct.CmtBuf.ToString();
// If password supplied, set it
if (this.password.Length != 0)
Unrar.RARSetPassword(this.archiveHandle, this.password);
// Fire NewVolume event for first volume
this.OnNewVolume(this.archivePathName);
}
/// <summary>
/// Reads the next archive header and populates CurrentFile property data
/// </summary>
/// <returns></returns>
public bool ReadHeader()
{
// Throw exception if archive not open
if (this.archiveHandle == IntPtr.Zero)
throw new IOException("Archive is not open.");
// Initialize header struct
this.header = new RARHeaderDataEx();
header.Initialize();
// Read next entry
currentFile = null;
int result = Unrar.RARReadHeaderEx(this.archiveHandle, ref this.header);
// Check for error or end of archive
if ((RarError)result == RarError.EndOfArchive)
return false;
else if ((RarError)result == RarError.BadData)
throw new IOException("Archive data is corrupt.");
// Determine if new file
if (((header.Flags & 0X01) != 0) && currentFile != null)
currentFile.ContinuedFromPrevious = true;
else
{
// New file, prepare header
currentFile = new RARFileInfo();
currentFile.FileName = header.FileNameW.ToString();
if ((header.Flags & 0X02) != 0)
currentFile.ContinuedOnNext = true;
if (header.PackSizeHigh != 0)
currentFile.PackedSize = (header.PackSizeHigh * 0X100000000) + header.PackSize;
else
currentFile.PackedSize = header.PackSize;
if (header.UnpSizeHigh != 0)
currentFile.UnpackedSize = (header.UnpSizeHigh * 0X100000000) + header.UnpSize;
else
currentFile.UnpackedSize = header.UnpSize;
currentFile.HostOS = (int)header.HostOS;
currentFile.FileCRC = header.FileCRC;
currentFile.FileTime = FromMSDOSTime(header.FileTime);
currentFile.VersionToUnpack = (int)header.UnpVer;
currentFile.Method = (int)header.Method;
currentFile.FileAttributes = (int)header.FileAttr;
currentFile.BytesExtracted = 0;
if ((header.Flags & 0xE0) == 0xE0)
currentFile.IsDirectory = true;
this.OnNewFile();
}
// Return success
return true;
}
/// <summary>
/// Returns array of file names contained in archive
/// </summary>
/// <returns></returns>
public string[] ListFiles()
{
ArrayList fileNames = new ArrayList();
while (this.ReadHeader())
{
if (!currentFile.IsDirectory)
fileNames.Add(currentFile.FileName);
this.Skip();
}
string[] files = new string[fileNames.Count];
fileNames.CopyTo(files);
return files;
}
/// <summary>
/// Moves the current archive position to the next available header
/// </summary>
/// <returns></returns>
public void Skip()
{
int result = Unrar.RARProcessFile(this.archiveHandle, (int)Operation.Skip, string.Empty, string.Empty);
// Check result
if (result != 0)
{
processFileError(result);
}
}
/// <summary>
/// Tests the ability to extract the current file without saving extracted data to disk
/// </summary>
/// <returns></returns>
public void Test()
{
int result = Unrar.RARProcessFile(this.archiveHandle, (int)Operation.Test, string.Empty, string.Empty);
// Check result
if (result != 0)
{
processFileError(result);
}
}
/// <summary>
/// Extracts the current file to the default destination path
/// </summary>
/// <returns></returns>
public void Extract()
{
this.Extract(this.destinationPath, string.Empty);
}
/// <summary>
/// Extracts the current file to a specified destination path and filename
/// </summary>
/// <param name="destinationName">Path and name of extracted file</param>
/// <returns></returns>
public void Extract(string destinationName)
{
this.Extract(string.Empty, destinationName);
}
/// <summary>
/// Extracts the current file to a specified directory without renaming file
/// </summary>
/// <param name="destinationPath"></param>
/// <returns></returns>
public void ExtractToDirectory(string destinationPath)
{
this.Extract(destinationPath, string.Empty);
}
#endregion
#region Private Methods
private void Extract(string destinationPath, string destinationName)
{
int result = Unrar.RARProcessFile(this.archiveHandle, (int)Operation.Extract, destinationPath, destinationName);
// Check result
if (result != 0)
{
processFileError(result);
}
}
private DateTime FromMSDOSTime(uint dosTime)
{
int day = 0;
int month = 0;
int year = 0;
int second = 0;
int hour = 0;
int minute = 0;
ushort hiWord;
ushort loWord;
hiWord = (ushort)((dosTime & 0xFFFF0000) >> 16);
loWord = (ushort)(dosTime & 0xFFFF);
year = ((hiWord & 0xFE00) >> 9) + 1980;
month = (hiWord & 0x01E0) >> 5;
day = hiWord & 0x1F;
hour = (loWord & 0xF800) >> 11;
minute = (loWord & 0x07E0) >> 5;
second = (loWord & 0x1F) << 1;
return new DateTime(year, month, day, hour, minute, second);
}
private static void processFileError(int result)
{
switch ((RarError)result)
{
case RarError.UnknownFormat:
throw new OutOfMemoryException("Unknown archive format.");
case RarError.BadData:
throw new IOException("File CRC Error");
case RarError.BadArchive:
throw new IOException("File is not a valid archive.");
case RarError.OpenError:
throw new IOException("File could not be opened.");
case RarError.CreateError:
throw new IOException("File could not be created.");
case RarError.CloseError:
throw new IOException("File close error.");
case RarError.ReadError:
throw new IOException("File read error.");
case RarError.WriteError:
throw new IOException("File write error.");
}
}
private int RARCallback(uint msg, int UserData, IntPtr p1, int p2)
{
string volume = string.Empty;
string newVolume = string.Empty;
int result = -1;
switch ((CallbackMessages)msg)
{
case CallbackMessages.VolumeChange:
volume = Marshal.PtrToStringAnsi(p1);
if ((VolumeMessage)p2 == VolumeMessage.Notify)
result = OnNewVolume(volume);
else if ((VolumeMessage)p2 == VolumeMessage.Ask)
{
newVolume = OnMissingVolume(volume);
if (newVolume.Length == 0)
result = -1;
else
{
if (newVolume != volume)
{
for (int i = 0; i < newVolume.Length; i++)
{
Marshal.WriteByte(p1, i, (byte)newVolume[i]);
}
Marshal.WriteByte(p1, newVolume.Length, (byte)0);
}
result = 1;
}
}
break;
case CallbackMessages.ProcessData:
result = OnDataAvailable(p1, p2);
break;
case CallbackMessages.NeedPassword:
result = OnPasswordRequired(p1, p2);
break;
}
return result;
}
#endregion
#region Protected Virtual (Overridable) Methods
protected virtual void OnNewFile()
{
if (this.NewFile != null)
{
NewFileEventArgs e = new NewFileEventArgs(this.currentFile);
this.NewFile(this, e);
}
}
protected virtual int OnPasswordRequired(IntPtr p1, int p2)
{
int result = -1;
if (this.PasswordRequired != null)
{
PasswordRequiredEventArgs e = new PasswordRequiredEventArgs();
this.PasswordRequired(this, e);
if (e.ContinueOperation && e.Password.Length > 0)
{
for (int i = 0; (i < e.Password.Length) && (i < p2); i++)
Marshal.WriteByte(p1, i, (byte)e.Password[i]);
Marshal.WriteByte(p1, e.Password.Length, (byte)0);
result = 1;
}
}
else
{
throw new IOException("Password is required for extraction.");
}
return result;
}
protected virtual int OnDataAvailable(IntPtr p1, int p2)
{
int result = 1;
if (this.currentFile != null)
this.currentFile.BytesExtracted += p2;
if (this.DataAvailable != null)
{
byte[] data = new byte[p2];
Marshal.Copy(p1, data, 0, p2);
DataAvailableEventArgs e = new DataAvailableEventArgs(data);
this.DataAvailable(this, e);
if (!e.ContinueOperation)
result = -1;
}
if ((this.ExtractionProgress != null) && (this.currentFile != null))
{
ExtractionProgressEventArgs e = new ExtractionProgressEventArgs();
e.FileName = this.currentFile.FileName;
e.FileSize = this.currentFile.UnpackedSize;
e.BytesExtracted = this.currentFile.BytesExtracted;
e.PercentComplete = this.currentFile.PercentComplete;
this.ExtractionProgress(this, e);
if (!e.ContinueOperation)
result = -1;
}
return result;
}
protected virtual int OnNewVolume(string volume)
{
int result = 1;
if (this.NewVolume != null)
{
NewVolumeEventArgs e = new NewVolumeEventArgs(volume);
this.NewVolume(this, e);
if (!e.ContinueOperation)
result = -1;
}
return result;
}
protected virtual string OnMissingVolume(string volume)
{
string result = string.Empty;
if (this.MissingVolume != null)
{
MissingVolumeEventArgs e = new MissingVolumeEventArgs(volume);
this.MissingVolume(this, e);
if (e.ContinueOperation)
result = e.VolumeName;
}
return result;
}
#endregion
}
#region Event Argument Classes
public class NewVolumeEventArgs
{
public string VolumeName;
public bool ContinueOperation = true;
public NewVolumeEventArgs(string volumeName)
{
this.VolumeName = volumeName;
}
}
public class MissingVolumeEventArgs
{
public string VolumeName;
public bool ContinueOperation = false;
public MissingVolumeEventArgs(string volumeName)
{
this.VolumeName = volumeName;
}
}
public class DataAvailableEventArgs
{
public readonly byte[] Data;
public bool ContinueOperation = true;
public DataAvailableEventArgs(byte[] data)
{
this.Data = data;
}
}
public class PasswordRequiredEventArgs
{
public string Password = string.Empty;
public bool ContinueOperation = true;
}
public class NewFileEventArgs
{
public RARFileInfo fileInfo;
public NewFileEventArgs(RARFileInfo fileInfo)
{
this.fileInfo = fileInfo;
}
}
public class ExtractionProgressEventArgs
{
public string FileName;
public long FileSize;
public long BytesExtracted;
public double PercentComplete;
public bool ContinueOperation = true;
}
public class RARFileInfo
{
public string FileName;
public bool ContinuedFromPrevious = false;
public bool ContinuedOnNext = false;
public bool IsDirectory = false;
public long PackedSize = 0;
public long UnpackedSize = 0;
public int HostOS = 0;
public long FileCRC = 0;
public DateTime FileTime;
public int VersionToUnpack = 0;
public int Method = 0;
public int FileAttributes = 0;
public long BytesExtracted = 0;
public double PercentComplete
{
get
{
if (this.UnpackedSize != 0)
return (((double)this.BytesExtracted / (double)this.UnpackedSize) * (double)100.0);
else
return (double)0;
}
}
}
#endregion
public class Test
{
/// <summary>
///
/// </summary>
/// <param name="rarArchive">rar文件地址</param>
/// <param name="destinationPath">目标地址</param>
/// <param name="CreateDir">是否创建目录</param>
public static void DecompressRar(string rarArchive, string destinationPath, bool CreateDir)
{
if (File.Exists(rarArchive))
{
Unrar tmp = new Unrar(rarArchive);
tmp.Open(Unrar.OpenMode.List);
string[] files = tmp.ListFiles();
tmp.Close();
Unrar unrar = new Unrar(rarArchive);
unrar.Open(Unrar.OpenMode.Extract);
unrar.DestinationPath = destinationPath;
while (unrar.ReadHeader())
{
if (unrar.CurrentFile.IsDirectory)
{
unrar.Skip();
}
else
{
if (CreateDir)
{
unrar.Extract();
}
else
{
unrar.Extract(destinationPath + Path.GetFileName(unrar.CurrentFile.FileName));
}
}
}
unrar.Close();
}
}
}
}
......@@ -19,22 +19,26 @@ namespace Mall.Education.Helper
{
/// <summary>
/// 插入图片
/// 插入课程图片记录
/// </summary>
/// <param name="cookie"></param>
public static void InsertGoodsFileImage()
public static int InsertGoodsFileImage(int CourseId, string goodsImages)
{
string citySql = $@"SELECT * FROM rb_destination WHERE 1=1 and Status =0 AND Name in('成都市') ";
var cityDataList = MySqlHelper.ExecuteDataset(MySqlHelper.defaultConnection, System.Data.CommandType.Text, citySql, null);
LogHelper.Write(JsonConvert.SerializeObject(cityDataList.Tables[0].Rows));
//var sqlOrderDetailResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrderDetail, null);
string sql = $@"update rb_goods_course set Image='{goodsImages}' where Id ={CourseId} ";
var result = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sql, null);
return result;
}
/// <summary>
/// 上传图片至阿里云/腾讯云
/// 删除课程图片记录
/// </summary>
public static void UpLoadImage() {
/// <param name="cookie"></param>
public static void DelGoodsFileImage()
{
string citySql = $@"SELECT * FROM rb_destination WHERE 1=1 and Status =0 AND Name in('成都市') ";
var cityDataList = MySqlHelper.ExecuteDataset(MySqlHelper.defaultConnection, System.Data.CommandType.Text, citySql, null);
LogHelper.Write(JsonConvert.SerializeObject(cityDataList.Tables[0].Rows));
//var sqlOrderDetailResult = MySqlHelper.ExecuteNonQuery(MySqlHelper.defaultConnection, System.Data.CommandType.Text, sqlOrderDetail, null);
}
/// <summary>
......
......@@ -25,4 +25,19 @@ namespace Mall.Education.Models
public string FilePath { get; set; }
}
/// <summary>
/// 课程图片
/// </summary>
public class GoodsImage
{
/// <summary>
/// 排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 路径
/// </summary>
public string Path { get; set; }
}
}
......@@ -5,6 +5,10 @@ using Mall.Education.RabbitMQ;
using System;
using System.ServiceProcess;
using COSSnippet;
using Mall.Education.Offices;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Mall.Education
{
......@@ -31,16 +35,80 @@ namespace Mall.Education
//new OfficeHelper().GetWordToImagePathList("C:/Users/Administrator/Desktop/testImage/网课需求(1).docx", "C:/Users/Administrator/Desktop/testImage/Image/", null);
//new Word2ImageConverter().ConvertToImage("C:/Users/Administrator/Desktop/testImage/网课需求(1).docx", "C:/Users/Administrator/Desktop/testImage/Image/");
//new Word2ImageConverter().ConvertToImage("https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Education/wkxq.docx", "C:/Users/Administrator/Desktop/testImage/Image/", System.Drawing.Imaging.ImageFormat.Png, out int PageNum);
//new Pdf2ImageConverter().ConvertToImage("C:/Users/Administrator/Desktop/testImage/MA10048W_zh.pdf", "C:/Users/Administrator/Desktop/testImage/PdfImage/");
//new Ppt2ImageConverter().ConvertToImage("C:/Users/Administrator/Desktop/testImage/kjljlkjk.ppt", "C:/Users/Administrator/Desktop/testImage/PptImage/");
//FileDataHelper.InsertGoodsFileImage();
TransferUploadObjectModel m = new TransferUploadObjectModel();
m.TransferUploadFile("C:/Users/Administrator/Desktop/testImage/Image/网课需求(1)_001.Png", "网课需求(1)_001.Png");
//TransferUploadObjectModel m = new TransferUploadObjectModel();
//m.TransferUploadFile("C:/Users/Administrator/Desktop/testImage/Image/网课需求(1)_001.Png", "网课需求(1)_001.Png");
ImageConvertData(new GoodsModel() { CourseId = 1, GoodsId = 1, FilePath = "" });
Console.ReadKey();
}
/// <summary>
/// 处理文件
/// </summary>
/// <param name="GoodsModel"></param>
private static void ImageConvertData(GoodsModel GoodsModel)
{
string tempDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempfile/Image");
if (!Directory.Exists(tempDir))
Directory.CreateDirectory(tempDir);
//是否需要先把文件下载到服务器
GoodsModel.FilePath = "https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Education/wkxq.docx";
//文件生成图片暂存本地
string FileExtension = Path.GetExtension(GoodsModel.FilePath);
string FileName = Path.GetFileNameWithoutExtension(GoodsModel.FilePath);
string FileDirectory = Path.GetDirectoryName(GoodsModel.FilePath);
int PageNum;
System.Drawing.Imaging.ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
if (FileExtension == ".doc" || FileExtension == ".docx")
{
new Word2ImageConverter().ConvertToImage(GoodsModel.FilePath, tempDir + "/", imageFormat, out PageNum);
}
else if (FileExtension == ".pdf")
{
new Pdf2ImageConverter().ConvertToImage(GoodsModel.FilePath, tempDir + "/", imageFormat, out PageNum);
}
else if (FileExtension == ".ppt" || FileExtension == ".pptx")
{
new Ppt2ImageConverter().ConvertToImage(GoodsModel.FilePath, tempDir + "/", imageFormat, out PageNum);
}
else
{
return;
}
if (PageNum > 0)
{
List<GoodsImage> goodsImages = new List<GoodsImage>();
//开始上传图片至服务器
TransferUploadObjectModel m = new TransferUploadObjectModel();
for (var i = 1; i <= PageNum; i++)
{
string newName = FileName + "_" + i.ToString("000") + "." + imageFormat.ToString();
m.TransferUploadFile(tempDir + "/" + newName, newName);
//上传之后 写入商品课程图片数据
goodsImages.Add(new GoodsImage
{
Sort = i,
Path = FileDirectory + "/" + newName
});
}
//更新图片数据
bool flag = FileDataHelper.InsertGoodsFileImage(GoodsModel.CourseId, JsonConvert.SerializeObject(goodsImages)) > 0;
if (flag == false)
{
Console.WriteLine("更新课程图片列表失败:CourseId:" + GoodsModel.CourseId);
}
}
}
}
}
......@@ -33,10 +33,10 @@ namespace Mall.Education.Offices
this.cancelled = true;
}
public void ConvertToImage(string originFilePath, string imageOutputDirPath)
public void ConvertToImage(string originFilePath, string imageOutputDirPath, ImageFormat imageFormat, out int PageNum)
{
this.cancelled = false;
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, null, 200);
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, imageFormat, 200, out PageNum);
}
/// <summary>
......@@ -48,8 +48,9 @@ namespace Mall.Education.Offices
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
private void ConvertToImage(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution)
private void ConvertToImage(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution,out int PageNum)
{
PageNum = 0;
try
{
Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
......@@ -83,7 +84,7 @@ namespace Mall.Education.Offices
{
int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
}
PageNum = endPageNum;
if (imageFormat == null)
{
imageFormat = ImageFormat.Png;
......@@ -146,10 +147,10 @@ namespace Mall.Education.Offices
this.cancelled = true;
}
public void ConvertToImage(string originFilePath, string imageOutputDirPath)
public void ConvertToImage(string originFilePath, string imageOutputDirPath, ImageFormat imageFormat, out int PageNum)
{
this.cancelled = false;
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200);
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, imageFormat, 200, out PageNum);
}
/// <summary>
......@@ -160,8 +161,9 @@ namespace Mall.Education.Offices
/// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution, out int PageNum)
{
PageNum = 0;
try
{
Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath);
......@@ -194,7 +196,7 @@ namespace Mall.Education.Offices
{
int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
}
PageNum = endPageNum;
if (resolution <= 0)
{
resolution = 128;
......@@ -209,14 +211,14 @@ namespace Mall.Education.Offices
}
MemoryStream stream = new MemoryStream();
string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + ".jpg";
string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + imageFormat.ToString();
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 = (Bitmap)img;
bm.Save(imgPath, ImageFormat.Jpeg);
bm.Save(imgPath, imageFormat);
img.Dispose();
stream.Dispose();
bm.Dispose();
......@@ -251,9 +253,9 @@ namespace Mall.Education.Offices
}
}
public void ConvertToImage(string originFilePath, string imageOutputDirPath)
public void ConvertToImage(string originFilePath, string imageOutputDirPath, ImageFormat imageFormat, out int PageNum)
{
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200);
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200, imageFormat, out PageNum);
}
/// <summary>
......@@ -264,8 +266,9 @@ namespace Mall.Education.Offices
/// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution, ImageFormat imageFormat, out int PageNum)
{
PageNum = 0;
try
{
Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(originFilePath);
......@@ -285,21 +288,6 @@ namespace Mall.Education.Offices
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;
......@@ -311,7 +299,7 @@ namespace Mall.Education.Offices
//再将pdf转换为图片
Pdf2ImageConverter converter = new Pdf2ImageConverter();
converter.ConvertToImage(tmpPdfPath, imageOutputDirPath);
converter.ConvertToImage(tmpPdfPath, imageOutputDirPath, imageFormat, out PageNum);
//删除pdf临时文件
File.Delete(tmpPdfPath);
......
......@@ -4,6 +4,11 @@ using RabbitMQ.Client.Events;
using System;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using Mall.Education.Offices;
using COSSnippet;
using Mall.Education.Helper;
using System.Collections.Generic;
namespace Mall.Education.RabbitMQ
{
......@@ -30,61 +35,6 @@ namespace Mall.Education.RabbitMQ
return factory;
}
///// <summary>
///// 消费消息
///// </summary>
///// <param name="rabbitConfig"></param>
//public static void DealWithMessage(RabbitConfig rabbitConfig)
//{
// using (IConnection conn = GetConnectionFactory(rabbitConfig).CreateConnection())
// {
// using (IModel channel = conn.CreateModel())
// {
// //在MQ上定义一个持久化队列,如果名称相同不会重复创建
// //channel.QueueDeclare(rabbitConfig.QueenName, true, false, false, null);
// //输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息
// //channel.BasicQos(0, 1, false);
// channel.QueueDeclare(rabbitConfig.QueenName, false, false, false, null);
// var consumer = new EventingBasicConsumer(channel);//消费者
// channel.BasicConsume(rabbitConfig.QueenName, true, consumer);//消费消息
// Console.WriteLine("开始");
// consumer.Received += (model, ea) =>
// {
// //var body = ea.Body;
// Console.WriteLine("123");
// };
// Console.WriteLine("结束");
// //在队列上定义一个消费者
// //EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
// ////消费队列,并设置应答模式为程序主动应答
// //channel.BasicConsume(rabbitConfig.QueenName, true, consumer);
// //consumer.Received += (sender, e) =>
// //{
// // Console.WriteLine("123");
// // //byte[] bytes = e.Body.ToArray();
// // //string message = Encoding.UTF8.GetString(bytes);
// // //try
// // //{
// // // Console.WriteLine(message);
// // // //序列化 操作数据
// // // //var msgModel = JsonConvert.DeserializeObject<FeaturesMQ>(message);
// // //}
// // //catch (Exception)
// // //{
// // // throw;
// // //}
// // //channel.BasicAck(e.DeliveryTag, false);
// //};
// }
// }
//}
[Obsolete]
public static void DealWithMessage(RabbitConfig rabbitConfig)
{
......@@ -111,7 +61,11 @@ namespace Mall.Education.RabbitMQ
{
var GoodsModel = JsonConvert.DeserializeObject<GoodsModel>(msg);
//处理
Console.WriteLine(msg);
if (GoodsModel != null)
{
ImageConvertData(GoodsModel);
}
//Console.WriteLine(msg);
}
catch (Exception ex)
{
......@@ -123,5 +77,64 @@ namespace Mall.Education.RabbitMQ
}
}
}
/// <summary>
/// 处理文件
/// </summary>
/// <param name="GoodsModel"></param>
private static void ImageConvertData(GoodsModel GoodsModel)
{
string tempDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempfile/Image");
if (!Directory.Exists(tempDir))
Directory.CreateDirectory(tempDir);
//是否需要先把文件下载到服务器
GoodsModel.FilePath = "https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Education/wkxq.docx";
//文件生成图片暂存本地
string FileExtension = Path.GetExtension(GoodsModel.FilePath);
string FileName = Path.GetFileNameWithoutExtension(GoodsModel.FilePath);
string FileDirectory = Path.GetDirectoryName(GoodsModel.FilePath);
int PageNum;
System.Drawing.Imaging.ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
if (FileExtension == ".doc" || FileExtension == ".docx")
{
new Word2ImageConverter().ConvertToImage(GoodsModel.FilePath, tempDir + "/", imageFormat, out PageNum);
}
else if (FileExtension == ".pdf")
{
new Pdf2ImageConverter().ConvertToImage(GoodsModel.FilePath, tempDir + "/", imageFormat, out PageNum);
}
else if (FileExtension == ".ppt" || FileExtension == ".pptx")
{
new Ppt2ImageConverter().ConvertToImage(GoodsModel.FilePath, tempDir + "/", imageFormat, out PageNum);
}
else {
return;
}
if (PageNum > 0)
{
List<GoodsImage> goodsImages = new List<GoodsImage>();
//开始上传图片至服务器
TransferUploadObjectModel m = new TransferUploadObjectModel();
for (var i = 1; i <= PageNum; i++)
{
string newName = FileName + "_" + i.ToString("000") + "." + imageFormat.ToString();
m.TransferUploadFile(tempDir + "/" + newName, newName);
//上传之后 写入商品课程图片数据
goodsImages.Add(new GoodsImage
{
Sort = i,
Path = FileDirectory + "/" + newName
});
}
//更新图片数据
bool flag = FileDataHelper.InsertGoodsFileImage(GoodsModel.CourseId, JsonConvert.SerializeObject(goodsImages)) > 0;
if (flag == false) {
Console.WriteLine("更新课程图片列表失败:CourseId:" + GoodsModel.CourseId);
}
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment