コード例 #1
0
        public ItemProjetoResumo(Glass.Data.Model.ItemProjeto itemProjeto)
        {
            IdItemProjeto   = (int)itemProjeto.IdItemProjeto;
            IdProjetoModelo = (int)itemProjeto.IdProjetoModelo;
            Valor           = itemProjeto.Total.ToString("c", new CultureInfo("pt-BR"));
            ImageUrl        = itemProjeto.ImagemUrlMini.Replace("~/", ServiceLocator.Current.GetInstance <Glass.Api.IConfiguracao>().EnderecoServicoImagem);
            CodigoModelo    = itemProjeto.CodigoModelo;
            IdCorVidro      = (int)itemProjeto.IdCorVidro;
            EspessuraVidro  = itemProjeto.EspessuraVidro;

            if (!ImageUrl.StartsWith(ServiceLocator.Current.GetInstance <Glass.Api.IConfiguracao>().EnderecoServicoImagem))
            {
                ImageUrl = string.Format("{0}{1}", ServiceLocator.Current.GetInstance <Glass.Api.IConfiguracao>().EnderecoServicoImagem, ImageUrl);
            }

            Ambiente = itemProjeto.Ambiente;

            var materiais = Glass.Data.DAL.MaterialItemProjetoDAO.Instance.GetList(itemProjeto.IdItemProjeto, string.Empty, 0, 1);

            if (materiais.FirstOrDefault() != null)
            {
                ValorCobradoM2   = materiais.FirstOrDefault().Valor.ToString("c", new CultureInfo("pt-BR"));
                DescricaoProduto = materiais.FirstOrDefault().DescrProduto;
            }
        }
コード例 #2
0
        public async Task <IActionResult> Recognize(string photoId)
        {
            var      photoUrl = _imageStorageService.UriFor(photoId);
            ImageUrl imgUrl   = new ImageUrl {
                Url = photoUrl
            };


            RecognizeViewModel recognizeViewModel = new RecognizeViewModel()
            {
                PhotoURL        = photoUrl,
                ImagePrediction = await endpoint.PredictImageUrlAsync(projectID, imgUrl)
            };

            ////
            //recognize from current default project
            //var defaultProject = _context.DefaultProjectHistories.OrderByDescending(x => x.SettingTime).FirstOrDefault();
            //Guid projectPredictionID;
            //if (defaultProject != null)
            //    projectPredictionID = defaultProject.MyProjectId;
            //else
            //    projectPredictionID = projectID;


            //RecognizeViewModel recognizeViewModel = new RecognizeViewModel()
            //{
            //    PhotoURL = photoUrl,
            //    ImagePrediction = await endpoint.PredictImageUrlAsync(projectPredictionID, imgUrl)
            //};
            ////

            //RecognizeViewModel recognizeViewModel = new RecognizeViewModel()
            //{
            //    PhotoURL = photoUrl,
            //    ImagePrediction = await endpoint.PredictImageUrlAsync(projectID, imgUrl)
            //};


            //RecognizeViewModel recognizeViewModel;

            //var proj = _context.DefaultProjectHistories.OrderByDescending(x => x.SettingTime).FirstOrDefault();
            //if (proj != null)
            //{
            //    recognizeViewModel = new RecognizeViewModel()
            //    {
            //        PhotoURL = photoUrl,
            //        ImagePrediction = await endpoint.PredictImageUrlAsync(proj.MyProjectId, imgUrl)
            //    };
            //}
            //else
            //{
            //    recognizeViewModel = new RecognizeViewModel()
            //    {
            //        PhotoURL = photoUrl,
            //        ImagePrediction = await endpoint.PredictImageUrlAsync(projectID, imgUrl)
            //    };
            //}

            return(View(recognizeViewModel));
        }
