C# 批量图片合并 图片保存为PDF

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PictureTurnPdf
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

   
        private void FrmMain_Load(object sender, EventArgs e)
        {
            cbPicBrowse.SelectedIndex = 0;
            cbSaveBrowse.SelectedIndex = 0;
        }
           
        #region txtPicBrowse改变事件
        private void txtPicBrowse_TextChanged(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            btnCombine.Enabled = btnTurnPdf.Enabled = false;
            if (txtPicBrowse.Text != "")
            {
                DirectoryInfo TheFolder1 = new DirectoryInfo(txtPicBrowse.Text);
                foreach (FileInfo NextFile in TheFolder1.GetFiles(cbPicBrowse.Text))
                    this.listBox1.Items.Add(NextFile.Name);
                label6.Text = string.Format("共:{0} 个文件", listBox1.Items.Count);
                if (listBox1.Items.Count >= 2 && txtSavePath.Text != "")
                    btnCombine.Enabled = btnTurnPdf.Enabled = true;
                else
                    btnCombine.Enabled = btnTurnPdf.Enabled = false;
            }
        } 
        #endregion

        #region cbPicBrowse改变事件
        private void cbPicBrowse_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbSaveBrowse.SelectedIndex = cbPicBrowse.SelectedIndex;
        } 
        #endregion

        #region 合并图片选择按钮
        private void btnPicBrowse_Click(object sender, EventArgs e)
        {
            txtPicBrowse.Text = GetButton_Click(sender);
        }
        /// <summary>
        /// 根据按钮获取对应选择路径
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        public string GetButton_Click(object sender)
        {
            string sPath = "";
            switch (((Button)sender).Name)
            {
                case "btnPicBrowse":
                    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                    {
                        sPath = folderBrowserDialog1.SelectedPath.ToString();
                    }
                    break;
                case "btnSaveBrowse":
                    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                    {
                        sPath = folderBrowserDialog1.SelectedPath.ToString();
                    }
                    break;
            }
            return sPath;
        }
        #endregion

        #region txtSavePath改变事件
        private void txtSavePath_TextChanged(object sender, EventArgs e)
        {
            if (listBox1.Items.Count >= 2 && txtSavePath.Text != "")
                btnCombine.Enabled = btnTurnPdf.Enabled = true;
            else
                btnCombine.Enabled = btnTurnPdf.Enabled = false;
        } 
        #endregion

        #region 合并的路径选择按钮
        private void btnSaveBrowse_Click(object sender, EventArgs e)
        {
            txtSavePath.Text = GetButton_Click(sender);
        } 
        #endregion

        #region 开始合并按钮
        private void btnCombine_Click(object sender, EventArgs e)
        {
            try
            {
                cbPicBrowse.Enabled = false;
                cbSaveBrowse.Enabled = false;
                btnPicBrowse.Enabled = false;
                btnSaveBrowse.Enabled = false;
                btnCombine.Enabled = btnTurnPdf.Enabled = false;
                numUdown.Enabled = false;
                rbtn1.Enabled = false;
                rbtn2.Enabled = false;
                Bitmap[] bit = new Bitmap[(int)numUdown.Value];
                int j = 0;
                pBar.Maximum = listBox1.Items.Count;
                pBar.Value = 0;
                for (int i = 1; i < listBox1.Items.Count + 1; i++)
                {
                    string imgstr = listBox1.Items[i - 1].ToString();
                    bit[j] = new Bitmap(txtPicBrowse.Text + "\\" + imgstr);
                    j++;
                    if (i % (int)numUdown.Value == 0)
                    {
                        j = 0;
                        string str;
                        str = txtSavePath.Text + "\\temp" + ((int)(i / (int)numUdown.Value)).ToString() + cbSaveBrowse.Text;
                        if (this.cbSaveBrowse.SelectedIndex == 0)
                        {
                            MergerImg(bit).Save(str, System.Drawing.Imaging.ImageFormat.Bmp);
                        }
                        else
                        {
                            MergerImg(bit).Save(str, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                    if (pBar.Value < pBar.Maximum)
                        pBar.Value += 1;
                    labSchedule.Text = ((pBar.Value * 100) / (pBar.Maximum)).ToString() + " %";
                    Application.DoEvents();
                }
                MessageBox.Show("合并完成!", "提示", MessageBoxButtons.OK);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            finally
            {
                cbPicBrowse.Enabled = true;
                cbSaveBrowse.Enabled = true;
                btnPicBrowse.Enabled = true;
                btnSaveBrowse.Enabled = true;
                btnCombine.Enabled = btnTurnPdf.Enabled = true;
                numUdown.Enabled = true;
                rbtn1.Enabled = true;
                rbtn2.Enabled = true;
            }
        }
        /// <summary>
        /// 合并方法
        /// </summary>
        /// <param name="maps"></param>
        /// <returns></returns>
        private Bitmap MergerImg(params Bitmap[] maps)
        {
            int X = 0;
            int Y = 0;
            Bitmap newImg;
            for (int i = 0; i < maps.Length; i++)
            {
                //X = X > maps[i].Width ? X : maps[i].Width;
                //Y += maps[i].Height;
                //增加合并图片之间的距离
                X = X > maps[i].Width ? X + 300 : maps[i].Width + 300;
                Y += maps[i].Height + 200;
            }
            newImg = new Bitmap(X, Y);
            X = 0;
            Y = 0;
            Graphics g = Graphics.FromImage(newImg);
            g.Clear(System.Drawing.Color.White);
            for (int i = 0; i < maps.Length; i++)
            {
                g.DrawImage(maps[i], X, Y, maps[i].Width, maps[i].Height);
                Y += maps[i].Height;


            }
            g.Dispose();
            return newImg;
        }
        #endregion

        #region 图片转PDF按钮
        private void btnTurnPdf_Click(object sender, EventArgs e)
        {
            string[] files =new string[listBox1.Items.Count];   
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                string imgstr = listBox1.Items[i].ToString();
                files[i] = txtPicBrowse.Text + "\\" + imgstr;   
            } 
           
            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
            try
            {
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(txtSavePath.Text + "\\save.pdf", FileMode.Create, FileAccess.ReadWrite));
                document.Open();
                iTextSharp.text.Image image;
                for (int i = 0; i < files.Length; i++)
                {
                    if (String.IsNullOrEmpty(files[i])) break;


                    image = iTextSharp.text.Image.GetInstance(files[i]);


                    if (image.Height > iTextSharp.text.PageSize.A4.Height - 25)
                    {
                        image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                    }
                    else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
                    {
                        image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                    }
                    image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
                    document.NewPage();
                    document.Add(image);
                    //iTextSharp.text.Chunk c1 = new iTextSharp.text.Chunk("Hello World");
                    //iTextSharp.text.Phrase p1 = new iTextSharp.text.Phrase();
                    //p1.Leading = 150;      //行间距
                    //document.Add(p1);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("转换失败,原因:" + ex.Message);
            }
            document.Close();
        } 
        #endregion
    
    }
}
软件截图
​​

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用.NET Framework中的System.Drawing命名空间来进行图片压缩操作。以下是一个示例代码,可以将指定目录下的所有图片进行批量压缩并保存到指定目录中: ```csharp using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace ImageCompression { class Program { static void Main(string[] args) { // 指定原始图片目录和压缩后保存的目录 string sourceDir = @"C:\source"; string targetDir = @"C:\target"; // 获取原始图片目录中的所有图片文件 string[] imageFiles = Directory.GetFiles(sourceDir, "*.jpg"); // 遍历每个图片文件,并进行压缩 foreach (string imagePath in imageFiles) { // 加载图片 using (Bitmap image = new Bitmap(imagePath)) { // 定义压缩后的宽度和高度 int targetWidth = 800; int targetHeight = (int)(image.Height * ((float)targetWidth / image.Width)); // 创建一个新的位图,并设置宽度和高度 Bitmap targetImage = new Bitmap(targetWidth, targetHeight); // 创建一个Graphics对象,并将原始图片绘制到新位图中 using (Graphics graphics = Graphics.FromImage(targetImage)) { graphics.DrawImage(image, new Rectangle(0, 0, targetWidth, targetHeight)); } // 定义压缩后的图片保存路径,并保存图片 string targetPath = Path.Combine(targetDir, Path.GetFileName(imagePath)); targetImage.Save(targetPath, ImageFormat.Jpeg); } } } } } ``` 在上述示例代码中,我们定义了一个源图片目录和一个目标保存目录,并使用`Directory.GetFiles`方法获取源目录中的所有`.jpg`文件。然后,我们遍历每个图片文件,并使用`Bitmap`类加载原始图片。接着,我们计算压缩后的图片宽度和高度,并使用`Graphics`对象将原始图片绘制到新位图中。最后,我们将压缩后的图片保存到目标目录中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zero-To-One

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值