Commit b934dc6e authored by liudong1993's avatar liudong1993

转图片优化

parent a5db7935
......@@ -48,6 +48,31 @@ namespace COSSnippet
}
}
/// <summary>
/// 文件是否存在
/// </summary>
/// <param name="AliFileName"></param>
public bool SelectFile(string AliFileName) {
// 创建OssClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// 判断文件是否存在。
var exist = client.DoesObjectExist(bucketName, AliFileName);
return exist;
}
catch (Aliyun.OSS.Common.OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
return false;
}
/// <summary>
/// 删除文件
/// </summary>
......
......@@ -19,7 +19,7 @@ namespace Mall.Education
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new RebornTimerServer(),
new EducationToImageServer(),
};
ServiceBase.Run(ServicesToRun);
//Console.WriteLine("进来了");
......
......@@ -39,8 +39,8 @@
//
// serviceInstaller1
//
this.serviceInstaller1.Description = "RebornTimerService定时器服务";
this.serviceInstaller1.ServiceName = "RebornTimerServer";
this.serviceInstaller1.Description = "EducationToImageServer服务";
this.serviceInstaller1.ServiceName = "EducationToImageServer";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
......
......@@ -6,6 +6,7 @@ using System.IO;
using System.Drawing;
using Schematrix;
using Mall.Education.Helper;
using System.Net;
namespace Mall.Education.Offices
{
......@@ -39,6 +40,64 @@ namespace Mall.Education.Offices
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, imageFormat, 200, out PageNum);
}
/// <summary>
/// 从网站上下载pdf,转化为字节流
/// </summary>
/// <param name="srcPdfFile">文件地址:'https://******/group2/M00/00/04/wKj-mlpcoZ2IUbK5AACrpaV6k98AAAB6gAAAAAAAKu9562.pdf'</param>
/// <returns></returns>
public static string GetByteByRemoteURL(string srcPdfFile,string fileName)
{
try
{
byte[] arraryByte;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(srcPdfFile);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
StreamReader responseStream = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
int length = (int)wr.ContentLength;
byte[] bs = new byte[length];
HttpWebResponse response = wr as HttpWebResponse;
Stream stream = response.GetResponseStream();
//读取到内存
MemoryStream stmMemory = new MemoryStream();
byte[] buffer1 = new byte[length];
int i;
//将字节逐个放入到Byte 中
while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0)
{
stmMemory.Write(buffer1, 0, i);
}
arraryByte = stmMemory.ToArray();
stmMemory.Close();
}
StreamToFile(arraryByte, fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
return fileName;
}
/// <summary>
/// 流转文件
/// </summary>
/// <param name="arraryByte"></param>
/// <param name="fileName"></param>
public static void StreamToFile(byte[] arraryByte, string fileName)
{
// 把 byte[] 写入文件
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(arraryByte);
bw.Close();
fs.Close();
}
/// <summary>
/// 将Word文档转换为图片的方法
/// </summary>
......@@ -53,6 +112,10 @@ namespace Mall.Education.Offices
PageNum = 0;
try
{
//var localfile = GetByteByRemoteURL(wordInputPath, imageOutputDirPath + Path.GetFileName(wordInputPath));
//if (localfile == "") {
// return;
//}
Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
if (doc == null)
......@@ -126,6 +189,7 @@ namespace Mall.Education.Offices
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
LogHelper.Write(ex, "word转图片");
}
}
......@@ -147,10 +211,10 @@ namespace Mall.Education.Offices
this.cancelled = true;
}
public void ConvertToImage(string originFilePath, string imageOutputDirPath, ImageFormat imageFormat, out int PageNum)
public void ConvertToImage(string originFilePath, string imageOutputDirPath, ImageFormat imageFormat, out int PageNum, bool IsNotLocal = true)
{
this.cancelled = false;
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, imageFormat, 200, out PageNum);
ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, imageFormat, 200, out PageNum, IsNotLocal);
}
/// <summary>
......@@ -161,11 +225,20 @@ 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, ImageFormat imageFormat, int resolution, out int PageNum)
private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution, out int PageNum,bool IsNotLocal = true)
{
PageNum = 0;
try
{
if (IsNotLocal) {
//生成本地文件
var localfile = GetByteByRemoteURL(originFilePath, imageOutputDirPath + Path.GetFileName(originFilePath));
if (localfile == "")
{
return;
}
originFilePath = localfile;
}
Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath);
if (doc == null)
......@@ -211,7 +284,7 @@ namespace Mall.Education.Offices
}
MemoryStream stream = new MemoryStream();
string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + imageFormat.ToString();
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);
......@@ -226,6 +299,9 @@ namespace Mall.Education.Offices
System.Threading.Thread.Sleep(200);
}
if (IsNotLocal) {
File.Delete(originFilePath);
}
if (this.cancelled)
{
return;
......@@ -237,6 +313,64 @@ namespace Mall.Education.Offices
LogHelper.Write(ex, "pdf转图片");
}
}
/// <summary>
/// 从网站上下载pdf,转化为字节流
/// </summary>
/// <param name="srcPdfFile">文件地址:'https://******/group2/M00/00/04/wKj-mlpcoZ2IUbK5AACrpaV6k98AAAB6gAAAAAAAKu9562.pdf'</param>
/// <returns></returns>
public static string GetByteByRemoteURL(string srcPdfFile, string fileName)
{
try
{
byte[] arraryByte;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(srcPdfFile);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
StreamReader responseStream = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
int length = (int)wr.ContentLength;
byte[] bs = new byte[length];
HttpWebResponse response = wr as HttpWebResponse;
Stream stream = response.GetResponseStream();
//读取到内存
MemoryStream stmMemory = new MemoryStream();
byte[] buffer1 = new byte[length];
int i;
//将字节逐个放入到Byte 中
while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0)
{
stmMemory.Write(buffer1, 0, i);
}
arraryByte = stmMemory.ToArray();
stmMemory.Close();
}
StreamToFile(arraryByte, fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
return fileName;
}
/// <summary>
/// 流转文件
/// </summary>
/// <param name="arraryByte"></param>
/// <param name="fileName"></param>
public static void StreamToFile(byte[] arraryByte, string fileName)
{
// 把 byte[] 写入文件
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(arraryByte);
bw.Close();
fs.Close();
}
}
#endregion
......@@ -271,7 +405,13 @@ namespace Mall.Education.Offices
PageNum = 0;
try
{
Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(originFilePath);
//生成本地文件
var localfile = GetByteByRemoteURL(originFilePath, imageOutputDirPath + Path.GetFileName(originFilePath));
if (localfile == "")
{
return;
}
Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(localfile);
if (doc == null)
{
......@@ -280,7 +420,7 @@ namespace Mall.Education.Offices
if (imageOutputDirPath.Trim().Length == 0)
{
imageOutputDirPath = Path.GetDirectoryName(originFilePath);
imageOutputDirPath = Path.GetDirectoryName(localfile);
}
if (!Directory.Exists(imageOutputDirPath))
......@@ -294,15 +434,16 @@ namespace Mall.Education.Offices
}
//先将ppt转换为pdf临时文件
string tmpPdfPath = originFilePath + ".pdf";
string tmpPdfPath = localfile + ".pdf";
doc.Save(tmpPdfPath, Aspose.Slides.Export.SaveFormat.Pdf);
//再将pdf转换为图片
Pdf2ImageConverter converter = new Pdf2ImageConverter();
converter.ConvertToImage(tmpPdfPath, imageOutputDirPath, imageFormat, out PageNum);
converter.ConvertToImage(tmpPdfPath, imageOutputDirPath, imageFormat, out PageNum, false);
//删除pdf临时文件
File.Delete(tmpPdfPath);
File.Delete(localfile);
}
catch (Exception ex)
{
......@@ -311,6 +452,64 @@ namespace Mall.Education.Offices
this.pdf2ImageConverter = null;
}
/// <summary>
/// 从网站上下载pdf,转化为字节流
/// </summary>
/// <param name="srcPdfFile">文件地址:'https://******/group2/M00/00/04/wKj-mlpcoZ2IUbK5AACrpaV6k98AAAB6gAAAAAAAKu9562.pdf'</param>
/// <returns></returns>
public static string GetByteByRemoteURL(string srcPdfFile, string fileName)
{
try
{
byte[] arraryByte;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(srcPdfFile);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
StreamReader responseStream = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
int length = (int)wr.ContentLength;
byte[] bs = new byte[length];
HttpWebResponse response = wr as HttpWebResponse;
Stream stream = response.GetResponseStream();
//读取到内存
MemoryStream stmMemory = new MemoryStream();
byte[] buffer1 = new byte[length];
int i;
//将字节逐个放入到Byte 中
while ((i = stream.Read(buffer1, 0, buffer1.Length)) > 0)
{
stmMemory.Write(buffer1, 0, i);
}
arraryByte = stmMemory.ToArray();
stmMemory.Close();
}
StreamToFile(arraryByte, fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
return fileName;
}
/// <summary>
/// 流转文件
/// </summary>
/// <param name="arraryByte"></param>
/// <param name="fileName"></param>
public static void StreamToFile(byte[] arraryByte, string fileName)
{
// 把 byte[] 写入文件
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(arraryByte);
bw.Close();
fs.Close();
}
}
#endregion
......
......@@ -10,6 +10,7 @@ using COSSnippet;
using Mall.Education.Helper;
using System.Collections.Generic;
using FluentScheduler;
using System.Linq;
namespace Mall.Education.RabbitMQ
{
......@@ -128,6 +129,7 @@ namespace Mall.Education.RabbitMQ
if (PageNum > 0)
{
//List<string> DelFile = new List<string>();
List<GoodsImage> goodsImages = new List<GoodsImage>();
//开始上传图片至服务器
if (GoodsModel.PathType == 1)
......@@ -136,7 +138,10 @@ namespace Mall.Education.RabbitMQ
for (var i = 1; i <= PageNum; i++)
{
string newName = FileName + "_" + i.ToString("000") + "." + imageFormat.ToString();
m.TransferUploadFile(tempDir + "/" + newName, FileDirNot + newName);
if (!m.SelectFile(FileDirNot + newName))
{
m.TransferUploadFile(tempDir + "/" + newName, FileDirNot + newName);
}
//上传之后 写入商品课程图片数据
goodsImages.Add(new GoodsImage
......@@ -146,7 +151,8 @@ namespace Mall.Education.RabbitMQ
});
//上传之后 删除本地临时文件
File.Delete(tempDir + "/" + newName);
//File.Delete(tempDir + "/" + newName);
//DelFile.Add(tempDir + "/" + newName);
}
}
else if (GoodsModel.PathType == 2) {
......@@ -154,7 +160,10 @@ namespace Mall.Education.RabbitMQ
for (var i = 1; i <= PageNum; i++)
{
string newName = FileName + "_" + i.ToString("000") + "." + imageFormat.ToString();
upload.TransferUploadFile(tempDir + "/" + newName, FileDirNot + newName);
if (!upload.SelectFile(FileDirNot + newName))
{
upload.TransferUploadFile(tempDir + "/" + newName, FileDirNot + newName);
}
//上传之后 写入商品课程图片数据
goodsImages.Add(new GoodsImage
......@@ -164,7 +173,8 @@ namespace Mall.Education.RabbitMQ
});
//上传之后 删除本地临时文件
File.Delete(tempDir + "/" + newName);
//File.Delete(tempDir + "/" + newName);
//DelFile.Add(tempDir + "/" + newName);
}
}
......@@ -173,6 +183,15 @@ namespace Mall.Education.RabbitMQ
if (flag == false) {
LogHelper.Write("更新课程图片列表失败:CourseId:" + GoodsModel.CourseId);
}
//if (DelFile.Any()) {
// System.Threading.Tasks.Task.Run(() => {
// System.Threading.Thread.Sleep(100000);
// foreach (var item in DelFile) {
// File.Delete(item);
// }
// });
//}
}
}
}
......@@ -198,7 +217,7 @@ namespace Mall.Education.RabbitMQ
{
LogHelper.Write(ex, "DelTemporaryFile");
}
}).ToRunEvery(1).Days().At(1, 10);
}).ToRunNow().AndEvery(1).Hours();
}
......@@ -219,7 +238,7 @@ namespace Mall.Education.RabbitMQ
}
foreach (FileInfo fi in dir.GetFiles())
{
if (fi.CreationTime < DateTime.Now.AddDays(-1))
if (fi.CreationTime < DateTime.Now.AddHours(-1))
fi.Delete();
}
}
......
namespace Mall.Education
{
partial class RebornTimerServer
partial class EducationToImageServer
{
/// <summary>
/// 必需的设计器变量。
......@@ -29,7 +29,7 @@
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "RebornTimerServer";
this.ServiceName = "EducationToImageServer";
}
#endregion
......
......@@ -12,9 +12,9 @@ using System.Threading.Tasks;
namespace Mall.Education
{
partial class RebornTimerServer : ServiceBase
partial class EducationToImageServer : ServiceBase
{
public RebornTimerServer()
public EducationToImageServer()
{
InitializeComponent();
}
......
......@@ -118,6 +118,87 @@ namespace COSSnippet
//.cssg-snippet-body-end
}
/// <summary>
/// 查询文件
/// </summary>
/// <param name="cosFileName"></param>
public bool SelectFile(string cosFileName) {
try
{
string bucket = bucketName; //存储桶,格式:BucketName-APPID
string key = cosFileName; //对象键
HeadObjectRequest request = new HeadObjectRequest(bucket, key);
//执行请求
HeadObjectResult result = cosXml.HeadObject(request);
//请求成功
Console.WriteLine(result.GetResultInfo());
LogHelper.Write(result.GetResultInfo());
if (result.GetResultInfo().Contains("200 OK"))
{
return true;
}
else {
return false;
}
}
catch (COSXML.CosException.CosClientException clientEx)
{
//请求失败
Console.WriteLine("CosClientException: " + clientEx);
}
catch (COSXML.CosException.CosServerException serverEx)
{
//请求失败
Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}
return false;
}
/// 高级接口下载对象
public void TransferDownloadObject(string filePath,string fileName, string cosPathName)
{
//.cssg-snippet-body-start:[transfer-download-object]
// 初始化 TransferConfig
TransferConfig transferConfig = new TransferConfig();
// 初始化 TransferManager
TransferManager transferManager = new TransferManager(cosXml, transferConfig);
String bucket = bucketName; //存储桶,格式:BucketName-APPID
String cosPath = cosPathName; //对象在存储桶中的位置标识符,即称对象键
string localDir = filePath;//本地文件夹
string localFileName = fileName; //指定本地保存的文件名
// 下载对象
COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(bucket, cosPath,
localDir, localFileName);
downloadTask.progressCallback = delegate (long completed, long total)
{
Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
};
downloadTask.successCallback = delegate (CosResult cosResult)
{
COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult result = cosResult
as COSXML.Transfer.COSXMLDownloadTask.DownloadTaskResult;
Console.WriteLine(result.GetResultInfo());
string eTag = result.eTag;
};
downloadTask.failCallback = delegate (CosClientException clientEx, CosServerException serverEx)
{
if (clientEx != null)
{
Console.WriteLine("CosClientException: " + clientEx);
}
if (serverEx != null)
{
Console.WriteLine("CosServerException: " + serverEx.GetInfo());
}
};
transferManager.Download(downloadTask);
//.cssg-snippet-body-end
}
/// 高级接口上传二进制数据
public void TransferUploadBytes()
{
......
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