コード例 #3
0
        public ActionResult Add(NewMovieViewModel model)
        {
            var data           = this.CinemaShowDbContext;
            var contentManager = new ServerContentManager();
            var categories     = data.Categories;
            var path           = contentManager.UploadFile(model.Image, DateTime.Now);

            var imageUrl = new ImageUrl
            {
                Id  = Guid.NewGuid(),
                Url = path
            };

            data.ImageUrls.Add(imageUrl);

            var movie = new Movie
            {
                Id          = Guid.NewGuid(),
                Title       = model.Title,
                Description = model.Description,
                Image       = imageUrl,
                YoutubeUrl  = model.YoutubeUrl,
                Price       = model.Price
            };

            foreach (var category in model.Categories)
            {
                var currentCategory = categories.FirstOrDefault(c => c.Name.ToLower() == category.ToLower());
                movie.Categories.Add(currentCategory);
            }

            data.Movies.Add(movie);
            data.SaveChanges();
            return(this.RedirectToAction("Index", "Home"));
        }
コード例 #4
0
        private string ImageUpload()
        {
            List <ImageUrl> OthrContntPicTempFileUrlList = new List <ImageUrl>();
            ImageUrl        imageUrl = new ImageUrl();

            try
            {
                if (FileUploadImage.HasFile)
                {
                    string now = "";
                    now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff", CultureInfo.InvariantCulture);
                    //take only letter or digit
                    var sb = new StringBuilder();
                    foreach (char t in now.Where(char.IsLetterOrDigit))
                    {
                        sb.Append(t);
                    }
                    now = sb.ToString();//save to now string
                    var    rnd = new Random(100000);
                    var    tempMatImageName = now + rnd.Next();
                    string path             = Server.MapPath("~/Image/OtherContentImage/");
                    FileUploadHelper.BindImage(FileUploadImage, path, tempMatImageName, 800, 800);
                    imageUrl.ImageUrlTemp = "~/Image/OtherContentImage/" + tempMatImageName + Path.GetExtension(FileUploadImage.FileName);

                    return(imageUrl.ImageUrlTemp.ToString());
                }
                return(imageUrl.ImageUrlTemp.ToString());
            }
            catch (Exception ex)
            {
                labelMessageOtherContent.Text = "error: " + ex.Message;
            }
            return(imageUrl.ImageUrlTemp.ToString());
        }
コード例 #5
0
        public async Task <ThumbnailResponse> FindImageAsync(Uri uri)
        {
            try
            {
                HttpResponseMessage response = await Policies.HttpPolicy.ExecuteAsync(
                    _ => client.GetAsync(uri),
                    new Dictionary <string, object> {
                    { "uri", uri }
                });

                using (response)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        Log.FindThumbnailServerError(uri, response);
                        return(null);
                    }

                    string mediaType = response.Content.Headers.ContentType?.MediaType ?? "";
                    if (mediaType.Contains("image"))
                    {
                        var iu = new ImageUrl {
                            Uri = uri, Kind = "Direct"
                        };
                        ThumbnailResponse result = await FetchThumbnailAsync(iu, uri, skipChecks : true);

                        if (result != null)
                        {
                            ThumbnailLog.LogThumbnail(uri, uri, iu.Kind, result, "Best");
                        }
                        return(result);
                    }

                    if (mediaType.Contains("html"))
                    {
                        using (Stream stream = await response.Content.ReadAsStreamAsync())
                        {
                            var           parser   = new HtmlParser();
                            IHtmlDocument document = await parser.ParseDocumentAsync(stream);

                            return(await FindThumbnailInSoupAsync("item_document", uri, document));
                        }
                    }
                }
            }
            catch (TaskCanceledException)
            {
                Log.FindThumbnailTimeout(uri);
            }
            catch (HttpRequestException hre)
            {
                Log.FindThumbnailNetworkError(uri, hre);
            }
            catch (WebException we)
            {
                Log.FindThumbnailNetworkError(uri, we);
            }

            return(null);
        }
