public async Task <TinyResponse> TinifyAsync(TImage tImage, IFileSystem fs) { byte[] imageBytes; TinyResponse tinyResponse; try { string path = fs.GetRelativePath(tImage.AbsoluteUrl); using (Stream file = fs.OpenFile(path)) { imageBytes = ReadFully(file); } tinyResponse = await TinifyByteArrayAsync(imageBytes).ConfigureAwait(false); } catch (Exception) { tinyResponse = new TinyResponse { Output = new TinyOutput { Error = PackageConstants.ImageDeleted, IsOptimized = false } }; } return(tinyResponse); }
public override void Initialize() { maze = new Maze(mazewidth, mazeheight); rec = new RecursiveBacktracer(maze); TImage image = new TImage(maze.Texture, mazewidth * 2 + 1, mazeheight * 2 + 1); MaterialDX11 material = new MaterialDX11("vDefault.cso", "pUnlit.cso"); SamplerState state = new SamplerState(ApplicationDX11.Instance.Device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = new Color4(0.0f, 1.0f, 0.0f, 1.0f), ComparisonFunction = Comparison.LessEqual, Filter = Filter.MinLinearMagMipPoint, MaximumAnisotropy = 0, MaximumLod = 0, MinimumLod = 0, MipLodBias = 0 }); material.samplers.Add(state); material.AddTexture(image.GetTexture2D()); Entity.AddComponent(new MeshRenderer(material, Quad.GetMesh())); }
public void Goin(string persionid, string name, string pic, Action nextStep) { //string p = "pic" + DateTime.Now.ToString("yyyyMMddHHmmss"); //string er = ""; //Base64ToJpg(pic, p, ref er); CD.business1.showBackAndExitBtn(); BackExit.LetNextClickToMain(); CD.business1.setBusinessValue(this); this.nextStep = nextStep; this.persionid.Text = persionid; this.name.Text = name; try { if (pic == null || pic == "") { this.pic.Visibility = Visibility.Hidden; } else { this.pic.Source = TImage.Base64ToImageSource(pic); this.pic.Visibility = Visibility.Visible; } } catch (Exception e) { Log.AddLog("ERROR", "照片base64数据解析失败:" + e.ToString() + " 照片数据:" + pic); this.pic.Visibility = Visibility.Hidden; } }
public void UpdateImageAfterSuccessfullRequest(TinyResponse tinyResponse, TImage image, IFileSystem fs) { int.TryParse(image.Id, out var id); // download optimized image var tImageBytes = _tinyImageService.DownloadImage(tinyResponse.Output.Url); // preserve image metadata if (_settingsService.GetSettings().PreserveMetadata) { var originImageBytes = image.ToBytes(fs); PreserveImageMetadata(originImageBytes, ref tImageBytes); } // httpContext is null when optimization on upload // https://our.umbraco.org/projects/backoffice-extensions/tinifier/bugs/90472-error-systemargumentnullexception-value-cannot-be-null if (HttpContext.Current == null) { HttpContext.Current = new HttpContext(new SimpleWorkerRequest("dummy.aspx", "", new StringWriter())); } // update physical file UpdateMedia(image, tImageBytes); // update history _historyService.CreateResponseHistory(image.Id, tinyResponse); // update umbraco media attributes _imageRepository.Update(id, tinyResponse.Output.Size); // update statistic _statisticService.UpdateStatistic(); // update tinifying state _stateService.UpdateState(); }
private void IterateFilesAndTinifyFromMediaFolder(string pathForFolder, IEnumerable <FileInfo> files, ICollection <TImage> nonOptimizedImages, bool tinifyEverything) { foreach (var file in files) { var image = new TImage { Id = Path.Combine(pathForFolder, file.Name), Name = file.Name, AbsoluteUrl = Path.Combine(pathForFolder, file.Name) }; var imageHistory = _historyService.GetImageHistory(image.Id); if (imageHistory != null && imageHistory.IsOptimized) { continue; } if (tinifyEverything) { nonOptimizedImages.Add(image); } else { _imageService.OptimizeImageAsync(image).GetAwaiter().GetResult(); } } }
public TImage GetCropImage(string path) { if (string.IsNullOrEmpty(path)) { throw new EntityNotFoundException(); } var fileExt = Path.GetExtension(path).ToUpper().Replace(".", string.Empty).Trim(); if (!PackageConstants.SupportedExtensions.Contains(fileExt)) { throw new NotSupportedExtensionException(fileExt); } var tImage = new TImage { Id = path, Name = Path.GetFileName(path), AbsoluteUrl = path }; return(tImage); }
public void UpdateImageAfterSuccessfullRequest(TinyResponse tinyResponse, TImage image, IFileSystem fs) { // download optimized image var tImageBytes = TinyImageService.Instance.DownloadImage(tinyResponse.Output.Url); // preserve image metadata if (_settingsService.GetSettings().PreserveMetadata) { byte[] originImageBytes = image.ToBytes(fs); PreserveImageMetadata(originImageBytes, ref tImageBytes); } // update physical file base.UpdateMedia(image, tImageBytes); // update history _historyService.CreateResponseHistory(image.Id, tinyResponse); // update umbraco media attributes _imageRepository.Update(image.Id, tinyResponse.Output.Size); // update statistic var savedBytes = tinyResponse.Input.Size - tinyResponse.Output.Size; _statisticService.UpdateStatistic(); // update tinifying state _stateService.UpdateState(); }
public TImage GetImageById(int id) { var image = _imageRepository.GetByKey(id); if (image == null) { throw new EntityNotFoundException($"Image with such id doesn't exist. Id: {id}"); } if (!CheckExtension(image.Name)) { throw new Infrastructure.Exceptions.NotSupportedException(PackageConstants.NotSupported); } var path = image.GetValue("umbracoFile").ToString(); var tImage = new TImage { Id = id, Name = image.Name, Url = GetUrl(path) }; return(tImage); }
/// <summary> /// 设置Image指定图片(从Sprite Atlas里) /// </summary> /// <param name="timg">Image组件</param> /// <param name="atlasname">图集名</param> /// <param name="spritename">图片名</param> /// <param name="loadtype">资源加载类型</param> /// <param name="loadmethod">资源加载方式</param> /// <returns></returns> public void setImageSpriteAtlas(TImage timg, string atlasname, string spritename, ResourceLoadType loadtype = ResourceLoadType.NormalLoad, ResourceLoadMethod loadmethod = ResourceLoadMethod.Sync) { DIYLog.Assert(timg == null, "setImageSpriteAtlas不允许传空TImage!"); ResourceModuleManager.Singleton.requstResource(atlasname, (abi) => { DIYLog.Log("加载SpriteAtlas AB完成!"); // 清除老的资源引用 if (timg.ABI != null) { timg.ABI.releaseOwner(timg); } if (abi != null) { DIYLog.Log("加载SpriteAtlas之前!"); var spriteatlas = abi.getAsset <SpriteAtlas>(timg, atlasname); DIYLog.Log("加载SpriteAtlas之后!"); timg.sprite = spriteatlas.GetSprite(spritename); DIYLog.Log("SpriteAtlas.GetSprite()之后!"); } timg.ABI = abi; timg.AtlasName = atlasname; timg.SpriteName = spritename; }, loadtype, loadmethod); }
/// <summary> /// 设置TImage指定图片(单图的时候) /// </summary> /// <param name="timg">TImage组件</param> /// <param name="spritepath">Sprite路径</param> /// <param name="loadtype">资源加载类型</param> /// <param name="loadmethod">资源加载方式</param> /// <returns></returns> public void setTImageSingleSprite(TImage timg, string spritepath, ResourceLoadType loadtype = ResourceLoadType.NormalLoad, ResourceLoadMethod loadmethod = ResourceLoadMethod.Sync) { DIYLog.Assert(timg == null, "setTImageSingleSprite!"); ResourceModuleManager.Singleton.requstResource(spritepath, (abi) => { // 清除老的资源引用 if (timg.ABI != null && !string.IsNullOrEmpty(timg.AtlasPath)) { timg.ABI.releaseOwner(timg); } if (abi != null) { // Sprite统一为小写 var spritename = Path.GetFileNameWithoutExtension(spritepath).ToLower(); var sprite = abi.getAsset <Sprite>(timg, spritename); timg.sprite = sprite; timg.ABI = abi; timg.AtlasPath = spritepath; timg.SpriteName = spritename; } else { timg.ABI = null; timg.AtlasPath = string.Empty; timg.SpriteName = string.Empty; } }, loadtype, loadmethod); }
public async Task <TinyResponse> TinifyAsync(TImage tImage, IFileSystem fs) { TinyResponse tinyResponse; var path = tImage.AbsoluteUrl; int.TryParse(tImage.Id, out var id); var settings = _settingsService.GetSettings(); try { var imageBytes = GetImageBytesFromPath(tImage, fs, path); tinyResponse = await TinifyByteArrayAsync(imageBytes).ConfigureAwait(false); if (id > 0 && settings.EnableUndoOptimization) { _imageHistoryService.Create(tImage, imageBytes); } } catch (Exception) { tinyResponse = new TinyResponse { Output = new TinyOutput { Error = PackageConstants.ImageDeleted, IsOptimized = false } }; } return(tinyResponse); }
public IEnumerable <TImage> GetTopOptimizedImages() { using (IScope scope = scopeProvider.CreateScope()) { var database = scope.Database; var images = new List <TImage>(); var query = new Sql("SELECT ImageId, OriginSize, OptimizedSize, OccuredAt FROM TinifierResponseHistory WHERE IsOptimized = 'true'"); var optimizedImages = database.Fetch <TopImagesModel>(query); var historyIds = optimizedImages.OrderByDescending(x => (x.OriginSize - x.OptimizedSize)).Take(50) .OrderByDescending(x => x.OccuredAt).Select(y => y.ImageId); var pardesIds = new List <int>(); var croppedIds = new List <string>(); foreach (var historyId in historyIds) { if (int.TryParse(historyId, out var parsedId)) { pardesIds.Add(parsedId); } else { croppedIds.Add(historyId); } } var mediaItems = GetAll() .Where(item => pardesIds.Contains(item.Id)); foreach (var media in mediaItems) { var custMedia = new TImage { Id = media.Id.ToString(), Name = media.Name, AbsoluteUrl = GetAbsoluteUrl(media as Media) }; images.Add(custMedia); } foreach (var crop in croppedIds) { var custMedia = new TImage { Id = crop, Name = Path.GetFileName(crop), AbsoluteUrl = crop }; images.Add(custMedia); } return(images); } }
public override void Update() { if (start) { rec.DoOneStep(); TImage image = new TImage(maze.Texture, mazewidth * 2 + 1, mazeheight * 2 + 1); Resource tex = image.GetTexture2D(); ((MeshRenderer)Entity.GetComponent(ComponentType.MeshRenderer)).material_.SetTexture(0, tex); Utilities.Dispose <Resource>(ref tex); } }
/// <summary> /// Update physical media file, method depens on FileSystemProvider /// </summary> /// <param name="image"></param> /// <param name="optimizedImageBytes"></param> protected void UpdateMedia(TImage image, byte[] optimizedImageBytes) { string path = FileSystem.GetRelativePath(image.AbsoluteUrl); //if (!FileSystem.FileExists(path)) // throw new InvalidOperationException("Physical media file doesn't exist in " + path); using (Stream stream = new MemoryStream(optimizedImageBytes)) { FileSystem.AddFile(path, stream, true); } }
/// <summary> /// Get image list from different round at the start of each round /// </summary> /// <param name="n">the round to get the image list from</param> /// <returns>the image list</returns> public List <TImage> OnRoundStart(int n) { List <TImage> roundimage12 = new List <TImage>(); for (int i = 0; i < initialTestImages.Count; i++) { TImage tmp = new TImage(initialTestImages[i]); roundimage12.Add(tmp); } return(roundimage12); }
/// <summary> /// Read bytes from TImage based on File System /// </summary> /// <param name="tImage">TImage</param> /// <param name="fs">Umbraco file system (default or Azure)</param> /// <returns></returns> public static byte[] ToBytes(this TImage tImage, IFileSystem fs) { byte[] data; string path = fs.GetRelativePath(tImage.AbsoluteUrl); using (Stream fileStream = fs.OpenFile(path)) { data = fileStream.ToBytes(); } return(data); }
public async Task OptimizeImageAsync(TImage image) { _stateService.CreateState(1); var tinyResponse = await _tinyPngConnectorService.TinifyAsync(image, base.FileSystem).ConfigureAwait(false); if (tinyResponse.Output.Url == null) { _historyService.CreateResponseHistory(image.Id, tinyResponse); return; } UpdateImageAfterSuccessfullRequest(tinyResponse, image, base.FileSystem); SendStatistic(); }
/// <summary> /// The first part of Image Hit is over /// If the player has done all the correct operations in the first ten images, they will choose three random images to join the image list and start the second part game. /// If the player makes less than 7 errors in the first ten images, the wrong images and three random correct images will be added to the image list to start the second part of the game. /// If the player makes 7 or more errors in the first ten images, the ten images will be re-added to the image list to enter the second stage of the game. /// </summary> public void OnRound1Over() { List <TImage> correctImages = new List <TImage>(); List <TImage> incorrectImages = new List <TImage>(); int correctCount = 0; TImage img = null; for (int i = 0; i < currentRoundTestData.Count; i++) { img = FindImage(currentRoundTestImages, currentRoundTestData[i]); // To know which image it is during the current round if (currentRoundTestData[i].isCorrectlyIdentified) { correctCount++; correctImages.Add(img); // To add correct images } else { if (!currentRoundTestData[i].isKeyPressed || // If the space bar is not pressed currentRoundTestData[i].isKeyPressed && currentRoundTestData[i].isSpaceKey) // If the pressed bar is not space bar { incorrectImages.Add(img); // To add wrong images } } } if (correctCount <= 3) { initialTestImages = currentRoundTestImages; } else { for (int i = 0; i < 3; i++) // To select 3 correct images { if (correctImages.Count <= 0) { break; } int id = UnityEngine.Random.Range(0, correctImages.Count); incorrectImages.Add(correctImages[id]); correctImages.RemoveAt(id); } initialTestImages = incorrectImages; //The list for the second part of the game } OnRoundStart(1); RandSortImages(initialTestImages); // Randomize the list serialNumber = 0; canShowNextImage = true; }
public void UpdateImage(TImage image, byte[] bytesArray) { var mediaService = ApplicationContext.Current.Services.MediaService; var mediaItem = mediaService.GetById(image.Id) as Media; System.IO.File.Delete(HttpContext.Current.Server.MapPath($"~{image.Url}")); System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath($"~{image.Url}"), bytesArray); if (mediaItem != null) { mediaItem.UpdateDate = DateTime.UtcNow; _imageRepository.UpdateItem(mediaService, mediaItem); } }
public TImage Convert(uModels.Media uMedia) { TImage image = new TImage() { Id = uMedia.Id.ToString(), Name = uMedia.Name, AbsoluteUrl = SolutionExtensions.GetAbsoluteUrl(uMedia) }; if (string.IsNullOrEmpty(image.AbsoluteUrl)) { image.AbsoluteUrl = _umbracoDbRepository.GetMediaAbsoluteUrl(uMedia.Id); } return(image); }
public IEnumerator TEST_GetAverageTime_Method() { // Use the Assert class to test conditions. // yield to skip a frame yield return(null); List <ImageHitRound> imagedata = new List <ImageHitRound>(); float temp = TImage.GetAverageTime(imagedata); Assert.IsNotNull(temp, "Incorrect time..."); imagedata.Add(new ImageHitRound()); float temp1 = TImage.GetAverageTime(imagedata); Assert.IsNotNull(temp1, "Incorrect time..."); }
public void UpdateImageAfterSuccessfullRequest(TinyResponse tinyResponse, TImage image) { // download optimized image var tImageBytes = TinyImageService.Instance.DownloadImage(tinyResponse.Output.Url); // update physical file base.UpdateMedia(image, tImageBytes); // update history _historyService.CreateResponseHistory(image.Id, tinyResponse); // update umbraco media attributes _imageRepository.Update(image.Id, tinyResponse.Output.Size); // update statistic var savedBytes = tinyResponse.Input.Size - tinyResponse.Output.Size; _statisticService.UpdateStatistic(); // update tinifying state _stateService.UpdateState(); }
public IEnumerator CheckFindImage() { ImageHit imagehit = imageHitScritps; yield return(new WaitForSeconds(0.5f)); imagehit.gameState = 0; imagehit.serialNumber = 1; imagehit.NextImage(); TImage ti = imagehit.FindImage(imagehit.currentRoundTestImages, imagehit.currentRoundTestData[0]); Assert.True(ti != null, "message :The no CheckFindImage"); TImage t2 = imagehit.FindImage(null, imagehit.currentRoundTestData[0]); Assert.True(ti != null, "message :The no CheckFindImage"); }
public void Create(TImage image, byte[] originImage) { var directoryPath = HostingEnvironment.MapPath(PackageConstants.TinifierTempFolder); Directory.CreateDirectory(directoryPath); var filePath = Path.Combine(directoryPath, image.Name); File.WriteAllBytes(filePath, originImage); var model = new TinifierImagesHistory { ImageId = image.Id, OriginFilePath = filePath }; _imageHistoryRepository.Create(model); }
public void UndoTinify(int mediaId) { byte[] imageBytes; var originImage = _imageHistoryService.Get(mediaId); if (originImage != null) { var mediaFile = _mediaService.GetById(mediaId) as uMedia; if (File.Exists(originImage.OriginFilePath)) { using (var file = new FileStream(originImage.OriginFilePath, FileMode.Open)) imageBytes = SolutionExtensions.ReadFully(file); if (Directory.Exists(Path.GetDirectoryName(originImage.OriginFilePath))) { File.Delete(originImage.OriginFilePath); } var image = new TImage { Id = mediaId.ToString(), Name = mediaFile.Name, AbsoluteUrl = SolutionExtensions.GetAbsoluteUrl(mediaFile) }; // update physical file UpdateMedia(image, imageBytes); // update umbraco media attributes _imageRepository.Update(mediaId, imageBytes.Length); _historyService.Delete(mediaId.ToString()); // update statistic _statisticService.UpdateStatistic(); //delete image history _imageHistoryService.Delete(mediaId); } } else { throw new UndoTinifierException("Image not optimized or Undo tinify not enabled"); } }
private byte[] GetImageBytesFromPath(TImage tImage, IFileSystem fs, string path) { byte[] imageBytes; var fileSystem = _fileSystemProviderRepository.GetFileSystem(); if (fileSystem != null) { if (fileSystem.Type.Contains("PhysicalFileSystem")) { path = fs.GetRelativePath(tImage.AbsoluteUrl); } } using (var file = fs.OpenFile(path)) { imageBytes = SolutionExtensions.ReadFully(file); } return(imageBytes); }
public IEnumerator TEST_GetTotalKeyTime_Method() { // Use the Assert class to test conditions. // yield to skip a frame List <ImageHitRound> imagedata = new List <ImageHitRound>(); yield return(null); float temp = TImage.GetTotalKeyTime(imagedata); Assert.IsTrue(temp == 0, "Incorrect GetTotalKeyTime..."); List <ImageHitRound> imagedata1 = new List <ImageHitRound>(); var testRound = new ImageHitRound(); testRound.keyPressTime = 0.2f; imagedata1.Add(testRound); float temp1 = TImage.GetTotalKeyTime(imagedata1); Assert.IsTrue(temp1 == 0.2f, "Incorrect GetTotalKeyTime..."); }
public IEnumerable <TImage> GetAllImages() { var images = new List <TImage>(); var imagesMedia = _imageRepository.GetAll(); foreach (var item in imagesMedia) { var path = item.GetValue("umbracoFile").ToString(); var image = new TImage { Id = item.Id, Name = item.Name, Url = GetUrl(path) }; images.Add(image); } return(images); }
public IEnumerable <TImage> GetAllOptimizedImages() { var images = new List <TImage>(); var imagesMedia = _imageRepository.GetOptimizedItems().OrderByDescending(x => x.UpdateDate); foreach (var item in imagesMedia) { var path = item.GetValue("umbracoFile").ToString(); var image = new TImage { Id = item.Id, Name = item.Name, Url = GetUrl(path) }; images.Add(image); } return(images); }
public IEnumerator TEST_GetKeyPressCount_Method() { // Use the Assert class to test conditions. // yield to skip a frame yield return(null); List <ImageHitRound> imagedata = new List <ImageHitRound>(); int temp = TImage.GetKeyPressCount(imagedata); Assert.IsTrue(temp == 0, "Incorrect GetKeyPressCount value"); List <ImageHitRound> imagedata1 = new List <ImageHitRound>(); var testRound = new ImageHitRound(); testRound.isKeyPressed = true; imagedata1.Add(testRound); int tem1p = TImage.GetKeyPressCount(imagedata1); Assert.IsTrue(tem1p == 1, "Incorrect GetKeyPressCount value"); }