m0_73740280 2023-07-26 15:23 采纳率: 86.8%
浏览 3

这个c#程序如何显示XML文件中的图片

请问调用这个XMLToolstripClick方法为什么创建成功的XML文件无法显示插入的图片

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Markup;
using System.Xml;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.xmp.impl.xpath;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Web;
using System.Web.Script.Serialization;
using Image = System.Drawing.Image;
using System.Drawing.Imaging;
//using Image = System;

namespace demo04
{
    public partial class FrmChild : Form
    {
        public FrmChild formRichText;
        public string path;
        public FrmChild()
        {
            InitializeComponent();
        }

        private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmChild new_frmchild=new FrmChild();
            new_frmchild.MdiParent=this.MdiParent;
            new_frmchild.Text = "";
            new_frmchild.Show();
            new_frmchild.Activate();
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = ("文本文档(*.txt)|*.txt");
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                path=openFileDialog1.FileName;
                StreamReader sr= new StreamReader(path,Encoding.UTF8);
                string text=sr.ReadToEnd();
                richTextBox1.Text = text;
                this.Text=path;
                lblMark.Text = "";
                sr.Close();
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(this.Text=="")
            {
                saveFileDialog1.Filter = ("文本文档(*.txt)|*.txt");
                if(saveFileDialog1.ShowDialog()==DialogResult.OK)
                {
                    string path = saveFileDialog1.FileName;
                    StreamWriter sw = new StreamWriter(path,false);
                    sw.WriteLine(richTextBox1.Text);
                    sw.Flush();
                    sw.Close();
                    this.Text = path;
                }
            }
            else
            {
                string path = this.Text;
                StreamWriter sw = new StreamWriter(path, false);
                sw.WriteLine(richTextBox1.Text);
                sw.Flush();
                sw.Close();

            }
            lblMark.Text = "";
            MessageBox.Show("文档保存成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }

        private void 剪切ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        private void 复制ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

        private void 粘贴ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要关闭当前文档吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                this.Close();
        }

        private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FontDialog fontDialog= new FontDialog();
            fontDialog.ShowColor= true;
            fontDialog.Font = richTextBox1.SelectionFont;
            fontDialog.Color= richTextBox1.SelectionColor;
            if(fontDialog.ShowDialog() != DialogResult.Cancel)
            { 
                richTextBox1.SelectionFont= fontDialog.Font;
                richTextBox1.SelectionColor= fontDialog.Color;
            }

        }