コード例 #6
0
ファイル: Button.cs プロジェクト: akhuang/Zing
        public override void WriteInitializationScript(System.IO.TextWriter writer)
        {
            var options = new Dictionary <string, object>(Events);

            if (ImageUrl.HasValue())
            {
                options["imageUrl"] = ImageUrl;
            }

            if (SpriteCssClass.HasValue())
            {
                options["spriteCssClass"] = SpriteCssClass;
            }

            if (Icon.HasValue())
            {
                options["icon"] = Icon;
            }

            if (Enable == false)
            {
                options["enable"] = Enable;
            }

            writer.Write(Initializer.Initialize(Selector, "Button", options));

            base.WriteInitializationScript(writer);
        }
コード例 #7
0
        public AppModel()
        {
            // JPEG ファイルは DPI が異なる場合があります (既定では 96 だが、72 などもある)。
            // Image コントロールに直接読み込ませると、DPI によりサイズが変化してしまいます。
            ImageUrl
            .Subscribe(u =>
            {
                var image = new BitmapImage(new Uri(u));

                // ダウンロードの要否で分岐します。
                if (image.IsDownloading)
                {
                    image.DownloadCompleted += (o, e) => BitmapImage.Value = image;
                }
                else
                {
                    BitmapImage.Value = image;
                }
            });
            ImageUrl
            .Subscribe(_ => DetectAsync());

            IsImageEmpty = ImageUrl
                           .Select(u => u == null)
                           .ToReadOnlyReactiveProperty(true);
        }
コード例 #8
0
ファイル: ItunesFeed.cs プロジェクト: mythocalos/dotnetage
        protected override void WriteElementExtensions(XmlWriter writer, string version)
        {
            WriteItunesElement(writer, "subtitle", Subtitle);
            WriteItunesElement(writer, "author", Author);
            WriteItunesElement(writer, "summary", Summary);
            if (ImageUrl != null)
            {
                WriteItunesElement(writer, "image", ImageUrl.ToString());
            }
            WriteItunesElement(writer, "explicit", Explicit ? "yes" : "no");

            writer.WriteStartElement(prefix, "owner", @namespace);
            WriteItunesElement(writer, "name", OwnerName);
            WriteItunesElement(writer, "email", OwnerEmail);
            writer.WriteEndElement();

            foreach (var category in ItunesCategories)
            {
                writer.WriteStartElement(prefix, "category", @namespace);
                writer.WriteAttributeString("text", category[0]);
                if (category.Count == 2)
                {
                    writer.WriteStartElement(prefix, "category", @namespace);
                    writer.WriteAttributeString("text", category[1]);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }
        }
コード例 #9
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getprediction")] HttpRequest req,
            ILogger log)
        {
            string imgLink = req.Query["img"];

            if (IsValidImgLink(imgLink))
            {
                var imageUrl        = new ImageUrl(imgLink);
                var projectId       = Guid.Parse(Environment.GetEnvironmentVariable("CustomVisionProjectId"));
                var publishedName   = Environment.GetEnvironmentVariable("CustomVisionPublishedName");
                var imagePrediction = await _customVisionPredictionClient.ClassifyImageUrlAsync(
                    projectId,
                    publishedName,
                    imageUrl);

                var highestPrediction = imagePrediction.Predictions
                                        .OrderByDescending(prediction => prediction.Probability)
                                        .First();
                var message = $"This looks like {highestPrediction.TagName}! I'm {highestPrediction.Probability} certain of it 🤓.";

                return(new OkObjectResult(message));
            }
            else
            {
                return(new BadRequestObjectResult("Please provide an image url (png/jp(e)g/gif) in the `img` query parameter."));
            }
        }
コード例 #10
0
        public static async Task <ImagePrediction> PredictImageURL(Guid projectID, string modelName, string url)
        {
            ImageUrl imageUrl = new ImageUrl(url);

            ImagePrediction result = null;

            try
            {
                result = await endpoint.ClassifyImageUrlAsync(projectID, modelName, imageUrl);

                Console.WriteLine($"\nSuccessfully retrieved predictions for image '{url}'.");
            }
            catch (Exception e)
            {
                Console.WriteLine($"\n{e.GetType().Name}: {e.Message} \nCould not get prediction for image '{url}'.");
            }

            // Loop over each prediction and write out the results
            if (result != null)
            {
                foreach (var c in result.Predictions)
                {
                    Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}");
                }
            }

            return(result);
        }
