Esempio n. 1
0
        public string ImageRecognize(List <int[, ]> matrixList)
        {
            string code = string.Empty;

            for (int i = 0; i < matrixList.Count; i++)
            {   //判断是否返回I,返回I的话直接返回去,用整体破解
                var singleCode = OCRImageRecognize(ImageHandle.CreateImage(matrixList[i])).Replace(" ", "").Replace("  ", "").Trim();
                if (singleCode == "X" || singleCode == "H")
                {
                    if (matrixList[i].GetLength(1) <= 10)
                    {
                        singleCode = "I";
                    }
                }
                if (singleCode == "C")
                {
                    if (GetBlackCount(matrixList[i]) <= 166)
                    {
                        singleCode = "C";
                    }
                    else
                    {
                        singleCode = "G";
                    }
                }
                code += singleCode;
            }
            return(code);
        }
Esempio n. 2
0
        /// <inheritdoc />
        public IObservable <string> ExportImage(ImageHandle handle, string outputPath, IScheduler executionScheduler = null)
        {
            Guard.Against.ArgumentNull(handle, nameof(handle));
            Guard.Against.ArgumentNullOrEmpty(outputPath, nameof(outputPath));
            executionScheduler ??= RxApp.TaskpoolScheduler;

            return(Observable.Create <string>(observer =>
            {
                return executionScheduler.Schedule(() =>
                {
                    try
                    {
                        var originalFileName = Path.GetFileNameWithoutExtension(handle.LoadingSettings.FilePath);
                        var originalExtension = Path.GetExtension(handle.LoadingSettings.FilePath); //TODO: Compare with output format
                        var newFileName = $"{originalFileName}.min{originalExtension}";
                        var fullOutputPath = Path.Combine(outputPath, newFileName);

                        using var fs = File.Create(fullOutputPath);
                        handle.OriginalImage.Encode(fs, handle.LoadingSettings.Format.ToSkiaFormat(), handle.ManipulationState.Quality);

                        observer.OnNext(fullOutputPath);
                    }
                    catch (Exception ex)
                    {
                        observer.OnError(ex);
                    }
                    observer.OnCompleted();
                });
            }));
        }
Esempio n. 3
0
        /// <inheritdoc />
        public IObservable <ImageHandle> LoadImage(string path, IScheduler executionScheduler = null)
        {
            Guard.Against.ArgumentNullOrEmpty(path, nameof(path));
            executionScheduler ??= RxApp.TaskpoolScheduler;

            return(Observable.Create <ImageHandle>(observer =>
            {
                CompositeDisposable disposable = new CompositeDisposable();
                ImageHandle handle = default;
                SKCodec codec = default;

                IDisposable scheduling = executionScheduler.Schedule(() =>
                {
                    try
                    {
                        codec = SKCodec.Create(path) ?? throw new ImageLoadingException(path);
                        codec.DisposeWith(disposable);

                        var bitmap = SKBitmap.Decode(codec);
                        var format = codec.EncodedFormat == SKEncodedImageFormat.Gif ? SKEncodedImageFormat.Png : codec.EncodedFormat;
                        handle = new ImageHandle(path, bitmap, format);
                        observer.OnNext(handle);
                    }
                    catch (Exception ex)
                    {
                        observer.OnError(ex);
                    }
                    observer.OnCompleted();
                }).DisposeWith(disposable);

                return disposable;
            }));
        }
        // Request user's avatar data. Sizes can be powers of 2 between 16 and 2048
        static void FetchAvatar(ImageManager imageManager, Int64 userID)
        {
            imageManager.Fetch(ImageHandle.User(userID), (result, handle) =>
            {
                {
                    if (result == Result.Ok)
                    {
                        // You can also use GetTexture2D within Unity.
                        // These return raw RGBA.
                        var data = imageManager.GetData(handle);

                        var rgbaList = new List <Rgba32>();

                        for (int x = 0; x < data.Length; x += 4)
                        {
                            rgbaList.Add(new Rgba32(data[x], data[x + 1], data[x + 2], data[x + 3]));
                        }

                        var image = Image.LoadPixelData <Rgba32>(data, 128, 128);

                        //Console.WriteLine("image updated {0}", imgUrl);
                        Console.WriteLine(image.ToBase64String <Rgba32>(PngFormat.Instance));
                    }
                    else
                    {
                        Console.WriteLine("image error {0}", handle.Id);
                    }
                }
            });
        }
 public override string ImageRecognize()
 {
     try
     {
         var height = base._cutCharImageList[0].GetLength(0);
         if (height == 10)
         {
             var addend = Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[0])));
             height = base._cutCharImageList[1].GetLength(0);
             if (height == 10)
             {
                 addend = addend * 10 + Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[1])));
             }
             height = base._cutCharImageList[2].GetLength(0);
             string operater = null;
             if (height == 1)
             {
                 operater = "-";
             }
             else
             {
                 operater = "+";
             }
             height = base._cutCharImageList[3].GetLength(0);
             if (height == 1)//加号及减号被分割了,那就忽略
             {
                 height = base._cutCharImageList[5].GetLength(0);
                 if (height == 10)//说明加数是十位数
                 {
                     var add = 10 * Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[4]))) + Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[5])));
                     return(AddOrSubOperator(addend, add, operater).ToString());
                 }
                 else
                 {
                     var add = Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[4])));
                     return(AddOrSubOperator(addend, add, operater).ToString());
                 }
             }
             else
             {
                 height = base._cutCharImageList[4].GetLength(0);
                 if (height == 10)//说明加数是十位数
                 {
                     var add = 10 * Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[3]))) + Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[4])));
                     return(AddOrSubOperator(addend, add, operater).ToString());
                 }
                 else
                 {
                     var add = Convert.ToInt32(OCRImageRecognize(ImageHandle.CreateImage(base._cutCharImageList[3])));
                     return(AddOrSubOperator(addend, add, operater).ToString());
                 }
             }
         }
         return(null);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
        public IHttpActionResult CutImage(int size)
        {
            // 文件的临时处理文件夹
            var temp = Guid.NewGuid().ToString("N");

            if (!Directory.Exists(cutfolder + temp))
            {
                Directory.CreateDirectory(cutfolder + temp);
            }
            // 拿到接口传进来的文件
            var file      = HttpContext.Current.Request.Files[0];
            var extension = file.FileName.Split('.').Last().ToLower();

            if (extension == "png" || extension == "jpg" || extension == "jpeg" || extension == "bmp" || extension == "jfif" || extension == "tiff")
            {
                var imgName = cutfolder + temp + "/原图." + extension;
                NLogerHelper.Info("原图--" + imgName);
                file.SaveAs(imgName);
                ImageHandle.CutImage(imgName, cutfolder + temp + "/", size);
                return(Json(new
                {
                    Code = 200,
                    Msg = "分割与轮廓查找已完成!"
                }));
            }
            else
            {
                return(Json(new
                {
                    Code = 10001,
                    Msg = "请选择图片类型上传!"
                }));
            }
        }