        private void 字体ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FontDialog fontDialog = new FontDialog();
            fontDialog.ShowColor = true;
            fontDialog.Font = richTextBox1.SelectionFont;
            fontDialog.Color = richTextBox1.SelectionColor;
            if (fontDialog.ShowDialog() != DialogResult.Cancel)
            {
                richTextBox1.SelectionFont = fontDialog.Font;
                richTextBox1.SelectionColor = fontDialog.Color;
            }
        }

        private void FrmChild_Load(object sender, EventArgs e)
        {
            
        }

        private void 查找与替换ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            formRichText = this;
            FrmFindReplace formFind = new FrmFindReplace(formRichText);
            formFind.Show();
        }

        private void txtTotalCount_TextChanged(object sender, EventArgs e)
        {
            txtTotalCount.Text = Convert.ToString(richTextBox1.Text.Replace("\n","").Replace(" ","").Length);
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            lblMark.Text = "*";
            txtTotalCount_TextChanged(sender,e);
            txtChcCount_TextChanged(sender,e);
            txtSpaceCount_TextChanged(sender,e);
            //if(richTextBox1.getindex)

        }

        private void txtChcCount_TextChanged(object sender, EventArgs e)
        {
            txtChcCount.Text = Convert.ToString(ChNum_Count());
        }

        private int ChNum_Count()
        {
            int ch_num = 0;
            char[] ch = richTextBox1.Text.ToArray();
            foreach(char i in ch)
            {
                if ((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z')) ch_num++;
            }
            return ch_num;
        }

        private void txtSpaceCount_TextChanged(object sender, EventArgs e)
        {
            txtSpaceCount.Text=Convert.ToString(Space_Count());
        }

        private int Space_Count()
        {
            int space_num = 0;
            char[] ch = richTextBox1.Text.ToArray();
            foreach (char i in ch)
            {
                if (i == ' ') space_num++;
            }
            return space_num;

        }


        private void menuStrip2_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void FrmChild_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(lblMark.Text=="*")
            {
                DialogResult dr = MessageBox.Show("文件尚未保存,是否继续关闭?","信息询问",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                if(dr==System.Windows.Forms.DialogResult.Yes)
                {
                    this.Dispose();
                }
                else
                {
                    e.Cancel= true;
                }
            }
        }

        private void tXT文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = ("文本文档(*.txt)|*.txt");
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog1.FileName;
                StreamWriter sw = new StreamWriter(path, false);
                sw.WriteLine(richTextBox1.Text);
                sw.Flush();
                sw.Close();
                MessageBox.Show("文件创建成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void pDF文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "PDF文件(*.PDF)|*.PDF";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog.FileName;
                //开始创建PDF文档
                Document document = new Document();
                PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
                document.Open();
                BaseFont baseFont = BaseFont.CreateFont(@"c:\windows\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 20);
                string pathimage = openFileDialog1.FileName;
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(pathimage);
                img.SetAbsolutePosition(0, 0);
                document.Add(new Paragraph(richTextBox1.Text, font));
                document.Add(img);
                document.Close();
                MessageBox.Show("文件创建成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void xML文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = ("XML文件(*.xml)|*.xml");//过滤器
            if(saveFileDialog1.ShowDialog()== DialogResult.OK)
            {
                int index = 0;
                int startindex,endindex;
                string value;
                string path = saveFileDialog1.FileName;
                //输出到xml
                //创建xml文档
                //实例化一个xmldocument类
                XmlDocument xDoc = new XmlDocument();
                //string pathimage = openFileDialog1.FileName;
               // xDoc.Load(Application.StartupPath + "\\pic.xml");
                //声明一个xml所需要的语法的变量,添加在末尾
                XmlDeclaration xmlDeclaration = xDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                //获取richTextBox1的行数
                int lines = richTextBox1.GetLineFromCharIndex(this.richTextBox1.TextLength) + 1;
                //创建根节点
                XmlElement element = xDoc.CreateElement("text");
                //图片流
                /*FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(fs);//二进制读取器
                byte[] imageBuffer = new byte[br.BaseStream.Length];
                br.Read(imageBuffer, 0, Convert.ToInt32(br.BaseStream.Length));
                string textString = System.Convert.ToBase64String(imageBuffer);
                fs.Close();
                br.Close();
                XmlText text = xDoc.CreateTextNode(textString);*/
                //添加根节点到xml文档去
                //MemoryStream ms= new MemoryStream();
                
                xDoc.AppendChild(element);
               // xDoc.DocumentElement.LastChild.AppendChild(text);
                while (index<lines)
                {
                    if (index == lines - 1)
                    {
                        startindex = richTextBox1.GetFirstCharIndexFromLine(index);//第一行
                        value = richTextBox1.Text.Substring(startindex, richTextBox1.Text.Length - startindex);
                    }
                    else
                    {
                        startindex = richTextBox1.GetFirstCharIndexFromLine(index);
                        endindex = richTextBox1.GetFirstCharIndexFromLine(index + 1) - 1;
                        value = richTextBox1.Text.Substring(startindex, endindex - startindex + 1);

                    }
                    //创建、添加子节点
                    XmlElement xmlline = xDoc.CreateElement("line");
                    element.AppendChild(xmlline);
                    xmlline.InnerText = value;
                    index++;
                    //xDoc.DocumentElement.LastChild.AppendChild(text);
                }
                
                /*xDoc.Load(path);
                XmlNodeList NodeList = xDoc.GetElementsByTagName("image");
                XmlNode ImageNode = NodeList[0];

                //var PicByte = ImageNode.InnerXml;
                //byte[] b = Convert.FromBase64String(ImageNode.InnerXml);
                System.IO.MemoryStream ms = new MemoryStream();
                xDoc.Save(ms);
                StreamReader reader = new StreamReader(ms, Encoding.Default);
                reader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str = reader.ReadLine();
                if (str != null)
                {
                    str = reader.ReadToEnd();
                }
                byte[] b = Convert.FromBase64String(str);
                //return str;
                ms.Write(b,0,b.Length);
                ms.Close();
               
                //pictureBox1.Image = Image.FromStream(sm);
                //xDoc.Save(openFileDialog1.FileName);*/
                Image img = Image.FromFile(openFileDialog1.FileName);
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                img.Save(stream, ImageFormat.Jpeg);
                byte[] b = stream.GetBuffer();
                string s = Convert.ToBase64String(b);
                element.AppendChild(xDoc.CreateElement("image"));
                XmlElement elmtData = xDoc.CreateElement("data");
                elmtData.InnerText = s;
                xDoc.DocumentElement.AppendChild(elmtData);
                xDoc.Save(path);
                /*xDoc.Load(path);
                string s1 = xDoc.DocumentElement.SelectSingleNode("data").InnerText;
                byte[] b1 = Convert.FromBase64String(s);
                MemoryStream stream1 = new MemoryStream(b);
                Bitmap bitmap = new Bitmap(stream);
                this.xML文件ToolStripMenuItem.Image=bitmap;*/
                MessageBox.Show("文件创建成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void 图片ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "JPG图片(*.jpg,*.jprg)|*.jpg|BMP图片(*.bmp)|*.bmp|GIF图片(*.gif)|*.gif|PNG图片(*.png)|*.png";
            openFileDialog1.FilterIndex = 0;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect= false;
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = openFileDialog1.FileName;
                System.Drawing.Image img= System.Drawing.Image.FromFile(path);
                Clipboard.SetDataObject(img);
                richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
            }
        }

        private void 表格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmChild tableparent = this;
            FrmTable frmtable = new FrmTable(tableparent);
            frmtable.Show();
        }

        private void 转英文ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string str_trans = richTextBox1.SelectedText;
            string from = "auto";
            string to = "en";
            TranslationResult result = GetTranslationFromBaiduFanyi(str_trans, from, to);
            if(result.Error_code == null)
            {
                richTextBox1.SelectedText = result.Trans_result[0].Dst;
            }
            else
            {
                MessageBox.Show("翻译出错,错误码:"+result.Error_code+",错误信息:"+result.Error_msg,"发生错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void 转中文ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string str_trans = richTextBox1.SelectedText;
            string from = "auto";
            string to = "zh";
            TranslationResult result = GetTranslationFromBaiduFanyi(str_trans, from, to);
            if (result.Error_code == null)
            {
                richTextBox1.SelectedText = result.Trans_result[0].Dst;
            }
            else
            {
                MessageBox.Show("翻译出错,错误码:" + result.Error_code + ",错误信息:" + result.Error_msg, "发生错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public class Translation
        {
            public string Src { get; set; }
            public string Dst { get; set; }
        }

        public class TranslationResult
        {
            //错误码,翻译结果无法正常返回
            public string Error_code { get; set; }
            public string Error_msg { get; set; }
            public string From { get; set; }
            public string To { get; set; }
            public string Query { get; set; }
            //翻译正确,返回的结果
            //这里是数组的原因是百度翻译支持多个单词或多段文本的翻译,在发送的字段q中用换行符(\n)分隔
            public Translation[] Trans_result { get; set; }
        }

        //对字符串做md5加密
        private static string GetMD5WithString(string input)
        {
            if (input == null)
            {
                return null;
            }
            MD5 md5Hash = MD5.Create();
            //将输入字符串转换为字节数组并计算哈希数据  
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            //创建一个 Stringbuilder 来收集字节并创建字符串  
            StringBuilder sBuilder = new StringBuilder();
            //循环遍历哈希数据的每一个字节并格式化为十六进制字符串  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            //返回十六进制字符串  
            return sBuilder.ToString();
        }

        private static TranslationResult GetTranslationFromBaiduFanyi(string q, string from, string to)
        {
            //可以直接到百度翻译API的官网申请
            //一定要去申请,不然程序的翻译功能不能使用
            string appId = "20230722001753684";
            string password = "H5DPOrqMaxzLHEPhtOqo";

            string jsonResult = String.Empty;
            //源语言
            string languageFrom = from.ToString().ToLower();
            //目标语言
            string languageTo = to.ToString().ToLower();
            //随机数
            string randomNum = System.DateTime.Now.Millisecond.ToString();
            //md5加密
            string md5Sign = GetMD5WithString(appId + q + randomNum + password);
            //url
            string url = String.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}",
                HttpUtility.UrlEncode(q, Encoding.UTF8),
                languageFrom,
                languageTo,
                appId,
                randomNum,
                md5Sign
                );
            WebClient wc = new WebClient();
            try
            {
                jsonResult = wc.DownloadString(url);
            }
            catch
            {
                jsonResult = string.Empty;
            }
            //解析json
            JavaScriptSerializer jss = new JavaScriptSerializer();
            TranslationResult result = jss.Deserialize<TranslationResult>(jsonResult);
            return result;
        }
    }
}


  • 写回答

2条回答 默认 最新

  • threenewbee 2023-07-26 15:35
    关注

    System.Drawing.Image img= System.Drawing.Image.FromFile(path);
    Clipboard.SetDataObject(img);
    richTextBox1.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
    这个代码的思路是将你选择的图片加载到剪贴板
    再粘贴
    你依次检查:
    (1)你首先检查调用之后粘贴图片到word或者什么地方,有没有图片,如果没有,说明剪贴板是空的
    (2)检查Clipboard.SetDataObject(img);这里下断点,看看图片对象是不是有效,如果不是就是前面一行Image格式不对
    (3)单独调用最后一行,看能不能粘贴上,如果可以,说明你的SetDataObject这个数据剪贴板不识别

    评论

报告相同问题?

问题事件

  • 创建了问题 7月26日

悬赏问题

  • ¥20 macmin m 4连接iPad
  • ¥15 DBIF_REPO_SQL_ERROR
  • ¥15 根据历年月数据,用Stata预测未来六个月汇率
  • ¥15 DevEco studio开发工具 真机联调找不到手机设备
  • ¥15 请教前后端分离的问题
  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
  • ¥15 霍尔传感器hmc5883l的xyz轴输出和该点的磁感应强度大小的关系是什么
  • ¥15 vscode开发micropython,import模块出现异常