コード例 #11
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            HttpResponse response = context.HttpContext.Response;

            try
            {
                var image = new ImageUrl {
                    Url = (string)context.Object
                };
                if (image == null)
                {
                    return;
                }

                using (WebClient client = new WebClient())
                {
                    byte[] imageData = await client.DownloadDataTaskAsync(image.Url);;
                    response.Body.Write(imageData);
                }
            }
            catch (Exception ex)
            {
                await response.WriteAsync("Error check the url in AircraftController");
            }
        }
コード例 #12
0
    void Start()
    {
        // setup the request header
        RequestHeader clientSecurityHeader = new RequestHeader {
            Key   = clientId,
            Value = clientSecret
        };

        // setup the request header
        RequestHeader contentTypeHeader = new RequestHeader {
            Key   = "Content-Type",
            Value = "application/json"
        };

        // validation
        if (string.IsNullOrEmpty(imageToOCR))
        {
            Debug.LogError("imageToOCR needs to be set through the inspector...");
            return;
        }

        // build image url required by Azure Vision OCR
        ImageUrl imageUrl = new ImageUrl {
            Url = imageToOCR
        };

        // send a post request
        StartCoroutine(RestWebClient.Instance.HttpPost(baseUrl, JsonUtility.ToJson(imageUrl), (r) => OnRequestComplete(r), new List <RequestHeader>
        {
            clientSecurityHeader,
            contentTypeHeader
        }));
    }
