C# 實現修改圖片文件詳細信息中的屬性值


C#中可以通過 System.Drawing.Imaging.PropertyItem 來獲取和設置 Image 的屬性值,不過在獲取 Image 的 PropertyItem 屬性值時需要指定屬性的ID,PropertyItem 的ID可以通過 Image.PropertyItems 獲得,通過這一點我們可以很簡單的實現設置圖片屬性的功能。


命名空間:

        using System.IO;
        using System.Drawing;
        using System.Drawing.Imaging;

功能實現:

獲取Image中的所有屬性:

private List<string> GetPropertyItems(string fileName)
        {
            List<string> result = new List<string>(0);
            if (File.Exists(fileName))
            {
                FileStream fm = new FileStream(fileName, FileMode.Open);
                Image Img = Image.FromStream(fm);
                foreach (PropertyItem i in Img.PropertyItems)
                {
                    //如果不清楚PropertyItem的Id可以通過枚舉獲得
                    //Console.WriteLine("Value:{0},ID:{1}",Encoding.Unicode.GetString(i.Value),i.Id);
                    result.Add(Encoding.Unicode.GetString(i.Value));
                }
                fm.Dispose();
                Img.Dispose();
            }
            return result;
        }

設置Image中的屬性並保存:

        private void SetPropertyInfo(string fileName,string newName, int propId,string value)
        {
            if (File.Exists(fileName))
            {
                FileStream fm = new FileStream(fileName, FileMode.Open);
                Image Img = Image.FromStream(fm);
                PropertyItem pi = Img.PropertyItems[0];
                pi.Id = propId; //40094
                pi.Type = 1;
                pi.Value = Encoding.Unicode.GetBytes(value);
                pi.Len = pi.Value.Length;
                Img.SetPropertyItem(pi);
                //File.Delete(fileName);
                //Img.Save(fileName);
                Img.Save(newName);
                fm.Dispose();
                Img.Dispose();
            }
        }

調用:

去除指定圖片的Tag(標記)屬性並輸出:

        //清除圖片的標記屬性  PropertyItem.Id : 40094
        SetPropertyInfo("C:\\Users\\Administrator\\Desktop\\Old.jpg","C:\\Users\\Administrator\\Desktop\\New.jpg",40094,null);

 需要注意的是獲取的PropertyItem的Value值有大部分是亂碼,只有部分是正常的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM