文档格式转换 图片详细操作获取编码格式

#region 解析TXT(编码格式为utf-8的TXT)
///
/// 解析TXT(编码格式为utf-8的TXT)
///
///
///
public static void Previewtxtt(System.Web.UI.Page p, string inFilePath)
{
string fileName = inFilePath.Substring(inFilePath.LastIndexOf(’\’) + 1);
p.Response.ContentType = “text/plain;”;
p.Response.Charset = “UTF-8”;
p.Response.ContentEncoding = System.Text.Encoding.UTF8;
p.Response.AddHeader(“content-disposition”, “filename=” + fileName);
p.Response.WriteFile(inFilePath);
p.Response.End();
}
#endregion

#region   解析TXT (编码格式 不是utf-8的格式)
/// <summary>
/// 解析TXT (编码格式 不是utf-8的格式)
/// </summary>
/// <param name="p"></param>
/// <param name="inFilePath"></param>
public static void Previewtxtt2(System.Web.UI.Page p, string inFilePath)
{
    string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + 1);
    p.Response.ContentType = "text/plain;";
    p.Response.ContentEncoding = System.Text.Encoding.UTF8;
    p.Response.AddHeader("content-disposition", "filename=" + fileName);
    p.Response.WriteFile(inFilePath);
    p.Response.End();
}
#endregion

#region  判断文件编码类型 TXT时使用

/// <summary>
/// 给定文件的路径,读取文件的二进制数据,判断文件的编码类型
/// </summary>
/// <param name=“FILE_NAME“>文件路径</param>
/// <returns>文件的编码类型</returns>
public static System.Text.Encoding GetType(string FILE_NAME)
{
    FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
    Encoding r = GetType(fs);
    fs.Close();
    return r;
}
#endregion

#region 判断文件的编码类型

/// <summary>
/// 通过给定的文件流,判断文件的编码类型
/// </summary>
/// <param name=“fs“>文件流</param>
/// <returns>文件的编码类型</returns>
public static System.Text.Encoding GetType(FileStream fs)
{
    byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
    byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
    byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
    Encoding reVal = Encoding.Default;

    BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
    int i;
    int.TryParse(fs.Length.ToString(), out i);
    byte[] ss = r.ReadBytes(i);
    if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
    {
        reVal = Encoding.UTF8;
    }
    else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
    {
        reVal = Encoding.BigEndianUnicode;
    }
    else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
    {
        reVal = Encoding.Unicode;
    }
    r.Close();
    return reVal;

}

#endregion

#region 判断编码格式  TXT预览时使用

/// <summary>
/// 判断是否是不带 BOM 的 UTF8 格式
/// </summary>
/// <param name=“data“></param>
/// <returns></returns>
private static bool IsUTF8Bytes(byte[] data)
{
    int charByteCounter = 1; //计算当前正分析的字符应还有的字节数
    byte curByte; //当前分析的字节.
    for (int i = 0; i < data.Length; i++)
    {
        curByte = data[i];
        if (charByteCounter == 1)
        {
            if (curByte >= 0x80)
            {
                //判断当前
                while (((curByte <<= 1) & 0x80) != 0)
                {
                    charByteCounter++;
                }
                //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X
                if (charByteCounter == 1 || charByteCounter > 6)
                {
                    return false;
                }
            }
        }
        else
        {
            //若是UTF-8 此时第一位必须为1
            if ((curByte & 0xC0) != 0x80)
            {
                return false;
            }
            charByteCounter--;
        }
    }
    if (charByteCounter > 1)
    {
        throw new Exception("非预期的byte格式");
    }
    return true;
}

#endregion

#region  图片合并(上下合并)
public void CombinImage(string sourceImg, string url, string path)
{
    Image imgBack = Image.FromFile(sourceImg);
    Image img2 = Image.FromFile(url);
    if (imgBack.Width > img2.Width)
    {
        Bitmap MyMap = new Bitmap(imgBack.Width, imgBack.Height + img2.Height);//创建了一个宽710,高150画布
        Graphics MyG = Graphics.FromImage(MyMap);
        MyG.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);
        MyG.DrawImage(img2, 0, imgBack.Height, img2.Width, img2.Height);
        //g.DrawImage(img2, 0, imgBack.Height, img2.Width,img2.Height);  上 左   图片宽 图片 高
        MyMap.Save(path);
        GC.Collect();
        imgBack.Dispose();
    }
    else
    {
        Bitmap MyMap = new Bitmap(img2.Width, imgBack.Height + img2.Height);//创建了一个宽710,高150画布
        Graphics MyG = Graphics.FromImage(MyMap);
        MyG.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);
        MyG.DrawImage(img2, 0, imgBack.Height, img2.Width, img2.Height);
        //g.DrawImage(img2, 0, imgBack.Height, img2.Width,img2.Height);  上 左   图片宽 图片 高
        MyMap.Save(path);
        GC.Collect();
        imgBack.Dispose();
    }

}
#endregion