Esempio n. 7
0
        public async Task <IActionResult> UpdateProblem([FromForm] ProblemUpload upload)
        {
            if (upload.Id == null)
            {
                return(BadRequest());
            }
            try
            {
                var problem = await _Repository.GetProblemByIdAsync(upload.Id.Value);

                problem.AnswerDescription  = upload.AnsDescription;
                problem.ProblemDescription = upload.ProblemDescription;
                problem.AnswerPicture      = ImageHandle.SaveImg(upload.AnsImg);
                problem.ProblemPicture     = ImageHandle.SaveImg(upload.ProblemImg);
                problem.Tags = upload.Tags.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();

                problem = await _Repository.UpdateProblemAsync(problem);

                _Logger.LogInformation("Updated problem {problem.Id}", problem.Id);
                return(Ok(problem));
            }
            catch (ProblemNotFound e)
            {
                _Logger.LogError("Problem {e.Id} not found", e.Id);
                return(NotFound(new { id = e.Id }));
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 退出讨论组
        /// </summary>
        public static bool ExitGroup(string groupId, string groupName, List <AntSdkGroupMember> Members)
        {
            ExitGroupInput input = new ExitGroupInput();

            input.groupId = groupId;
            input.token   = AntSdkService.AntSdkLoginOutput.token;
            input.userId  = AntSdkService.AntSdkLoginOutput.userId;
            input.version = GlobalVariable.Version;

            BaseOutput output  = new BaseOutput();
            var        errCode = 0;
            string     errMsg  = string.Empty;
            //TODO:AntSdk_Modify
            //DONE:AntSdk_Modify
            var isResult = AntSdkService.GroupExitor(AntSdkService.AntSdkLoginOutput.userId, groupId, ref errCode, ref errMsg);

            if (isResult)
            {
                string[] ThreadParams = new string[3];
                ThreadParams[0] = groupId;
                ThreadParams[1] = ImageHandle.GetGroupPicture(Members.Where(c => c.userId != AntSdkService.AntSdkLoginOutput.userId).Select(c => c.picture).ToList());
                ThreadParams[2] = string.IsNullOrEmpty(groupName) ? "" : groupName;
                Thread UpdateGroupPictureThread = new Thread(UpdateGroupPicture);
                UpdateGroupPictureThread.Start(ThreadParams);

                //OnDropOutGroupEvent(this);
            }
            else
            {
                MessageBoxWindow.Show(errMsg, GlobalVariable.WarnOrSuccess.Warn);
            }
            return(isResult);
        }
        public bool GetImageSize(ImageHandle image, out uint width, out uint height)
        {
            CheckIfUsable();

            width  = 0;
            height = 0;
            return(NativeMethods.Utils_GetImageSize(image.AsInt32, ref width, ref height));
        }
        public UtilsGetImageSizeResult GetImageSize(ImageHandle image)
        {
            UtilsGetImageSizeResult result = new UtilsGetImageSizeResult();

            result.Result = GetImageSize(image, out result.Width, out result.Height);

            return(result);
        }
        public IHttpActionResult ContrastImage(int SimilarValue)
        {
            // 文件的临时处理文件夹
            string imageName1 = string.Empty;
            string imageName2 = string.Empty;
            var    temp       = Guid.NewGuid().ToString("N");

            if (!Directory.Exists(cutfolder + temp))
            {
                Directory.CreateDirectory(cutfolder + temp);
            }
            // 拿到接口传进来的文件
            var file1     = HttpContext.Current.Request.Files[0];
            var extension = file1.FileName.Split('.').Last().ToLower();

            if (extension == "png" || extension == "jpg" || extension == "jpeg" || extension == "bmp" || extension == "jfif" || extension == "tiff")
            {
                imageName1 = cutfolder + temp + "/原图1." + extension;
                NLogerHelper.Info("原图--" + imageName1);
                file1.SaveAs(imageName1);
            }
            else
            {
                return(Json(new
                {
                    Code = 10001,
                    Msg = "请选择图片类型上传!"
                }));
            }
            // 拿到接口传进来的文件
            var file2      = HttpContext.Current.Request.Files[1];
            var extension1 = file2.FileName.Split('.').Last().ToLower();

            if (extension1 == "png" || extension1 == "jpg" || extension1 == "jpeg" || extension1 == "bmp")
            {
                imageName2 = cutfolder + temp + "/原图2." + extension1;
                NLogerHelper.Info("原图--" + imageName2);
                file2.SaveAs(imageName2);
            }
            else
            {
                return(Json(new
                {
                    Code = 10001,
                    Msg = "请选择图片类型上传!"
                }));
            }
            var p = ImageHandle.ContrastImage(imageName1, imageName2, SimilarValue);

            return(Json(new
            {
                Code = 200,
                Msg = "比对完成!",
                Data = p
            }));
        }
Esempio n. 12
0
 /// <summary>
 /// 图片本地化
 /// </summary>
 /// <param name="fileUrl"></param>
 /// <param name="errMsg"></param>
 /// <returns></returns>
 private string DownLoadImage(string fileUrl, ref string errMsg)
 {
     if (!Directory.Exists(_downloadGifPath))
     {
         Directory.CreateDirectory(_downloadGifPath);
     }
     if (!fileUrl.StartsWith("http:") && !fileUrl.StartsWith("file"))
     {
         try
         {
             //复制一份 防止图片占用
             var gifIndex = fileUrl.LastIndexOf("\\", StringComparison.Ordinal) + 1;
             var gifName  = fileUrl.Substring(gifIndex, fileUrl.Length - gifIndex);
             var gifPath  = _downloadGifPath + "tmp~" + gifName;
             if (!File.Exists(gifPath))
             {
                 File.Copy(fileUrl, gifPath, true);
             }
             return(gifPath);
         }
         catch (Exception ex)
         {
             errMsg = "图片下载失败";
             return(fileUrl);
         }
     }
     if (fileUrl.StartsWith("file"))
     {
         try
         {
             var index     = fileUrl.LastIndexOf("/", StringComparison.Ordinal) + 1;
             var fileName  = fileUrl.Substring(index, fileUrl.Length - index);
             var localFile = ImageHandle.DownloadPictureFromFile(fileUrl, _downloadGifPath + fileName, 10000);//10s超时
             //复制一份 防止打开之后被占用
             var tmpPath = _downloadGifPath + "tmp~" + fileName;
             if (!File.Exists(tmpPath))
             {
                 File.Copy(localFile, tmpPath, true);
             }
             return(tmpPath);
         }
         catch (Exception ex)
         {
             errMsg = "图片下载失败";
             return(fileUrl);
         }
     }
     else
     {
         var index     = fileUrl.LastIndexOf("/", StringComparison.Ordinal) + 1;
         var fileName  = fileUrl.Substring(index, fileUrl.Length - index);
         var localFile = ImageHandle.DownloadPictureFromHttp(fileUrl, _downloadGifPath + fileName, 10000);//10s超时
         return(localFile);
     }
 }
Esempio n. 13
0
        public override void ImageCutToList()
        {
            ImageConnectCut ic = new ImageConnectCut(base.imageMatrix);

            int[,] singleMatrix = ImageHandle.GetPictureSquence(ic.ConnectedLayerAreaMatrix);
            ic          = new ImageConnectCut(singleMatrix);
            resetMatrix = ImageHandle.ResetMatrix(ic.ConnectedLayerAreaMatrix);
            ic          = new ImageConnectCut(resetMatrix);
            clearMatrixByWidthAndHeight = ic.ClearMarixByWidthAndHeight(22, 38, 4, 32);
            base._cutCharImageList      = ic.GetCodeList();
        }
Esempio n. 14
0
        public void SavePicture(string picWebPath, string base64Image)
        {
            string fullPath = PictureDirPath + picWebPath;

            if (File.Exists(fullPath))
            {
                throw new UserFriendlyException("文件以存在");
            }

            ImageHandle.SaveImage(base64Image, fullPath);
        }
Esempio n. 15
0
    //Thanks to Karl @ Stunlock Studios for giving me their function as he implemented utils.GetImage(Size/RGBA) into our library
    public Texture2D GetTextureFromSteamID(SteamID steamId)
    {
        IFriends friends = Steamworks.SteamInterface.Friends;
        IUtils   utils   = Steamworks.SteamInterface.Utils;

        ImageHandle avatarHandle = friends.GetLargeFriendAvatar(steamId);

        if (avatarHandle.IsValid)
        {
            uint width, height;
            if (utils.GetImageSize(avatarHandle, out width, out height))
            {
                Texture2D texture = new Texture2D((int)width, (int)height, TextureFormat.RGBA32, true);
                Color32[] buffer  = new Color32[width * height];

                GCHandle bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

                try
                {
                    System.IntPtr bufferPtr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);

                    if (utils.GetImageRGBA(avatarHandle, bufferPtr, (int)width * (int)height * 4))
                    {
                        // Flip vertical
                        for (int x = 0; x < width; x++)
                        {
                            for (int y = 0; y < height / 2; y++)
                            {
                                Color32 temp = buffer[x + (width * y)];
                                buffer[x + (width * y)] = buffer[x + (width * (height - 1 - y))];
                                buffer[x + (width * (height - 1 - y))] = temp;
                            }
                        }

                        texture.SetPixels32(buffer);
                        texture.Apply();
                    }
                }
                finally
                {
                    bufferHandle.Free();
                }
                return(texture);
            }
        }

        return(null);
    }
Esempio n. 16
0
        public static void UpdateGroupPicture(object localPicture)
        {
            string[] ThreadParams              = localPicture as string[];
            string   pictureAddress            = ImageHandle.UploadPicture(ThreadParams[1]);
            AntSdkUpdateGroupInput updateInput = new AntSdkUpdateGroupInput();

            updateInput.userId       = AntSdkService.AntSdkLoginOutput.userId;
            updateInput.groupId      = ThreadParams[0];
            updateInput.groupName    = "";
            updateInput.groupPicture = pictureAddress;
            var    errCode = 0;
            string errMsg  = string.Empty;

            //TODO:AntSdk_Modify
            //DONE:AntSdk_Modify
            AntSdkService.UpdateGroup(updateInput, ref errCode, ref errMsg);
            //(new HttpService()).UpdateGroup(updateInput, ref updateOut, ref errMsg);
        }
Esempio n. 17
0
        public async Task <IActionResult> CreateProblem([FromForm] ProblemUpload upload)
        {
            var problem = new Problem
            {
                AnswerDescription  = upload.AnsDescription,
                ProblemDescription = upload.ProblemDescription
            };

            // savefile
            problem.AnswerPicture  = ImageHandle.SaveImg(upload.AnsImg);
            problem.ProblemPicture = ImageHandle.SaveImg(upload.ProblemImg);
            problem.Tags           = upload.Tags.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();

            problem = await _Repository.CreateProblemAsync(problem);

            _Logger.LogInformation("Created problem {problem.Id}", problem.Id);
            return(Ok(problem));
        }
Esempio n. 18
0
        public object UploadImageFiles()
        {
            //HttpFileCollectionBase files = Request.Files;
            var files  = Request.Files;
            var idList = new List <ImageVM>();

            for (var i = 0; i < files.Count; i++)
            {
                var name      = files[i].FileName;
                var imghandle = new ImageHandle();
                if (!MatchImageFromImag(System.IO.Path.GetExtension(name)))
                {
                    throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.ExpectationFailed)
                    {
                        Content      = new StringContent(JsonConvert.SerializeObject(new { success = false, message = "圖片格式不符" })),
                        ReasonPhrase = "Server Error"
                    });
                }


                var filename   = Guid.NewGuid().ToString();
                var imagpath   = imghandle.path + filename + ".jpeg";
                var postedFile = files[i].InputStream;
                var image      = System.Drawing.Image.FromStream(postedFile);
                //var newImage = imghandle.ResizeImage(image, 500, 600);

                var tempimg = db.temp_image.Add(new temp_image
                {
                    image_Byte = imghandle.ImageToBuffer(image, System.Drawing.Imaging.ImageFormat.Jpeg),
                    userId     = UserId,
                    image_Path = imagpath,
                    created    = DateTime.Now,
                    deleted    = false
                });
                image.Save(Server.MapPath(imagpath));
                db.SaveChanges();
                idList.Add(new ImageVM {
                    id = tempimg.ID.ToString(), path = tempimg.image_Path, isTemp = true
                });
            }


            return(Json(idList));
        }
