您的位置:首页 > 其它

生成image类,video,pdf提取图像

2012-11-07 14:17 162 查看
/// <summary>
/// 取得缩略图
/// </summary>
/// <param name="sourceImg"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static System.Drawing.Image GetThumb(System.Drawing.Image sourceImg, int width, int height)
{
System.Drawing.Image targetImg = new Bitmap(width, height);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(targetImg))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.White);
g.DrawImage(sourceImg, new Rectangle(0, 0, width, height), new Rectangle(0, 0, sourceImg.Width, sourceImg.Height), GraphicsUnit.Pixel);
g.Dispose();
}

return targetImg;
}
//#region pdf截图

///// <summary>
/////
///// </summary>
///// <param name="pdfFilePath"></param>
///// <param name="imgOutPath"></param>
///// <returns></returns>//这个在xp,win7可以用,但是在win2003下报访问剪切板失败的异常,求解
//public static string ConvertPdf2Image(string pdfFilePath, string imgOutPath)
//{
//    if (!System.IO.File.Exists(pdfFilePath))
//    {
//        return string.Empty;
//    }
//    string msg = string.Empty;
//    try
//    {
//        ConvertPdf2Image(pdfFilePath, imgOutPath, 0, 1, null, 1);
//        if (System.IO.File.Exists(imgOutPath))
//        {
//            return imgOutPath;
//        }
//        else
//            return string.Empty;
//    }
//    catch (System.Exception ex)
//    {
//
//        return string.Empty;
//    }

//}
/////// <summary>
/////// pdf转image缩略图
/////// </summary>
/////// <param name="pdfFilePath"></param>
/////// <param name="imageDirectoryPath"></param>
/////// <param name="beginPageNum"></param>
/////// <param name="endPageNum"></param>
/////// <param name="format"></param>
/////// <param name="zoom"></param>//安装Acrobat软件100多M大小
////public static void ConvertPdf2Image(string pdfFilePath, string imageDirectoryPath, int beginPageNum, int endPageNum, ImageFormat format, double zoom)
////{
////    if (!System.IO.File.Exists(pdfFilePath))
////    {
////        return;
////    }
////    zoom = 1;
////    Acrobat.CAcroPDDoc pdfDoc = null;
////    Acrobat.CAcroPDPage pdfPage = null;
////    Acrobat.CAcroRect pdfRect = null;
////    Acrobat.CAcroPoint pdfPoint = null;

////    //生成操作Pdf文件的Com对象
////    //            pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");
////    var CreatePdf = Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");
////    pdfDoc = (Acrobat.CAcroPDDoc)CreatePdf;

////    //检查输入参数
////    if (!pdfDoc.Open(pdfFilePath))
////    {
////        throw new FileNotFoundException(string.Format("源文件{0}不存在!", pdfFilePath));
////    }
////    string dir = System.IO.Path.GetDirectoryName(imageDirectoryPath);
////    if (!Directory.Exists(dir))
////    {
////        Directory.CreateDirectory(dir);
////    }

////    if (beginPageNum <= 0)
////    {
////        beginPageNum = 1;
////    }

////    if (endPageNum > pdfDoc.GetNumPages() || endPageNum <= 0)
////    {
////        endPageNum = pdfDoc.GetNumPages();
////    }

////    if (beginPageNum > endPageNum)
////    {
////        throw new ArgumentException("参数\"beginPageNum\"必须小于\"endPageNum\"!");
////    }

////    if (format == null)
////    {
////        format = ImageFormat.Jpeg;
////    }

////    if (zoom <= 0)
////    {
////        zoom = 1;
////    }

////    //转换
////    for (int i = beginPageNum; i <= endPageNum; i++)
////    {
////        //取出当前页
////        pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i - 1);
////        //得到当前页的大小
////        pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();
////        //生成一个页的裁剪区矩形对象
////        pdfRect = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");

////        //计算当前页经缩放后的实际宽度和高度,zoom==1时,保持原比例大小
////        int imgWidth = (int)((double)pdfPoint.x * zoom);
////        int imgHeight = (int)((double)pdfPoint.y * zoom);

////        //设置裁剪矩形的大小为当前页的大小
////        pdfRect.Left = 0;
////        pdfRect.right = (short)imgWidth;
////        pdfRect.Top = 0;
////        pdfRect.bottom = (short)imgHeight;

////        //将当前页的裁剪区的内容编成图片后复制到剪贴板中
////        Thread cbThread = new Thread(new ThreadStart(delegate
////        {
////            try
////            {
////                Clipboard.Clear();
////                pdfPage.CopyToClipboard(pdfRect, 0, 0, (short)(100 * zoom));
////                IDataObject clipboardData = Clipboard.GetDataObject();
////                //检查剪贴板中的对象是否是图片,如果是图片则将其保存为指定格式的图片文件
////                if (clipboardData.GetDataPresent(DataFormats.Bitmap))
////                {

////                    Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);
////                    pdfBitmap.Save(imageDirectoryPath,ImageFormat.Jpeg);
////                    pdfBitmap.Dispose();
////                }
////                //System.Drawing.Image img = GetThumb(Clipboard.GetImage(), 200, 150);
////                //if (img != null)
////                //{
////                //    img.Save(imageDirectoryPath);
////                //}
////            }
////            catch (System.Exception ex)
////            {
////
////            }

////        }));
////        cbThread.ApartmentState = ApartmentState.STA;//在老外那里看到asp.net不正常,用这个方法解决这个问题
////        cbThread.Start();
////        cbThread.Join();
////    }

////    //关闭和释放相关COM对象
////    pdfDoc.Close();
////    Marshal.ReleaseComObject(pdfRect);
////    Marshal.ReleaseComObject(pdfPoint);
////    Marshal.ReleaseComObject(pdfPage);
////    Marshal.ReleaseComObject(pdfDoc);

////}
//#endregion

#region 视频格式mp4,3gp,flv截图。注意swf除外
/// <summary>
/// 视频格式mp4,3gp,flv截图。注意swf除外
/// </summary>
/// <param name="vFileName"></param>
/// <param name="outImgPath"></param>
/// <returns></returns>
public static string ConvertVideo2Image(string vFileName, string outImgPath)
{
int[] size = WebConfiguration.ConverterSetting.GetThumbSize();
return ConvertVideo2Image( vFileName, outImgPath,size[0],size[1]);
}
/// <summary>
/// 视频格式mp4,3gp,flv截图。注意swf除外
/// </summary>
/// <param name="vFileName"></param>
/// <param name="outImgPath"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public  static string ConvertVideo2Image(string vFileName,string outImgPath,int width,int height)
{
//取得ffmpeg.exe的路径,路径配置在Web.Config中,如:<add key="ffmpeg" value="E:\ffmpeg\ffmpeg.exe" />
string ffmpeg = WebConfiguration.ConverterSetting.GetFfmpegExePath();// System.Configuration.ConfigurationSettings.AppSettings["ffmpeg"];
if ((!System.IO.File.Exists(ffmpeg)) || (!System.IO.File.Exists(vFileName)))
{
return "error:not find the ffmpeg exe";
}

string flv_img = outImgPath;
//截图的尺寸大小,配置在Web.Config中,如:<add key="CatchFlvImgSize" value="240x180" />
string FlvImgSize = width+"x"+height;
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//此处组合成ffmpeg.exe文件需要的参数即可,此处命令在ffmpeg 0.4.9调试通过
startInfo.Arguments = " -i " + vFileName + " -y -f image2 -t 0.001 -ss 4 -s " + FlvImgSize + " " + outImgPath;
try
{
System.Diagnostics.Process.Start(startInfo);
}
catch
{
return "error:catch";
}
///注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
///这儿需要延时后再检测,我服务器延时8秒,即如果超过8秒图片仍不存在,认为截图失败;
///此处略去延时代码.如有那位知道如何捕捉ffmpeg.exe截图失败消息,请告知,先谢过!
Thread.Sleep(500);
if (System.IO.File.Exists(flv_img))
{
return flv_img;
}
return "error:not create cath img";
}
#endregion

#region pdf提取图像
/// <summary>
/// 从pdf中提取第一页,转为图像
/// </summary>
/// <param name="InputFile"></param>
/// <param name="filename"></param>
/// <returns></returns>
public static string ConvertPdf2Image(string InputPdfFilePath , string OutImgFilePath)
{
string tempImg = System.IO.Path.GetDirectoryName(OutImgFilePath)+"\\" + System.IO.Path.GetFileNameWithoutExtension(OutImgFilePath) + "#temp.jpg";
string msg = ConvertPdf2Image(InputPdfFilePath, false, tempImg, "-dSAFER -dBATCH -dNOPAUSE -r150 -sDEVICE=jpeg -dGraphicsAlphaBits=4 -dFirstPage=1 -dLastPage=1 ");
if (System.IO.File.Exists(tempImg))
{
try
{
int[] size = WebConfiguration.ConverterSetting.GetThumbSize();
BLL.Common.Image.GetThumb(System.Drawing.Image.FromFile(tempImg), size[0], size[1]).Save(OutImgFilePath);
if (System.IO.File.Exists(tempImg))//删除临时文件
{
System.IO.File.Delete(tempImg);
}
}
catch (System.Exception ex)
{
return "error:" + ex.Message;
}

}
if (msg.StartsWith("error"))
{
return msg;
}
else
return OutImgFilePath;
}

private static string ConvertPdf2Image(string InputFile, bool deletePDF, string filename, string Arguments)
{
string msg = string.Empty;
string OutputFile = filename;
string ExtOut = Path.GetExtension(OutputFile);
string partOut = OutputFile.Remove(OutputFile.Length - ExtOut.Length, ExtOut.Length);
ProcessStartInfo info = new ProcessStartInfo();
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.WorkingDirectory = WebConfiguration.ConverterSetting.GetPdf2ImageConverterPath();//System.Configuration.ConfigurationSettings.AppSettings["GhostScriptView"];
info.Arguments = Arguments + @" -sOutputFile=" + OutputFile + "  " + InputFile;
info.FileName = @"gswin32c.exe";//下载gs
Process subProcess = new Process();
subProcess.StartInfo = info;
subProcess.Start();
subProcess.WaitForExit(int.MaxValue);
if (System.IO.File.Exists(filename))
{
return filename;
}

return "error:not create cath img";
}

private int ReadPDFCount(string InputFile)
{
FileStream fs = new FileStream(InputFile, FileMode.Open, FileAccess.Read);
StreamReader r = new StreamReader(fs);
string pdfText = r.ReadToEnd();
// 一旦获取了pdf文本,我们需要做的就是使用正则表达式计算:"/Type /Page" 标记出现的次数。
Regex rx1 = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = rx1.Matches(pdfText);

return Convert.ToInt32(matches.Count);
}
#endregion


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: