在图片内写入内容

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        string path1 = @"D:\3-153623-C1.jpeg";
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            addImageComment(path1, "胡AAA,SDD2212胡2234火狐");
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string msg = extractComment(path1);
        }

/// <summary>
        /// 字符串转Unicode码
        /// </summary>
        /// <returns>The to unicode.</returns>
        /// <param name="value">Value.</param>
        private string StringToUnicode(string value)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(value);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i += 2)
            {
                // 取两个字符,每个字符都是右对齐。
                stringBuilder.AppendFormat("u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <returns>The to string.</returns>
        /// <param name="unicode">Unicode.</param>
        private string UnicodeToString(string unicode)
        {
            string resultStr = "";
            string[] strList = unicode.Split('u');
 for (int i = 1; i < strList.Length; i++)
            {
                resultStr += (char)int.Parse(strList[i], System.Globalization.NumberStyles.HexNumber);
            }
            return resultStr;
        }
 public void addImageComment(string imageFlePath, string comments)
        {
            string jpegDirectory = System.IO.Path.GetDirectoryName(imageFlePath);
            string jpegFileName = System.IO.Path.GetFileNameWithoutExtension(imageFlePath);
            BitmapDecoder decoder = null;
            BitmapFrame bitmapFrame = null;
            BitmapMetadata metadata = null;
            if (System.IO.File.Exists(imageFlePath))
            {
                // load the jpg file with a JpegBitmapDecoder    
                using (Stream jpegStreamIn = File.Open(imageFlePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    decoder = new JpegBitmapDecoder(jpegStreamIn, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                }
                bitmapFrame = decoder.Frames[0];
                metadata = (BitmapMetadata)bitmapFrame.Metadata;
 if (bitmapFrame != null)
                {
                    BitmapMetadata metaData = (BitmapMetadata)bitmapFrame.Metadata.Clone();
                    if (metaData != null)
                    {
                        string ascStr = StringToUnicode(comments);
                        // modify the metadata   
                        metaData.SetQuery("/app1/ifd/exif:{uint=37510}", ascStr);//comment
                        // get an encoder to create a new jpg file with the new metadata.      
                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metaData, bitmapFrame.ColorContexts));
                        // Save the new image 
                        using (Stream jpegStreamOut = File.Open(imageFlePath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            encoder.Save(jpegStreamOut);
                    }
                    }
                }
            }
        }
 public string extractComment(string imageFilePath)
        {
            string getinfo = "";
            string jpegDirectory = System.IO.Path.GetDirectoryName(imageFilePath);
            string jpegFileName = System.IO.Path.GetFileNameWithoutExtension(imageFilePath);
            BitmapDecoder decoder = null;
            BitmapFrame bitmapFrame = null;
            BitmapMetadata metadata = null;
            FileInfo originalImage = new FileInfo(imageFilePath);
            if (File.Exists(imageFilePath))
 {
                // load the jpg file with a JpegBitmapDecoder    
                using (Stream jpegStreamIn = File.Open(imageFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    decoder = new JpegBitmapDecoder(jpegStreamIn, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                }
                bitmapFrame = decoder.Frames[0];
                metadata = (BitmapMetadata)bitmapFrame.Metadata;
                if (bitmapFrame != null)
                {
                    BitmapMetadata metaData = (BitmapMetadata)bitmapFrame.Metadata.Clone();
                    if (metaData != null)
{
                        try
                        {
                            byte[] info = Encoding.Default.GetBytes(metadata.GetQuery("/app1/ifd/exif:{uint=37510}").ToString());
                            getinfo = Encoding.ASCII.GetString(info);
                        }
                        catch 
                        {
                            return string.Empty;
                        }
                    }
  }
            }
            string ret = UnicodeToString(getinfo);
            return ret;
        }
    }

猜你喜欢

转载自www.cnblogs.com/yuanchao/p/11165445.html