Esempio n. 19
0
        public void SetHeadSculpture(string base64Image)
        {
            string rootPath = AppConfigurations.RootPath;
            string webPath  = $"\\Sonarqube\\{Id}.png";

            if (!string.IsNullOrEmpty(HeadSculpture))
            {
                File.Delete(rootPath + HeadSculpture);
            }

            string path = rootPath + webPath;

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            ImageHandle.SaveImage(base64Image, path);

            HeadSculpture = webPath;
        }
Esempio n. 20
0
        public void SetupScreen()
        {
            titleText.text = $"<b>{user.Username}#{user.Discriminator}</b> wants to join your game!";

            var imageManager = DiscordClient.GetImageManager();

            var handle = new ImageHandle()
            {
                Id   = user.Id,
                Size = 256
            };

            imageManager.Fetch(handle, false, (result, img) =>
            {
                if (result == Result.Ok)
                {
                    var texture = imageManager.GetTexture(img);
                    playerAvatar.rectTransform.localRotation = Quaternion.Euler(180f, 0f, 0f);
                    playerAvatar.texture = texture;
                }
            });
        }
        public void SetupScreen()
        {
            titleText.text = $"<b>{user.Username}#{user.Discriminator}</b> invited you to play! ({activity.Party.Size.CurrentSize}/{activity.Party.Size.MaxSize} players)";

            var imageManager = DiscordClient.GetImageManager();

            var handle = new ImageHandle()
            {
                Id   = user.Id,
                Size = 256
            };

            imageManager.Fetch(handle, false, (result, img) =>
            {
                if (result == Result.Ok)
                {
                    var texture = imageManager.GetTexture(img);
                    playerAvatar.rectTransform.localRotation = Quaternion.Euler(180f, 0f, 0f);
                    playerAvatar.texture = texture;
                }
            });
        }
        public override void LoadAvatar()
        {
            if (userId == 0)
            {
                return;
            }

            var handle = new ImageHandle()
            {
                Type = ImageType.User,
                Id   = userId,
                Size = avatarSize
            };

            manager.Fetch(handle, false, (result, handleResult) =>
            {
                if (result == Result.Ok)
                {
                    var tex       = manager.GetTexture(handleResult);
                    image.texture = tex;
                    AlphaVisible();
                    onAvatarAvailable.Invoke(tex);
                }
                else
                {
                    Debug.Log($"Failed to fetch avatar for user {userId}.");
                }
            });


            void AlphaVisible()
            {
                var color = image.color;

                color.a     = 1.0f;
                image.color = color;
            }
        }
Esempio n. 23
0
        /// <inheritdoc />
        public IObservable <ImageHandle> CalculatePreview(ImageHandle handle, IScheduler executionScheduler = null)
        {
            Guard.Against.ArgumentNull(handle, nameof(handle));
            executionScheduler ??= RxApp.TaskpoolScheduler;

            return(Observable.Create <ImageHandle>(observer =>
            {
                IDisposable scheduling = executionScheduler.Schedule(() =>
                {
                    var old = handle.Preview;

                    using var data = handle.OriginalImage.Encode(handle.LoadingSettings.Format.ToSkiaFormat(), handle.ManipulationState.Quality);

                    handle.Preview = SKBitmap.Decode(data);

                    old?.Dispose();

                    observer.OnNext(handle);
                    observer.OnCompleted();
                });

                return scheduling;
            }));
        }
    // Start is called before the first frame update
    async void Start()
    {
        Loaded = false;
        var discord = DiscordGameSDK.Instance.discord;
        await DiscordGameSDK.Instance.SDKReady.Task;
        User user = discord.GetUserManager().GetCurrentUser();

        Debug.Log(user.Id);
        var handle = new ImageHandle()
        {
            Type = ImageType.User,
            Id   = user.Id,
            Size = 256
        };

        discord.GetImageManager().Fetch(handle, false, (result, rere) =>
        {
            Texture avatar = discord.GetImageManager().GetTexture(handle);
            RawImage image = gameObject.GetComponent <RawImage>();
            image.texture  = avatar;
            Debug.Log("User Loaded");
            Loaded = true;
        });
    }
Esempio n. 25
0
        public override string ImageRecognize()
        {
            if (base._cutCharImageList.Count == 4)
            {
                ImageConnectCut ica = new ImageConnectCut(resetMatrix);
                clearMatrixByWidthAndHeight = ica.ClearMarixByWidthAndHeight(22, 38, 4, 64);//宽粘连
                base._cutCharImageList      = ica.GetCodeList();
                if (base._cutCharImageList.Count == 4)
                {
                    ica = new ImageConnectCut(resetMatrix);
                    clearMatrixByWidthAndHeight = ica.ClearMarixByWidthAndHeight(22, 70, 4, 38);//高粘连
                    base._cutCharImageList      = ica.GetCodeList();
                }
            }

            if (base._cutCharImageList.Count == 7)
            {
                return(OCRImageRecognize(ImageHandle.CreateImage(clearMatrixByWidthAndHeight)).Replace(" ", "").Trim());
            }
            else
            {
                return(ImageRecognize(base._cutCharImageList));
            }
        }
Esempio n. 26
0
        public string CreateOrEdit(dynamic requestData)
        {
            LogHelper.WriteMsgByDay("ZhuanTiController-CreateOrEdit-log:" + requestData.ToString());
            ReturnJson r           = new ReturnJson();
            int        zhuantiid   = requestData.ZhuanTiId;   //专题id,新建时为0,编辑时为实际id
            string     action      = requestData.Action;      //接口类型  分Create Edit
            string     zhuantiname = requestData.ZhuanTiName; //专题名称
            var        contentList = requestData.ContentList; //专题内容列表

            if (string.IsNullOrEmpty(zhuantiname))
            {
                r.message = "专题名称不能为空";
            }
            else if (zhuantiname.Length > 14)
            {
                zhuantiname = zhuantiname.Substring(0, 14);
            }
            else
            {
                string sql = "";
                sql = string.Format("SELECT 1 FROM dbo.CpkZhuanTi WHERE ZhuanTiName = '{0}' ", zhuantiname);
                int c = dataContext.GetCount(CommandType.Text, sql);
                if (action == "Create")
                {
                    if (c > 0) //判断是否存在
                    {
                        r.message = "该专题名称已存在";
                    }
                }
                else
                {
                    if (c > 1) //判断是否存在
                    {
                        r.message = "该专题名称已存在";
                    }
                }

                if (string.IsNullOrEmpty(r.message))   //以上验证都通过时
                {
                    //现将该专题已存在的内容及菜品关系 逻辑删除
                    sql = string.Format(@"UPDATE dbo.CpkZhuanTiContent SET IsEnable = 0 WHERE ZhuanTiId ={0}", zhuantiid);
                    SqlHelper2.ExecuteNonQuery(CommandType.Text, sql);
                    foreach (var item in contentList)                                    //循环内容列表
                    {
                        string content  = item["Content"].ToString().Replace("\"", "'"); //富文本内容
                        string caiPinId = item["CaiPinId"];                              //内容关联的菜品
                        //LogHelper.WriteMsgByDay("CaiPinController-content-log:" + content);
                        if (content.IndexOf("base64") > 0)
                        {
                            foreach (string a in ImageHandle.GetHtmlImageUrlList(content))
                            {
                                //LogHelper.WriteMsgByDay("CaiPinController-string a-log:" + a);
                                //LogHelper.WriteMsgByDay("CaiPinController-Common.ImageHandle.DNS-log:" + Common.ImageHandle.DNS);
                                if (a.IndexOf(Common.ImageHandle.DNS) < 0)
                                {
                                    string[] asplit = a.Split(',');
                                    //LogHelper.WriteMsgByDay("CaiPinController-asplit-log:" + asplit.ToString());
                                    string imgtype = asplit[0].Substring(11, asplit[0].Length - 18);
                                    //LogHelper.WriteMsgByDay("CaiPinController-imgtype-log:" + imgtype);
                                    string filepath = Common.ImageHandle.Base64StringToImage(asplit[1], imgtype, "/Images");
                                    content = content.Replace(a, filepath);
                                }
                            }
                        }
                        //新增编辑都是如下逻辑,因为编辑时上面已逻辑删除之前的内容
                        //新增专题基本信息
                        CpkZhuanTi m = new CpkZhuanTi();
                        m.ZhuanTiId   = zhuantiid;
                        m.ZhuanTiName = zhuantiname;
                        m.UpdateDate  = DateTime.Now;
                        db.CpkZhuanTi.AddOrUpdate(m); //根据zhuantiid新增或者编辑
                        db.SaveChanges();
                        zhuantiid = m.ZhuanTiId;
                        //新增专题内容

                        CpkZhuanTiContent mContent = new CpkZhuanTiContent();
                        mContent.ZtContentId = 0;
                        mContent.ZhuanTiId   = zhuantiid;
                        mContent.Content     = content;
                        db.CpkZhuanTiContent.AddOrUpdate(mContent);
                        db.SaveChanges();
//                        sql = string.Format(@"INSERT INTO dbo.CpkZhuanTiContent
//                                                    ( ZhuanTiId , Content)
//                                            VALUES  ( {0} , '{1}' ); select SCOPE_IDENTITY() ", zhuantiid, content);
//                        int ztContentId = Convert.ToInt32(SqlHelper2.ExecuteScalar(CommandType.Text, sql));
                        int ztContentId = mContent.ZtContentId;
                        //新增专题内容关联的菜品
                        sql = string.Format(@"INSERT INTO dbo.CpkCpZtContentRelation
                                                    ( ZtContentId , CaiPinId )
                                              SELECT {0},CaiPinId FROM dbo.CpkCaiPinBasicInfo WHERE CaiPinId IN ({1});
                                              DELETE FROM dbo.CpkZhuanTiContent WHERE ZhuanTiId ={2} AND IsEnable = 0
                                        ", ztContentId, caiPinId, zhuantiid);
                        SqlHelper2.ExecuteNonQuery(CommandType.Text, sql);
                    }
                    r.status  = "succ";
                    r.message = action + "成功";
                }
            }
            return(JsonConvert.SerializeObject(r));
        }
Esempio n. 27
0
        void Ratio_button_checkChange(object sender, EventArgs e)
        {
            if (bmp == null)
            {
                MessageBox.Show("请先选择图片");
                return;
            }
            RadioButton r = (RadioButton)sender;

            if (!r.Checked)
            {
                return;
            }
            string text = r.Text;

            switch (text)
            {
            case "原图": this.pictureBox1.Image = bmp; break;

            case "黑白色": ImageHandle.HeiBaiSeImage(bmp, this.pictureBox1); break;

            case "雾化": ImageHandle.WuHuaImage(bmp, this.pictureBox1); break;

            case "蜕化": ImageHandle.RuiHuaImage(bmp, this.pictureBox1); break;

            case "底片": ImageHandle.DiPianImage(bmp, this.pictureBox1); break;

            case "浮雕": ImageHandle.FuDiaoImage(bmp, this.pictureBox1); break;

            case "日光照射": ImageHandle.RiGuangZhaoSheImage(bmp, this.pictureBox1); break;

            case "油画": ImageHandle.YouHuaImage(bmp, this.pictureBox1); break;

            case "垂直百叶窗": ImageHandle.BaiYeChuang1(bmp, this.pictureBox1); break;

            case "水平百叶窗": ImageHandle.BaiYeChuang2(bmp, this.pictureBox1); break;

            case "淡入": ImageHandle.DanRu(bmp, this.pictureBox1); break;

            case "逆时针旋转": ImageHandle.XuanZhuan90(bmp, this.pictureBox1); break;

            case "顺时针旋转": ImageHandle.XuanZhuan270(bmp, this.pictureBox1); break;

            case "分块": ImageHandle.FenKuai(bmp, this.pictureBox1); break;

            case "积木": ImageHandle.JiMu(bmp, this.pictureBox1); break;

            case "马赛克": ImageHandle.MaSaiKe(bmp, this.pictureBox1); break;

            case "自动旋转": ImageHandle.XuanZhuan(bmp, this.pictureBox1); break;

            case "上下对接": ImageHandle.DuiJie_ShangXia(bmp, this.pictureBox1); break;

            case "左右对接": ImageHandle.DuiJie_ZuoYou(bmp, this.pictureBox1); break;

            case "左右翻转": ImageHandle.FanZhuan_ZuoYou(bmp, this.pictureBox1); break;

            case "四周扩散": ImageHandle.KuoSan(bmp, this.pictureBox1); break;

            case "上下拉伸": ImageHandle.LaShen_ShangDaoXiao(bmp, this.pictureBox1); break;
            }
        }
        //public string NewGroupPicture;
        /// <summary>
        /// 更新讨论组
        /// </summary>
        private void UpdateGroup()
        {
            if (GroupInfo == null)
            {
                return;
            }
            AntSdkUpdateGroupInput input = new AntSdkUpdateGroupInput();

            input.userId       = AntSdkService.AntSdkLoginOutput.userId;
            input.groupId      = this.GroupInfo.groupId;
            NewGroupMemberList = new List <AntSdkContact_User>();
            foreach (ContactInfoViewModel vm in GroupMemberList)
            {
                if (!OriginalMemberIds.Contains(vm.User.userId))
                {
                    if (input.userIds == null)
                    {
                        input.userIds = new List <string>();
                    }
                    input.userIds.Add(vm.User.userId);
                    if (input.userNames == null)
                    {
                        input.userNames = new List <string>();
                    }
                    input.userNames.Add(vm.User.userName);
                    NewGroupMemberList.Add(vm.User);
                }
            }
            if (NewGroupMemberList.Count != 0)
            {
                BaseOutput output  = new BaseOutput();
                var        errCode = 0;
                string     errMsg  = string.Empty;
                //TODO:AntSdk_Modify
                //DONE:AntSdk_Modify
                var isResult = AntSdkService.UpdateGroup(input, ref errCode, ref errMsg);
                if (!isResult)
                {
                    NewGroupMemberList = null;
                    MessageBoxWindow.Show(errMsg, GlobalVariable.WarnOrSuccess.Warn);
                    return;
                }
                //if (!(new HttpService()).UpdateGroup(input, ref output, ref errMsg))
                //{
                //    NewGroupMemberList = null;
                //    if (output.errorCode != "1004")
                //    {
                //        MessageBoxWindow.Show(errMsg,GlobalVariable.WarnOrSuccess.Warn);
                //    }
                //    return;
                //    //OnUpdateGroupEvent(input.groupId, input.userIds);
                //}
                string[] ThreadParams = new string[3];
                ThreadParams[0] = this.GroupInfo.groupId;
                ThreadParams[1] = ImageHandle.GetGroupPicture(GroupMemberList.Select(c => c.Photo).ToList());
                ThreadParams[2] = string.IsNullOrEmpty(this.GroupInfo.groupName) ? "" : this.GroupInfo.groupName;
                Thread UpdateGroupPictureThread = new Thread(GroupPublicFunction.UpdateGroupPicture);
                UpdateGroupPictureThread.Start(ThreadParams);
                //this.NewGroupPicture = input.groupPicture;
            }
            App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                this.close.Invoke();
            }));
        }
        private void CreateGroup()
        {
            // 讨论组名不能为空
            //if (string.IsNullOrWhiteSpace(GroupName))
            //{
            //    GroupNameBorderBrush = new SolidColorBrush(Colors.Red);
            //    //GroupNameBorderThickness = new Thickness(1, 1, 1, 1);
            //    return;
            //}
            //else
            //{
            //    GroupNameBorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#e0e0e0"));
            //    //GroupNameBorderThickness = new Thickness(0);
            //}
            // 讨论组成员不能少于3
            if (GroupMemberList == null || GroupMemberList.Count < 3)
            {
                MessageBoxWindow.Show("讨论组至少需要包括三个成员", GlobalVariable.WarnOrSuccess.Warn);
                return;
            }
            if (string.IsNullOrWhiteSpace(GroupName.Trim(' ')))//自定义群名为空 取默认值
            {
                GroupName = GetNewGroupName();
            }
            GroupName = GroupName.TrimStart(' ');
            #region 旧代码
            CreateGroupInput input = new CreateGroupInput();
            input.token     = AntSdkService.AntSdkLoginOutput.token;
            input.version   = GlobalVariable.Version;
            input.userId    = AntSdkService.AntSdkLoginOutput.userId;
            input.groupName = GroupName;
            //获取讨论组成员头像
            //List<string> picList = new List<string>();
            //foreach (ContactInfoViewModel m in GroupMemberList)
            //{
            //    picList.Add(m.Photo);
            //}
            //input.groupPicture = ImageHandle.GetGroupPicture(picList);
            //input.groupPicture =;
            input.userIds = string.Join(",", GroupMemberList.Select(c => c.User.userId).ToArray());
            //CreateGroupOutput output = new CreateGroupOutput();
            var errCode = 0;
            var errMsg  = string.Empty;

            //if (!(new HttpService()).CreateGroup(input, ref output, ref errMsg))
            //{
            //    if (output.errorCode != "1004")
            //    {
            //        MessageBoxWindow.Show(errMsg,GlobalVariable.WarnOrSuccess.Warn);
            //    }
            //    return;
            //}
            //output.group.groupPicture = ImageHandle.GetGroupPicture(GroupMemberList.Select(c => c.Photo).ToList());
            //ThreadPool.QueueUserWorkItem(m =>
            //{

            //});
            #endregion

            AntSdkCreateGroupInput newGroupInput = new AntSdkCreateGroupInput();
            newGroupInput.userId    = AntSdkService.AntSdkLoginOutput.userId;
            newGroupInput.groupName = GroupName;
            newGroupInput.userIds   = GroupMemberList.Select(c => c.User.userId).ToArray();
            //newGroupInput.groupPicture = ImageHandle.GetGroupPicture(GroupMemberList.Select(c => c.Photo).ToList());
            //TODO:AntSdk_Modify
            //DONE:AntSdk_Modify
            AntSdkCreateGroupOutput createGroupOutput = AntSdkService.CreateGroup(newGroupInput, ref errCode, ref errMsg);
            if (createGroupOutput == null)
            {
                if (!AntSdkService.AntSdkIsConnected)
                {
                    errMsg = "网络已断开,请检查网络";
                }
                if (!string.IsNullOrEmpty(errMsg))
                {
                    MessageBoxWindow.Show(errMsg, GlobalVariable.WarnOrSuccess.Warn);
                }
                return;
            }
            createGroupOutput.groupPicture = ImageHandle.GetGroupPicture(GroupMemberList.Select(c => c.Photo).ToList());
            //异步更新讨论组头像,这里需要用前台线程,因此不能用线程池
            string[] ThreadParams = new string[3];
            ThreadParams[0] = createGroupOutput.groupId;
            ThreadParams[1] = createGroupOutput.groupPicture;
            ThreadParams[2] = string.IsNullOrEmpty(createGroupOutput.groupName) ? "" : createGroupOutput.groupName;
            Thread UpdateGroupPictureThread = new Thread(GroupPublicFunction.UpdateGroupPicture);
            UpdateGroupPictureThread.Start(ThreadParams);
            this.CreateGroupOutput = createGroupOutput;
            App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                this.close.Invoke();
            }));
        }
        public bool GetImageRGBA(ImageHandle image, System.IntPtr buffer, int bufferSize)
        {
            CheckIfUsable();

            return(NativeMethods.Utils_GetImageRGBA(image.AsInt32, buffer, bufferSize));
        }