コード例 #13
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ImageUrl.Length != 0)
            {
                hash ^= ImageUrl.GetHashCode();
            }
            if (PageUrl.Length != 0)
            {
                hash ^= PageUrl.GetHashCode();
            }
            if (Title.Length != 0)
            {
                hash ^= Title.GetHashCode();
            }
            if (Description.Length != 0)
            {
                hash ^= Description.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
コード例 #14
0
        private static ImageUrl DownloadBlogImgToLocal(string blogImgUrl)
        {
            ImageUrl imageUrl = new ImageUrl();
            string   fileName = CrawlerUtility.GetFileContent(blogImgUrl, Const.BlogFileDirectory, "http://www.zimuzu.tv/");

            if (fileName == "")
            {
                return(null);
            }
            string localFilePath = Const.BlogFileDirectory + fileName;

            using (Image downloadImage = Image.FromFile(localFilePath))
            {
                if (downloadImage.Size.Width > 500)
                {
                    var image = Domain.Helper.ImgHandler.ZoomPictureProportionately(downloadImage, 500, 500 * downloadImage.Size.Height / downloadImage.Size.Width);
                    image.Save(localFilePath);
                }
            }

            string yunUrl = UploadUtility.UploadLocalFile(localFilePath);

            Console.WriteLine("localFile:{0} upload to yunUrl:{1}", localFilePath, yunUrl);
            imageUrl.Url         = fileName;
            imageUrl.ImageStatus = ImageStatus.Local;
            imageUrl.TimeStamp   = DateTime.Now;
            if (!string.IsNullOrEmpty(yunUrl))
            {
                imageUrl.YunUrl      = yunUrl;
                imageUrl.ImageStatus = ImageStatus.Yun;
            }
            return(imageUrl);
        }
コード例 #15
0
 public override int GetHashCode()
 {
     return(Name.GetHashCode() +
            Price.GetHashCode() +
            ExternalUrl.GetHashCode() +
            ImageUrl.GetHashCode());
 }
コード例 #16
0
 protected override bool _Equals(TaskDict other)
 {
     return(Directions.Equals(other.Directions) &&
            AudioUrl.Equals(other.AudioUrl) &&
            ImageUrl.Equals(other.ImageUrl) &&
            Location.Equals(other.Location));
 }
コード例 #17
0
ファイル: JsonPhotoContainer.cs プロジェクト: db42/FBReader
 public ImageUrl ConvertToImageUrl()
 {
     string largePicUrl = this.source;
     string smallPicUrl = this.picture;
     ImageUrl image = new ImageUrl(smallPicUrl, largePicUrl);
     return image;
 }
コード例 #18
0
        public Feed(RssSchema schema)
        {
            Title   = schema.Title ?? "";
            Summary = schema.Summary ?? "";
            Content = schema.Content ?? "";
            string theme = AppTools.GetLocalSetting(Enums.AppSettings.Theme, "Light").ToLower();

            ImageUrl = schema.ImageUrl;
            if (string.IsNullOrEmpty(ImageUrl))
            {
                ImgVisibility = Visibility.Collapsed;
            }
            else if (ImageUrl.StartsWith("//"))
            {
                ImageUrl = "http:" + ImageUrl;
            }
            ExtraImageUrl = schema.ExtraImageUrl ?? "";
            MediaUrl      = schema.MediaUrl ?? "";
            InternalID    = schema.InternalID;
            FeedUrl       = schema.FeedUrl;
            Author        = schema.Author ?? AppTools.GetReswLanguage("App_NoAuthor");
            Date          = schema.PublishDate.ToString(AppTools.GetReswLanguage("App_DateFormat"));
            Categories    = schema.Categories;
            if (Categories == null || Categories.Count() == 0)
            {
                TagVisibility = Visibility.Collapsed;
            }
        }
コード例 #19
0
        public OperationResult <ImageUrl> UploadImage(HttpPostedFileBase file, int blogId)
        {
            if (file.ContentLength > 0)
            {
                string fileName = DateTime.Now.ToString("yy/MM/dd/") + Guid.NewGuid().ToString("N") +
                                  Path.GetExtension(file.FileName);
                string diskPath = HttpContext.Current.Server.MapPath("~" + ConstValues.BlogImageDirectory + fileName);
                string diskDir  = diskPath.Substring(0, diskPath.LastIndexOf("\\", StringComparison.Ordinal));
                if (!Directory.Exists(diskDir))
                {
                    Directory.CreateDirectory(diskDir);
                }
                file.SaveAs(diskPath);
                string yunUrl   = UploadUtility.UploadLocalFile(diskPath);
                var    imageUrl = new ImageUrl()
                {
                    BlogId      = blogId,
                    Url         = fileName.Replace('/', '\\'),
                    TimeStamp   = DateTime.Now,
                    YunUrl      = yunUrl,
                    ImageStatus = string.IsNullOrEmpty(yunUrl) ? ImageStatus.Local : ImageStatus.Yun
                };

                _context.ImageUrls.Add(imageUrl);
                _context.SaveChanges();
                if (string.IsNullOrEmpty(yunUrl))
                {
                    imageUrl.Url = "http://www.withyun.com" + ConstValues.BlogImageDirectory + fileName;
                }

                return(new OperationResult <ImageUrl>(true, imageUrl));
            }
            return(new OperationResult <ImageUrl>(false, null));
        }
コード例 #20
0
            public ImageUrl ConvertToImageUrl()
            {
                string   largePicUrl = this.source;
                string   smallPicUrl = this.picture;
                ImageUrl image       = new ImageUrl(smallPicUrl, largePicUrl);

                return(image);
            }
コード例 #21
0
        /// <summary>
        /// Changes the pass code.
        /// </summary>
        /// <param name="newPassCode">The new pass code.</param>
        /// <returns>Returns true if operation was successful.</returns>
        public Card ChangePassCode(int newPassCode)
        {
            ImageUrl.Replace(PassCode.ToString(), newPassCode.ToString());
            SmallImageUrl.Replace(PassCode.ToString(), newPassCode.ToString());
            PassCode = newPassCode;

            return(this);
        }
コード例 #22
0
        public ImageUrl GenProfileImageUrl(string userid)
        {
            string   large_pic_url = "https://graph.facebook.com/" + userid + "/picture?type=large";
            string   small_pic_url = "https://graph.facebook.com/" + userid + "/picture";
            ImageUrl image         = new ImageUrl(small_pic_url, large_pic_url);

            return(image);
        }
コード例 #23
0
        public ImageUrl test()
        {
            var rng = new Random();
            var x   = new ImageUrl();

            x.image_url = "https://edge.alluremedia.com.au/uploads/businessinsider/2017/05/hang-glider.jpg";
            return(x);
            //return "{\"image_url\":\"https:\/\/media1.giphy.com\/media\/MjiO4GHq4LpGE\/giphy.gif\","
        }
コード例 #24
0
        public ImageUrl Add(ImageUrl image)
        {
            var blog = _context.Blogs.First(b => b.Id == image.BlogId);

            blog.HtmlContent = "<html><body><p><img src='" + image.YunUrl + "' /></p>" + blog.HtmlContent.Remove(0, 12);
            _context.ImageUrls.Add(image);
            _context.SaveChanges();
            return(image);
        }
コード例 #25
0
 /// <summary>
 /// Associa ImageUrl com Breeds. Antes verifica se já existe associação, caso não,
 /// insere na tabela de associação
 /// </summary>
 /// <param name="imageUrl"></param>
 /// <returns></returns>
 async Task AssociateImageUrlToBreeds(ImageUrl imageUrl)
 {
     using (var conn = theCatContext.GetConnection)
     {
         var result = await conn.QueryFirstAsync <int>(
             @$ "SELECT count(*) as nrec
                FROM ImageUrlBreeds
                WHERE ImageUrlId = '{imageUrl.ImageUrlId}'
                  AND BreedsId = '{imageUrl.Breeds.BreedsId}'"
コード例 #26
0
        public IActionResult UpdateImg(ImageUrl url)
        {
            var user = GetCurrentUserProfile();

            user.ImageLocation = url.ImageLocation;
            _repo.Update(user);

            return(Ok(user));
        }
コード例 #27
0
 private void InvokeCognitive(string photoUrl)
 {
     PredictionEndpoint endpoint = new PredictionEndpoint()
     {
         ApiKey = PREDICTION_KEY
     };
     ImageUrl url    = new ImageUrl(photoUrl);
     var      result = endpoint.PredictImageUrl(new Guid("152a2f03-5840-46b4-acfe-987a8342b47e"), url);
 }
コード例 #28
0
        async Task <ThumbnailResponse> FetchThumbnailAsync(ImageUrl imageUrl, Uri referrer, bool skipChecks = false)
        {
            try
            {
                // N.B.: We put the whole bit of cache logic in here because somebody might succeed or fail altogether
                //       while we wait on retries, and we want to re-check the cache on every loop.
                return(await Policies.HttpPolicy.ExecuteAsync(async _ =>
                {
                    object cachedObject = imageCache.Get(imageUrl.Uri.AbsoluteUri);
                    if (cachedObject is string)
                    {
                        Log.ThumbnailErrorCacheHit(referrer, imageUrl.Uri, cachedObject);
                        return null;
                    }
                    if (cachedObject is ThumbnailResponse)
                    {
                        Log.ThumbnailSuccessCacheHit(referrer, imageUrl.Uri);
                        return (ThumbnailResponse)cachedObject;
                    }

                    ThumbnailResponse response = await this.thumbnailServiceClient.GetThumbnail(
                        imageUrl.Uri,
                        skipChecks: skipChecks,
                        referrer: referrer
                        );
                    if (response.Error != null)
                    {
                        ThumbnailLog.LogThumbnail(referrer, imageUrl.Uri, imageUrl.Kind, null, response.ErrorString());
                        CacheError(imageUrl, response.ErrorString());
                        return null;
                    }

                    return CacheSuccess(imageUrl, response);
                },
                                                              new Dictionary <string, object> {
                    { "uri", imageUrl.Uri }
                }));
            }
            catch (TaskCanceledException tce)
            {
                ThumbnailLog.LogThumbnail(referrer, imageUrl.Uri, imageUrl.Kind, null, "Timeout");
                CacheError(imageUrl, tce.Message);
                return(null);
            }
            catch (HttpRequestException hre)
            {
                ThumbnailLog.LogThumbnail(referrer, imageUrl.Uri, imageUrl.Kind, null, "NetworkError", hre);
                CacheError(imageUrl, hre.Message);
                return(null);
            }
            catch (WebException we)
            {
                ThumbnailLog.LogThumbnail(referrer, imageUrl.Uri, imageUrl.Kind, null, "NetworkError", we);
                CacheError(imageUrl, we.Message);
                return(null);
            }
        }
コード例 #29
0
ファイル: Image.cs プロジェクト: jraghu24/Rraghu
        protected override void Render(HtmlTextWriter writer)
        {
            int  id;
            bool hasid  = int.TryParse(NodeId, out id);
            int? nodeId = hasid ? id : (int?)null;

            Src = ImageUrl.GetImageUrl(Src, Field, Provider, Parameters, nodeId);
            base.Render(writer);
        }
コード例 #30
0
        public bool Update(ImageUrl image)
        {
            var    blog       = _context.Blogs.First(b => b.Id == image.BlogId);
            string orignalUrl = "http://www.withyun.com" + ConstValues.BlogImageDirectory + image.Url.Replace('\\', '/');

            blog.HtmlContent = blog.HtmlContent.Replace(orignalUrl, image.YunUrl);
            _context.ImageUrls.Attach(image);
            return(_context.SaveChanges() > 0);
        }
コード例 #31
0
        /// <summary>
        /// 获取图片路径
        /// </summary>
        /// <param name="days">倒数第几天</param>
        /// <returns></returns>
        public string GetBingURL(int days = 0)
        {
            string InfoUrl = $"http://cn.bing.com/HPImageArchive.aspx?idx={days}&n=1";
            CoreEngine.Current.Logger.Info($"Bing查询接口:{InfoUrl}");
            string ImageUrl;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InfoUrl);
                request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8";
                string XmlString;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream myResponseStream = response.GetResponseStream();
                    using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8))
                    {
                        XmlString = myStreamReader.ReadToEnd();
                    }
                }
                //===------
                // 定义正则表达式用来匹配标签
                Regex regImg = new Regex("<Url>(?<imgUrl>.*?)</Url>", RegexOptions.IgnoreCase);
                // 搜索匹配的字符串
                MatchCollection matches = regImg.Matches(XmlString);
                // 取得匹配项列表
                ImageUrl = "http://www.bing.com" + matches[0].Groups["imgUrl"].Value;
                //===------
                if (days == 0)//保存copyright
                {
                    CoreEngine.Current.Logger.Info("Bing查询接口:保存Image Copyright");
                    // 定义正则表达式用来匹配标签
                    Regex regCopyright = new Regex("<copyright>(?<imgCopyright>.*?)</copyright>", RegexOptions.IgnoreCase);
                    // 搜索匹配的字符串
                    MatchCollection matchesCopyright = regCopyright.Matches(XmlString);
                    // 取得匹配项列表
                    var copyright = matchesCopyright[0].Groups["imgCopyright"].Value;
                    CoreEngine.Current.AppSetting.SetCopyright(copyright);
                    CoreEngine.Current.Logger.Info($"Bing查询接口:Copyright:{copyright}");
                }
                //===------
                if (CoreEngine.Current.AppSetting.GetSizeMode == Model.ImageSizeType._720p)
                {
                    ImageUrl = ImageUrl.Replace("1920x1080", "1366x768");
                }
                else if (CoreEngine.Current.AppSetting.GetSizeMode == Model.ImageSizeType._1200p)
                {
                    ImageUrl = ImageUrl.Replace("1920x1080", "1920x1200");
                }
                CoreEngine.Current.Logger.Info($"Bing获取到接口的壁纸链接:{ImageUrl}");

                return ImageUrl;
            }
            catch
            {
                return null;
            }
        }