#region  图片合并

/// <summary>
/// 两张图片合并为一张  左右合并  
/// </summary>
/// <param name="sourceImg">第一张图片 路径</param>
/// <param name="url"> 第二张 图片路径</param>
/// <param name="path">合成后 输出路径</param>

public void CombinImage2(string sourceImg, string url, string path)
{
    Image imgBack = Image.FromFile(sourceImg);
    Image img2 = Image.FromFile(url);
    if (imgBack.Height > img2.Height)
    {
        Bitmap MyMap = new Bitmap(imgBack.Width + img2.Width, imgBack.Height);//创建了一个宽710,高150画布
        Graphics MyG = Graphics.FromImage(MyMap);
        MyG.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);
        MyG.DrawImage(img2, imgBack.Width, 0, img2.Width, img2.Height);
        //g.DrawImage(img2, 0, imgBack.Height, img2.Width,img2.Height);  上 左   图片宽 图片 高
        MyMap.Save(path);
        GC.Collect();
        imgBack.Dispose();
    }
    else
    {
        Bitmap MyMap = new Bitmap(img2.Width + imgBack.Width, img2.Height);//创建了一个宽710,高150画布
        Graphics MyG = Graphics.FromImage(MyMap);
        MyG.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);
        MyG.DrawImage(img2, imgBack.Width, 0, img2.Width, img2.Height);
        //g.DrawImage(img2, 0, imgBack.Height, img2.Width,img2.Height);  上 左   图片宽 图片 高
        MyMap.Save(path);
        GC.Collect();
        imgBack.Dispose();
    }

}
#endregion

#region   文件转为 二进制
/// <summary>
/// 文件转为 二进制
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public static byte[] File2Bytes(string path)
{
    if (!System.IO.File.Exists(path))
    {
        return new byte[0];
    }
    FileInfo fi = new FileInfo(path);
    byte[] buff = new byte[fi.Length];

    FileStream fs = fi.OpenRead();
    fs.Read(buff, 0, Convert.ToInt32(fs.Length));
    fs.Close();
    return buff;
}

#endregion

#region   将Excel转换为Pdf 

