/// <summary> /// <see cref="DataOfFriends"/>转<see cref="MessageListItem"/> /// </summary> /// <param name="friend"></param> /// <returns></returns> public static MessageListItem ToMsgListItem(this DataOfFriends friend) { var tmpitem = new MessageListItem(); try { tmpitem = new MessageListItem()//实例化一个消息项 { MessageTitle = friend.toNickname, Jid = friend.toUserId, //设置UserId //MessageItemType = ItemType.User,//好友项 ShowTitle = friend.remarkName, //备注名 Avator = Applicate.LocalConfigData.GetDisplayAvatorPath(friend.toUserId), //获取头像 }; } catch (System.Exception ex) { ConsoleLog.Output("ToMsgListItem=-" + ex.Message); } return(tmpitem); }
/// <summary> /// 从资源文件中的Bitmap转为BitmapImage /// </summary> /// <param name="srcImg">源图片</param> /// <returns>转换后的图片</returns> public static BitmapSource ConvertBitmapToBitmapSource(Bitmap srcImg) { try { //判断非空 if (srcImg != null) { //转换 //img = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(srcImg.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return(Imaging.CreateBitmapSourceFromHBitmap(srcImg.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()));//并返回 } else { return(new BitmapImage()); } } catch (Exception ex) { ConsoleLog.Output("转换资源文件中bitmap为bitmapImage时出错:" + ex.Message); return(new BitmapImage()); } }
/// <summary> /// 将图片读取为byte再转为BitmapImage /// </summary> /// <param name="filePath">图片路径</param> /// <returns>内存中的图片</returns> public static BitmapImage ReadFileByteToBitmap(string filePath) { var bitmap = new BitmapImage(); try { BinaryReader binReader = new BinaryReader(File.OpenRead(filePath)); FileInfo fileInfo = new FileInfo(filePath); byte[] bytes = binReader.ReadBytes((int)fileInfo.Length); binReader.Close(); binReader.Dispose(); // Init bitmap bitmap.BeginInit(); bitmap.StreamSource = new MemoryStream(bytes); bitmap.EndInit(); } catch (Exception ex) { ConsoleLog.Output("将头像复制到内存时出错:" + ex.Message); return null; } return bitmap; }
/// <summary> /// 文件转为byte数组 /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns></returns> private static byte[] FileTojByte(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); try { byte[] buffur = new byte[fs.Length]; fs.Read(buffur, 0, (int)fs.Length); return buffur; } catch (Exception ex) { ConsoleLog.Output(ex.Message); return null; } finally { if (fs != null) { //关闭资源 fs.Close(); } } }
/// <summary> /// 音频Uri变化时 /// </summary> /// <param name="d"></param> /// <param name="e"></param> private static void OnAudioUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.NewValue != null) { AsyncAudioControl audio = d as AsyncAudioControl; string uri = e.NewValue as string; string filepath = audio.AudioFileName; string filename = filepath.Substring(filepath.LastIndexOf('/') + 1, filepath.Length - filepath.LastIndexOf("/") - 1); string localpath = Applicate.LocalConfigData.ChatPath + filename; #region Download Image File if (File.Exists(localpath)) { //设置控件本身的 audio.LocalAudioPath = localpath; } else if (uri.Contains("http"))//if it's Web url { //get info about the path //string localpath = Applicate.LocalConfigData.ChatDownloadPath; WebClient web = new WebClient(); //when the progress changed , set the value of the progressbar web.DownloadProgressChanged += (s, ev) => { audio.AudioProgress.Value = ev.ProgressPercentage; }; //When download completed, fill the image of the border web.DownloadFileCompleted += (s, ev) => { if (ev.Error == null) { //设置控件本身的 audio.LocalAudioPath = localpath; //Applicate.GetWindow<MainWindow>().VlcPlayer.SourceProvider.MediaPlayer Task.Run(() => { //转码(不需要) //string localChatpath = Applicate.LocalConfigData.ChatPath + filename.Replace("amr", "mp3"); //string resu = Helpers.AmrConvertToMp3(localTemppath, localChatpath); //ConsoleLog.Output("转码::::::" + resu); App.Current.Dispatcher.Invoke(() => { audio.transitioner.SelectedIndex = 1; }); web.Dispose();// Dispose the WebClient }); } else { ConsoleLog.Output("音频下载失败:" + ev.Error.Message); } }; try { } catch (Exception ex) { ConsoleLog.Output("Download Aaudio Error:;;", ex); } //Start download image async web.DownloadFileAsync(new Uri(uri), localpath); #endregion } } }
/// <summary> /// 消息改变时 /// </summary> /// <param name="d">母控件</param> /// <param name="e">更改相关值</param> private static void OnBubbleMsgChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AsyncImageControl imagecontrol = (AsyncImageControl)d; if (e.NewValue != null) { #region Download Image File string uri = (string)e.NewValue; try { if (uri.Contains("http"))//if it's Web url { //get info about the path string localpath = Applicate.LocalConfigData.ChatDownloadPath; ChatBubbleItemModel msg = imagecontrol.Tag as ChatBubbleItemModel; string filename = msg.fileName.Substring( msg.fileName.LastIndexOf('/') + 1, msg.fileName.Length - msg.fileName.LastIndexOf('/') - 1 ); var localfile = localpath + filename; if (File.Exists(localfile))//if file exists, fill the image of the border { try { var imguri = new Uri(localfile); imagecontrol.Imgborder.Source = new BitmapImage(imguri); imagecontrol.transitioner.SelectedIndex = 1; imagecontrol.MouseLeftButtonUp += (sen, res) => { var photoView = new PictureWindow().GetPhotoView(localfile); photoView.Show(); //photoView.Activate(); //photoView.Focus(); }; } catch (Exception ex) { ConsoleLog.Output("显示图片cc" + ex.Message); } } else//if not exists { using (WebClient web = new WebClient()) { try { //when the progress changed , set the value of the progressbar web.DownloadProgressChanged += (s, ev) => { imagecontrol.ImageProgress.Value = ev.ProgressPercentage; }; //When download completed, fill the image of the border web.DownloadFileCompleted += (s, ev) => { if (ev.Error == null) { var imguri = new Uri(localfile); imagecontrol.Imgborder.Source = new BitmapImage(imguri); imagecontrol.transitioner.SelectedIndex = 1; imagecontrol.BtnDownload.Visibility = Visibility.Collapsed;//隐藏下载按钮 imagecontrol.MouseLeftButtonUp += (sen, res) => { var photoView = new PictureWindow().GetPhotoView(localfile); photoView.Show(); photoView.Activate(); photoView.Focus(); }; web.Dispose();//Dispose the WebClient } else { ConsoleLog.Output("图片下载失败"); } }; //Start download image async web.DownloadFileAsync(new Uri(uri), localfile); } catch (Exception ex) { ConsoleLog.Output("AsyncImageControl--GetImage--Error" + ex.Message); imagecontrol.Dispatcher.Invoke(() => { imagecontrol.BtnDownload.Visibility = Visibility.Visible;//显示下载按钮 }); } } } } #endregion else//if it's local path { if (File.Exists(uri)) { imagecontrol.Imgborder.Source = new BitmapImage(new Uri(uri)); imagecontrol.transitioner.SelectedIndex = 1; imagecontrol.MouseLeftButtonUp += (sen, res) => { var photoView = new PictureWindow().GetPhotoView(uri); photoView.Show(); photoView.Activate(); photoView.Focus(); }; } } } catch (Exception ex) { ConsoleLog.Output("Download Aaudio Error:;;", ex); } } else { return; } }
/// <summary> /// 消息改变时 /// </summary> /// <param name="d">母控件</param> /// <param name="e">更改相关值</param> private static void OnBubbleMsgChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AsyncVideoControl imagecontrol = (AsyncVideoControl)d; if (e.NewValue != null) { #region Download Image File string uri = (string)e.NewValue; if (uri.Contains("http"))//if it's Web url { //get info about the path string localpath = Applicate.LocalConfigData.ChatDownloadPath; ChatBubbleItemModel msg = imagecontrol.Tag as ChatBubbleItemModel; if (msg.fileName == null) { return; } string filename = msg.fileName.Substring( msg.fileName.LastIndexOf('/') + 1, msg.fileName.Length - msg.fileName.LastIndexOf('/') - 1 ); var localfile = localpath + filename; if (File.Exists(localfile))//if file exists, fill the image of the border { var imguri = new Uri(localfile); BitmapImage mapImage = ImageUtil.ConvertBitmapToBitmapImage(WindowsThumbnailProvider.GetThumbnail(localfile, 256, 256, ThumbnailOptions.None)); imagecontrol.Imgborder.Background = new ImageBrush(mapImage); imagecontrol.transitioner.SelectedIndex = 1; } else//if not exists { try { WebClient web = new WebClient(); //when the progress changed , set the value of the progressbar web.DownloadProgressChanged += (s, ev) => { imagecontrol.ImageProgress.Value = ev.ProgressPercentage; }; //When download completed, fill the image of the border web.DownloadFileCompleted += (s, ev) => { if (ev.Error == null) { BitmapImage mapImage = ImageUtil.ConvertBitmapToBitmapImage(WindowsThumbnailProvider.GetThumbnail(localfile, 256, 256, ThumbnailOptions.None)); imagecontrol.Imgborder.Background = new ImageBrush(mapImage); imagecontrol.transitioner.SelectedIndex = 1; //Set Border Background(Not for now) //var imguri = new Uri(localfile); //imagecontrol.Imgborder.Background = new ImageBrush(new BitmapImage(imguri)); web.Dispose();// Dispose the WebClient } else { ConsoleLog.Output("视频下载失败"); } }; //Start download image async web.DownloadFileAsync(new Uri(uri), localfile); } catch (Exception ex) { ConsoleLog.Output("Download Aaudio Error:;;", ex); } #endregion } } else//if it's local path { if (File.Exists(uri)) { BitmapImage mapImage = ImageUtil.ConvertBitmapToBitmapImage(WindowsThumbnailProvider.GetThumbnail(uri, 256, 256, ThumbnailOptions.None)); imagecontrol.Imgborder.Background = new ImageBrush(mapImage); imagecontrol.transitioner.SelectedIndex = 1; } } } else { return; } }
/// <summary> /// 创建二维码 /// </summary> /// <param name="QRString">二维码字符串</param> /// <param name="QRCodeEncodeMode">二维码编码(Byte、AlphaNumeric、Numeric)</param> /// <param name="QRCodeScale">二维码尺寸(Version为0时,1:26x26,每加1宽和高各加25</param> /// <param name="QRCodeVersion">二维码密集度0-40</param> /// <param name="QRCodeErrorCorrect">二维码纠错能力(L:7% M:15% Q:25% H:30%)</param> /// <param name="hasLogo">是否有logo(logo尺寸50x50,QRCodeScale>=5,QRCodeErrorCorrect为H级)</param> /// <param name="logoFilePath">logo路径</param> /// <returns></returns> public static BitmapSource CreateQRCode(string QRString, string QRCodeEncodeMode, short QRCodeScale, int QRCodeVersion, string QRCodeErrorCorrect, bool hasLogo, string logoFilePath) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); switch (QRCodeEncodeMode) { case "Byte": qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; break; case "AlphaNumeric": qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC; break; case "Numeric": qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC; break; default: qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; break; } qrCodeEncoder.QRCodeScale = QRCodeScale; qrCodeEncoder.QRCodeVersion = QRCodeVersion; switch (QRCodeErrorCorrect) { case "L": qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L; break; case "M": qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; break; case "Q": qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q; break; case "H": qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; break; default: qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; break; } try { System.Drawing.Image image = qrCodeEncoder.Encode(QRString, System.Text.Encoding.UTF8); if (hasLogo) { System.Drawing.Image copyImage = System.Drawing.Image.FromFile(logoFilePath); Graphics g = Graphics.FromImage(image); int x = image.Width / 2 - copyImage.Width / 2; int y = image.Height / 2 - copyImage.Height / 2; g.DrawImage(copyImage, new Rectangle(x, y, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel); g.Dispose(); copyImage.Dispose(); } System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image); image.Dispose(); return(Helpers.ConvertBitmapToBitmapSource(bmp)); } catch (Exception ex) { ConsoleLog.Output("QRCode Error:" + ex.Message); LogHelper.log.Info("QRCode Error:" + ex.Message); return(null); } }
/// <summary> /// 把 Emoji编码 [e]1f1e6-1f1fa[/e] /// [e]1f1e6[/e] /// [e]1f1fa[/e] /// [e]1f1e6[/e] /// [e]1f1f9[/e] 换成对应的字符串,此字符串能被window8.1,ios,andriod 直接显示. /// /// 如果在网页中显示,需要设置字体为 'Segoe UI Emoji' 如下.当然客户机还必须得有这个字体. /// /// <span style="font-family:'Segoe UI Emoji';"></span> /// /// </summary> /// <param name="paramContent"></param> /// <returns></returns> public string GetEmoji(string paramContent) { string paramContentR = paramContent.Replace("[e]", "\\u").Replace("[/e]", ""); var unicodehex = new char[6] { '0', '0', '0', '0', '0', '0' }; StringBuilder newString = new StringBuilder(2000); StringBuilder tempEmojiSB = new StringBuilder(20); StringBuilder tmps = new StringBuilder(5); int ln = paramContent.Length; for (int index = 0; index < ln; index++) { int i = index; //把指针给一个临时变量,方便出错时,现场恢复. try { if (paramContent[i] == '[') { //预测 if (paramContent[i + 1] == 'e') { if (paramContent[i + 2] == ']') //[e]的后面4位是 unicode 的16进制数值. { i = i + 3; //前进3位 i = ChangUnicodeToUTF16(paramContent, tempEmojiSB, tmps, i); if (paramContent[i] == '-') //向前探测1位 看看是否双字符 形如1f1e7-1f1ea { i++; i = ChangUnicodeToUTF16(paramContent, tempEmojiSB, tmps, i); } ; if (paramContent[i] == '[') { if (paramContent[i + 1] == '/') { if (paramContent[i + 2] == 'e') { if (paramContent[i + 3] == ']') { i = i + 3; //再前进4位 index = i; //识别转换成功 newString.Append(tempEmojiSB.ToString()); //识别转换成功 tempEmojiSB.Clear(); continue; } } } } } } } index = i; } catch (Exception ex) { ConsoleLog.Output(ex); //解析失败仍然继续 } newString.Append(paramContent[index]); } return(newString.ToString()); }
private static void OnMessageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { try { var message = e.NewValue as Messageobject; var mapcontrol = (MapBubble)d; var serverUri = new Uri(System.Web.HttpUtility.HtmlDecode(message.content)); //解码 string url = Applicate.MapApiUrl + "location={0},{1}&title={2}&content={3}&output=html"; //删除 string mapurl = string.Format(url, message.location_x, message.location_y, "我的位置", message.objectId); string uri = message.content; //get info about the path string localpath = Applicate.LocalConfigData.CatchPath; //ChatBubbleItemModel message = mapcontrol.Tag as ChatBubbleItemModel; string filename = message.fileName.Substring( message.fileName.LastIndexOf('/') + 1, message.fileName.Length - message.fileName.LastIndexOf('/') - 1 ); var localfile = localpath + filename; //获取缓存路径 if (File.Exists(localfile)) //if file exists, fill the image of the border { var imguri = new Uri(localfile); mapcontrol.MapImg.Source = new BitmapImage(imguri); mapcontrol.transitioner.SelectedIndex = 1; mapcontrol.MouseLeftButtonUp += (sen, res) => { Process.Start(mapurl); }; } else//if not exists { WebClient web = new WebClient(); //when the progress changed , set the value of the progressbar web.DownloadProgressChanged += (s, ev) => { mapcontrol.ImageProgress.Value = ev.ProgressPercentage; }; //When download completed, fill the image of the border web.DownloadFileCompleted += (s, ev) => { if (ev.Error == null) { var imguri = new Uri(localfile); mapcontrol.MapImg.Source = new BitmapImage(imguri); mapcontrol.transitioner.SelectedIndex = 1; mapcontrol.MouseLeftButtonUp += (sen, res) => { Process.Start(mapurl); }; web.Dispose();//Dispose the WebClient } else { ConsoleLog.Output("图片下载失败"); } }; //Start download image async web.DownloadFileAsync(new Uri(uri), localfile); } } catch (Exception ex) { ConsoleLog.Output("显示地址失败:" + ex.Message); } }