向AD中添加图片

来源:互联网 发布:淘宝盗图怎么申诉 编辑:程序博客网 时间:2024/04/30 13:13

        我们知道,AD用户的属性中,有三个属性可以保存图片,一个是thumbnailPhoto,这个属性通常保存的是用户的头像,Outlook或者Lync等就使用这个属性,来显示用户的头像。一个是“thumbnailLogo”,最后一个属性是jpegPhoto。AD本身没有提供一个界面来上传或者更新这几个属性,网上也有很多更新这几个属性的方法,一个比较好的帖子可以参考:How to import Photos into Active Directory

        这里使用的方法是C#,通过C#代码为AD用户添加头像(即修改thumbnailPhoto属性),或者修改jpegPhoto这个属性。修改这三个属性主要的问题是,AD对这三个属性是有如下限制的: 1,图片的宽和高不能大于96象素,否则修改会失败。2, 对于jpegPhoto,图片大小不能超过100k;而对于thumbnailPhoto和thumbnailLogo,图片大小不能超过10k。

        只有满足了以上条件的图片才可以成功的上传到AD中,因此在上传图片之前,要检查这两个条件,如果不符合条件,就需要使用Image.GetTumbnailImage方法进行转换,以下是具体的代码,将二进制的图片,转换为符合头像条件的图片。转换之后的二进制流可以直接赋值给thumbnailPhoto(thumbnailLogo)或者jepgPhoto。

        private byte[] GetImageBytes(byte[] photoBytes)        {            byte[] newPhotoBytes = null;            MemoryStream reader = null;            MemoryStream writer = null;            try            {                reader = new MemoryStream(photoBytes);                reader.Position = 0;                Image image = Image.FromStream(reader);                ImageFormat format = image.RawFormat;                if (image.Height > 96 || image.Width > 96 || photoBytes.Length > 10000) //thumbnailPhoto是10k的限制,jpegPhoto是100k                {                    reader.Position = 0;                    image = this.GetThumbnailBytes(reader);                }                writer = new MemoryStream();                image.Save(writer, format);                writer.Position = 0;                newPhotpBytes = new byte[(int)writer.Length];                writer.Read(newPhotpBytes, 0, (int)writer.Length - 1);            }            catch(Exception ex)            {                throw new Exception("图片转换失败。");            }            finally            {                if (reader != null)                {                    reader.Close();                }                if (writer != null)                {                    writer.Close();                }            }            return newPhotpBytes;        }        private Image GetThumbnailBytes(Stream photoStream)        {            Image.GetThumbnailImageAbort photoCallback = new Image.GetThumbnailImageAbort(MyCallback);            Bitmap bitMap = new Bitmap(photoStream);            Image thumbnailImage = bitMap.GetThumbnailImage(96, 96, photoCallback, IntPtr.Zero); //使用GetThumbnailImage的方法转换图片            return thumbnailImage;        }        public bool MyCallback()        {            return false;        }


        如果和SharePoint联系起来, 知道如何向AD中写入图片,就可以将SharePoint作为一个界面,AD用户可以在SharePoint中上传图片,更新自己的AD头像了,另外还可以保存一个小于100k的图片。

0 0
原创粉丝点击