/// 将Excel转换为Pdf 
/// </summary>
/// <param name="strFilePath">文件地址</param>
/// <param name="savepath">保存地址</param>
/// <returns></returns>
public bool Excel2Pdf(string fileName, string savepath)
{
    try
    {
        Aspose.Cells.Workbook excel = new Aspose.Cells.Workbook(fileName);
        //将ppt保存到指定路径下 savepath:保存路径
        excel.Save(savepath, Aspose.Cells.SaveFormat.Pdf);
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}
#endregion

#region 将byte数组转换为文件并保存到指定地址

/// <summary>
/// 将byte数组转换为文件并保存到指定地址
/// </summary>
/// <param name="buff">byte数组</param>
/// <param name="savepath">保存地址</param>
public static void Bytes2File(byte[] buff, string savepath)
{
    if (System.IO.File.Exists(savepath))
    {
        System.IO.File.Delete(savepath);
    }
    FileStream fs = new FileStream(savepath, FileMode.CreateNew);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(buff, 0, buff.Length);
    bw.Close();
    fs.Close();
}
#endregion

#region  Word转换为PDF
/// <summary>
/// 将Word转换为Pdf 
/// </summary>
/// <param name="strFilePath">文件地址</param>
/// <param name="savepath">保存地址</param>
/// <returns></returns>
public bool Word2Pdf(string strFilePath, string savepath)
{
    try
    {
        Aspose.Words.Document doc = new Aspose.Words.Document(strFilePath);
        //将Word保存到指定路径下 savepath:保存路径
        doc.Save(savepath, Aspose.Words.SaveFormat.Pdf);
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}
#endregion

#region PDF转换为图片
/// <summary>
/// 转换的图片清晰度,1最不清醒,10最清晰
/// </summary>
public enum Definition
{
    One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10
}
/// <summary>
/// 将1个PDF文档所有页全部转换为图片
/// </summary>
/// <param name="pdfInputPath">PDF文件路径</param>
/// <param name="imageOutputPath">图片输出路径</param>
/// <param name="imageName">生成图片的名字</param>
/// <param name="imageFormat">设置所需图片格式</param>
/// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
public void ConvertAllPDF2Images(string pdfInputPath, string imageOutputPath, string imageName,
ImageFormat imageFormat, Definition definition)
{
    PDFFile pdfFile = PDFFile.Open(pdfInputPath);
    if (!Directory.Exists(imageOutputPath))
    {
        Directory.CreateDirectory(imageOutputPath);
    }
    int startPageNum = 1;
    int endPageNum = pdfFile.PageCount;
    int X = 100;
    int counts = 0;
    for (int i = startPageNum; i <= endPageNum; i++)
    {
        try
        {
            Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition);
            int canKao = pageImage.Width > pageImage.Height ? pageImage.Height : pageImage.Width;
            int newHeight = canKao > 1080 ? pageImage.Height / 2 : pageImage.Height;
            int newWidth = canKao > 1080 ? pageImage.Width / 2 : pageImage.Width;
            Bitmap newPageImage = new Bitmap(newWidth, newHeight);
            X++;
            counts = X - 1;
            string savepaths = imageOutputPath + imageName + X.ToString() + ".Png";
            string savepathsd = imageOutputPath + imageName + "1.Png";
            Graphics g = Graphics.FromImage(newPageImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(pageImage, new Rectangle(0, 0, newWidth, newHeight),
                new Rectangle(0, 0, pageImage.Width, pageImage.Height), GraphicsUnit.Pixel);
            Crop(newPageImage).Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat);
            if (i == 2)
            {
                int count = 1;
                CombinImage2(imageOutputPath + imageName + count.ToString() + ".Png", imageOutputPath + imageName + i.ToString() + ".Png", savepaths);
            }
            if (i > 2)
            {
                CombinImage2(imageOutputPath + imageName + counts.ToString() + ".Png", imageOutputPath + imageName + i.ToString() + ".Png", savepaths);
            }
            if (i == endPageNum && i != 1)
            {
                string s_url = "Tempdate/" + imageName + X.ToString() + ".Png";
                GC.Collect();
                g.Dispose();
                newPageImage.Dispose();
                pageImage.Dispose();
                pdfFile.Dispose();
                Response.Redirect("Default2.aspx?name=" + s_url);
            }
            if (endPageNum == 1)
            {
                string s_url = "Tempdate/" + imageName + "1.Png";
                GC.Collect();
                g.Dispose();
                newPageImage.Dispose();
                pageImage.Dispose();
                pdfFile.Dispose();
                Response.Redirect("Default2.aspx?name=" + s_url);
            }
        }
        catch (Exception ex)
        {

        }
    }
}
#endregion

#region 切掉图片白边
/// <summary>
/// 剪切左右白边
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static Bitmap Crop(Bitmap b)
{
    int x, y;//for use of X,Y Coordinates of pixels
    Color c = new Color(); //pixel color for use of identifying if background
    int intLeft = 0;//furthest left X coordinate
    int intRight = 0;//furthest right X coordinate
    y = 0;
    while (y < b.Height)
    {
        x = 0;
        while (x < b.Width) //loop through pixels on X axis until end of image width
        {
            c = b.GetPixel(x, y); //Get the color of the pixel
            if (c.R != 255 && c.R != 0 && c.G != 255 && c.G != 0 && c.B != 255 && c.B != 0)
            {
                if (c.R < 240 || c.G < 240 || c.B < 240)
                {
                    //Determine if pixel is further left than the value we already have
                    if (intLeft == 0 || intLeft > x)
                    {
                        intLeft = x;
                    }
                    //Determine if pixel is further right than the value we already have
                    if (intRight <= b.Width && intRight < x)
                    {
                        intRight = x;
                    }
                }
            }
            x += 1;
        }
        y += 1;
    }
    Bitmap imgCropped = new Bitmap(b.Width - intLeft - (b.Width - intRight), b.Height);
    Graphics objGraphics = Graphics.FromImage(imgCropped);
    objGraphics.Clear(System.Drawing.Color.Transparent);
    RectangleF imagerec = new RectangleF(intLeft, 0, b.Width - intLeft - (b.Width - intRight), b.Height);   //  尺寸 获取白边的尺寸后 去除尺寸
    objGraphics.DrawImage(b, new Rectangle(0, 0, b.Width - intLeft - (b.Width - intRight), b.Height), imagerec, GraphicsUnit.Pixel);
    b.Dispose();
    objGraphics.Dispose();   //  释放资源 
    return imgCropped;  //返回画布
}
#endregion
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值