使用Winforms将位图图像另存为.JPG时,如何防止图像质量下降

时间:2017-10-24 02:11:44

标签: c# .net winforms bitmap picturebox

我是一名使用C#Winforms在GUI上工作的学生,用户可以在其上加载图像,在其上绘画,然后将编辑后的图像保存到他的系统中。

Bitmap b = new Bitmap(imgList);
            image.DrawImage(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawImage(btm, Point.Empty);

我的问题是,当我从图片框中保存已编辑的图像时,它的质量会降低,并且它的高度与图片框的高度相同。我已在下面提供了我的Form.cs以供参考。有什么办法可以让编辑过的图像保持原始图像的图像质量吗?

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SIP_UI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            imagelst = new ImageList();
        }

        //Declared Variables
        private Graphics g;

        private Graphics image;
        private Bitmap btm;
        private SolidBrush c;
        private bool drawing = false;
        private ImageList imagelst;
        private string[] imglst;
        private int imgCnt = 1;

        private bool saveNxtWasClicked = false;

        private bool savePrevWasClicked = false;

        private void Form1_Load(object sender, EventArgs e)
        {
            g = pictureBox1.CreateGraphics();
            btm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            image = Graphics.FromImage(btm);
            image.Clear(Color.White);

            //Status color on default load
            pnlStatus.BackColor = Color.DarkGray;

            chkbxImageInfo.Checked = false;
            if (chkbxImageInfo.Checked == false)
            {
                txtTestRep.Enabled = false;
                txtBoard.Enabled = false;
                cmbxPosition.Enabled = false;
            }

            btnNext.Enabled = true;
            btnPrev.Enabled = false;

            txtImgNum.Text = "0";
            lblTotl.Text = "#";

            using (StreamReader streamReaderOpen = new StreamReader("OpenLocation.txt"))
            {
                string strOpen = streamReaderOpen.ReadLine();
                //Check path validity
                if (System.IO.Directory.Exists(strOpen))
                {
                    txtOpnPath.Text = strOpen;
                }
                else
                {
                    txtOpnPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                }
            }
            using (StreamReader streamReaderSave = new StreamReader("SaveLocation.txt"))
            {
                string strSave = streamReaderSave.ReadLine();
                //Check path validity
                if (System.IO.Directory.Exists(strSave))
                {
                    txtSavPath.Text = strSave;
                }
                else
                {
                    txtSavPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                }
            }
            using (StreamReader streamReaderCsv = new StreamReader("CsvLocation.txt"))
            {
                string strCsv = streamReaderCsv.ReadLine();
                //Check path validity
                if (System.IO.Directory.Exists(strCsv))
                {
                    txtCsvPath.Text = strCsv;
                }
                else
                {
                    txtCsvPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                }
            }

            //Open images from previous folder
            if (txtOpnPath.Text.Length > 0)
            {
                int i = 0;
                int numImgs = Directory.GetFiles(txtOpnPath.Text, "*.PNG").Length;
                imglst = new string[numImgs];
                lblTotl.Text = Convert.ToString(numImgs);
                txtImgNum.Text = Convert.ToString(1);
                //foreach (var file in Directory.GetFiles(txtOpnPath.Text).Where(f => extensions.Contains(Path.GetExtension(f).ToUpper())))
                foreach (var file in Directory.GetFiles(txtOpnPath.Text, "*.PNG"))
                {
                    imglst[i++] = file;
                }
                if (imglst.Length > 0)
                {
                    drawImage(imglst[0]);


                    //Added new
                    bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[0]) + "_MSKD*").Any();
                    if (exist)
                    {
                        pnlStatus.BackColor = Color.Red;
                    }
                    else
                    {
                        pnlStatus.BackColor = Color.Green;
                    }
                }
                else
                {
                    MessageBox.Show("SELECT ANOTHER LOCATION", "NO SUPPORTED IMAGES FOUND", MessageBoxButtons.OK);
                    txtImgNum.Text = "0";
                }
            }
        }

        //Function to draw image into picturebox
        private void drawImage(string imgList)
        {
            Bitmap b = new Bitmap(imgList);
            image.DrawImage(b, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawImage(btm, Point.Empty);
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            drawing = false;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            drawing = true;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (drawing)
            {
                c = new SolidBrush(Color.Gray);
                image.FillEllipse(c, e.X - (trackBar1.Value / 2), e.Y - (trackBar1.Value / 2), (trackBar1.Value * 15), (trackBar1.Value * 15));

                g.DrawImage(btm, Point.Empty);
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            btnNext.Enabled = true;
            lblTotl.Text = "#";
            var fd = new System.Windows.Forms.FolderBrowserDialog();
            if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                int i = 0;
                txtOpnPath.Text = fd.SelectedPath;
                int numImgs = Directory.GetFiles(txtOpnPath.Text, "*.PNG").Length;
                imglst = new string[numImgs];
                lblTotl.Text = Convert.ToString(numImgs);
                foreach (var file in Directory.GetFiles(txtOpnPath.Text, "*.PNG"))
                {
                    imglst[i++] = file;
                }
                if (imglst.Length > 0)
                {
                    drawImage(imglst[0]);
                    txtImgNum.Text = "1";

                    //Added new
                    bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[0]) + "_MSKD*").Any();
                    if (exist)
                    {
                        pnlStatus.BackColor = Color.Red;
                    }
                    else
                    {
                        pnlStatus.BackColor = Color.Green;
                    }
                }
                else
                {
                    MessageBox.Show("SELECT ANOTHER LOCATION", "NO SUPPORTED IMAGES FOUND", MessageBoxButtons.OK);
                    pictureBox1.Image = null;
                    txtImgNum.Text = "0";
                }

                using (StreamWriter streamWriter = new StreamWriter("OpenLocation.txt"))
                {
                    streamWriter.WriteLine(txtOpnPath.Text);
                }
            }
        }

        private void btnSaveFdr_Click(object sender, EventArgs e)
        {
            var savFoldr = new System.Windows.Forms.FolderBrowserDialog();
            if (savFoldr.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtSavPath.Text = savFoldr.SelectedPath;

                using (StreamWriter streamWriter = new StreamWriter("SaveLocation.txt"))
                {
                    streamWriter.WriteLine(txtSavPath.Text);
                }
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            saveNxtWasClicked = true;
            savePrevWasClicked = true;

            int count = 1;
            imgCnt = Convert.ToInt32(txtImgNum.Text);
            string imgPath = imglst[imgCnt - 1];
            string fileName = Path.GetFileNameWithoutExtension(imgPath) + "_MSKD";
            string fileExtnsn = Path.GetExtension(imgPath);
            string filePath = txtSavPath.Text + "\\" + fileName + fileExtnsn;
            while (File.Exists(filePath))
            {
                string tempFileName = string.Format("{0}({1})", fileName, count++);
                filePath = Path.Combine(txtSavPath.Text, tempFileName + fileExtnsn);
            }

            btm.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //Writing to CSV
            string csvPath = txtCsvPath.Text + "\\CSVSpec.csv";
            if (chkbxImageInfo.Checked == true)
            {
                if (File.Exists(csvPath))
                {
                    // Initialise stream object with file
                    using (var wr = new StreamWriter(csvPath, true, Encoding.UTF8))
                    {
                        // Collection of image details
                        var row = new List<string>();
                        row.Add(Path.GetFileNameWithoutExtension(imgPath));
                        row.Add(txtTestRep.Text);
                        row.Add(txtBoard.Text);
                        row.Add(cmbxPosition.Text);

                        var sb = new StringBuilder();

                        foreach (string value in row)
                        {
                            // Add a comma before each string

                            if (sb.Length > 0)
                            {
                                sb.Append(",");
                            }
                            sb.Append(value);
                        }
                        wr.WriteLine(sb.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("Please add CSVSpec.csv file in specified location to save Image Information.", "MISSING: TEMPLATE FILE", MessageBoxButtons.OK);
                }
            }
            else
            {
            }

            DialogResult result = MessageBox.Show("IMAGE SAVED", "SAVE DIALOGUE", MessageBoxButtons.OK);
            if (result == DialogResult.OK)
            {
                if (imgCnt != imglst.Length)
                {
                    drawImage(imglst[imgCnt]);
                    imgCnt++;

                    txtImgNum.Text = Convert.ToString(imgCnt);
                    txtTestRep.Text = string.Empty;
                    txtBoard.Text = string.Empty;
                    cmbxPosition.SelectedIndex = 0;

                    saveNxtWasClicked = false;
                }
                else
                {
                    btnNext.Enabled = false;
                }
            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            int a = Convert.ToInt32(txtImgNum.Text);
            btnNext.Enabled = true;

            if (a > 1)
            {
                a = a - 2;
                drawImage(imglst[a]);
                txtImgNum.Text = Convert.ToString(a + 1);

                txtTestRep.Text = string.Empty;
                txtBoard.Text = string.Empty;
                cmbxPosition.SelectedIndex = 0;

                bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[a]) + "_MSKD*").Any();
                if (exist)
                {
                    pnlStatus.BackColor = Color.Red;
                }
                else
                {
                    pnlStatus.BackColor = Color.Green;
                }
            }
            else
            {
                btnPrev.Enabled = false;
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            int a = Convert.ToInt32(txtImgNum.Text);

            btnPrev.Enabled = true;

            if (imglst != null && a < imglst.Length)
            {
                drawImage(imglst[a++]);
                txtImgNum.Text = Convert.ToString(a);

                txtTestRep.Text = string.Empty;
                txtBoard.Text = string.Empty;
                cmbxPosition.SelectedIndex = 0;

                bool exist = Directory.EnumerateFiles(txtSavPath.Text, Path.GetFileNameWithoutExtension(imglst[a - 1]) + "_MSKD*").Any();
                if (exist)
                {
                    pnlStatus.BackColor = Color.Red;
                }
                else
                {
                    pnlStatus.BackColor = Color.Green;
                }
            }

            else
            {
                btnNext.Enabled = false;
            }
        }

        private void txtImgNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                int imgNum = Convert.ToInt32(txtImgNum.Text) - 1;
                drawImage(imglst[imgNum]);
            }
        }

        private void chkbxImageInfo_CheckedChanged(object sender, EventArgs e)
        {
            if (chkbxImageInfo.Checked)
            {
                txtTestRep.Enabled = true;
                txtBoard.Enabled = true;
                cmbxPosition.Enabled = true;
            }
            else
            {
                txtTestRep.Enabled = false;
                txtBoard.Enabled = false;
                cmbxPosition.Enabled = false;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            int imgNum = Convert.ToInt32(txtImgNum.Text) - 1;
            drawImage(imglst[imgNum]);
        }

        private void btnCsv_Click(object sender, EventArgs e)
        {
            var csvFoldr = new System.Windows.Forms.FolderBrowserDialog();
            if (csvFoldr.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtCsvPath.Text = csvFoldr.SelectedPath;

                using (StreamWriter streamWriter = new StreamWriter("CsvLocation.txt"))
                {
                    streamWriter.WriteLine(txtCsvPath.Text);
                }
            }
        }
    }
}

0 个答案:

没有答案