public override async Task <Result> Execute(CancellationToken token) { var physicalDrivesList = physicalDrives.ToList(); var sourceMediaResult = commandHelper.GetReadableMedia(physicalDrivesList, sourcePath); if (sourceMediaResult.IsFaulted) { return(new Result(sourceMediaResult.Error)); } using var sourceMedia = sourceMediaResult.Value; await using var sourceStream = sourceMedia.Stream; RigidDiskBlock rigidDiskBlock = null; try { var firstBytes = await sourceStream.ReadBytes(512 * 2048); rigidDiskBlock = await commandHelper.GetRigidDiskBlock(new MemoryStream(firstBytes)); } catch (Exception) { // ignored } var sourceSize = sourceMedia.Size; var readSize = size is > 0 ? size.Value : rigidDiskBlock?.DiskSize ?? sourceSize; logger.LogDebug($"Size '{(size is > 0 ? size.Value : "N/A")}'"); logger.LogDebug($"Source size '{sourceSize}'"); logger.LogDebug($"Rigid disk block size '{(rigidDiskBlock == null ? "N/A" : rigidDiskBlock.DiskSize)}'"); logger.LogDebug($"Read size '{readSize}'"); var destinationMediaResult = commandHelper.GetWritableMedia(physicalDrivesList, destinationPath, readSize, false); if (destinationMediaResult.IsFaulted) { return(new Result(destinationMediaResult.Error)); } using var destinationMedia = destinationMediaResult.Value; await using var destinationStream = destinationMedia.Stream; var isVhd = commandHelper.IsVhd(destinationPath); if (!isVhd) { destinationStream.SetLength(readSize); } var imageConverter = new ImageConverter(); imageConverter.DataProcessed += (_, e) => { OnDataProcessed(e.PercentComplete, e.BytesProcessed, e.BytesRemaining, e.BytesTotal, e.TimeElapsed, e.TimeRemaining, e.TimeTotal); }; await imageConverter.Convert(token, sourceStream, destinationStream, readSize, isVhd); return(new Result()); }
public async Task <IActionResult> ResizeImage( [FromQuery] ResizeRequestModel requestModel, [FromServices] IWebHostEnvironment env, [FromServices] StorageService storage, [FromServices] ImageConverter converter ) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } (var fileExists, var blobFile) = await storage.TryGetFile(requestModel.Name); if (!fileExists) { return(NotFound()); } var options = ConversionOptionsFactory.FromResizeRequest(requestModel); var imageSource = await storage.GetBlobBytes(blobFile); var result = await converter.Convert(imageSource, options); if (result.Length == 0) { return(BadRequest("Could not convert file.")); } return(File(result, options.TargetMimeType)); }
public async Task <IActionResult> ResizeImage( [FromQuery] ResizeRequestModel requestModel, [FromServices] IHostingEnvironment env, [FromServices] StorageService storage, [FromServices] ImageConverter converter ) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var options = ConversionOptionsFactory.FromResizeRequest(requestModel); (var cacheExists, var cacheFile) = await storage.TryGetFileCached(options.GetCacheKey()); if (cacheExists) { // validar Etag if (IsEtagNotModified(Request, cacheFile.Properties.ETag)) { return(new NotModifiedResult( cacheFile.Properties.LastModified.GetValueOrDefault().UtcDateTime, cacheFile.Properties.ETag)); } var cacheContent = await storage.GetBlobBytes(cacheFile); return(File(cacheContent, cacheFile.Properties.ContentType, cacheFile.Properties.LastModified.GetValueOrDefault().UtcDateTime, new EntityTagHeaderValue(cacheFile.Properties.ETag))); } (var fileExists, var blobFile) = await storage.TryGetFile(requestModel.Name); if (fileExists == false) { return(NotFound()); } var imageSource = await storage.GetBlobBytes(blobFile); var result = await converter.Convert(imageSource, options); if (result.Length == 0) { return(BadRequest("Could not convert file.")); } // Salvar a imagem convertida em um blob separado (var uploadOk, var savedFile) = await storage.TryUploadToCache(options.GetCacheKey(), result, options.TargetMimeType); return(File(result, savedFile.Properties.ContentType, savedFile.Properties.LastModified.GetValueOrDefault().UtcDateTime, new EntityTagHeaderValue(savedFile.Properties.ETag))); }
private void ConvertImages(Task task) { if (converterThread != null) { if (TaskExists(convertingTask)) { converterThread.Join(); //will freeze UI but oh well } else { converterThread.Abort(); } } Bitmap image = task.originalImage; ImageConverter noDither = new ImageConverter(image, Helper.Palette[7], false); ImageConverter dither = new ImageConverter(image, Helper.Palette[7], true); convertingTask = task.internalId; converterThread = new Thread(() => { noDither.Convert(); dither.Convert(); Dispatcher.InvokeAsync(() => { if (!TaskExists(task.internalId)) { return; } task.convertedImage = noDither.Convert(); task.ditheredImage = dither.Convert(); task.imagesConverted = true; DataExchange.UpdateTasksFromGUI(); ShowPreview(); }); }); converterThread.Name = "TaskPanel conversion"; converterThread.IsBackground = true; converterThread.Start(); }
public void TestConvert_FromEntityToModel_FormatIsCorrect() { // Prepare var entity = GenerateImageEntity(); var expected = "Test Format"; // Act var actual = ImageConverter.Convert(entity).Format; // Assert Assert.AreEqual(expected, actual); } // TEST METHOD ENDS
public void TestConvert_FromModelToEntity_FormatIsCorrect() { // Prepare var model = GenerateImageModel(); var expected = "Test Format"; // Act var actual = ImageConverter.Convert(model).Format; // Assert Assert.AreEqual(expected, actual); } // TEST METHOD ENDS
public void TestConvert_FromModelToEntity_IdIsCorrect() { // Prepare var model = GenerateImageModel(); var expected = Guid.Parse("d0257b18-cb43-4065-92d2-42539c12bd84"); // Act var actual = ImageConverter.Convert(model).Id; // Assert Assert.AreEqual(expected, actual); } // TEST METHOD ENDS
public void TestConvert_FromEntityToModel_ArticleIdIsCorrect() { // Prepare var entity = GenerateImageEntity(); var expected = Guid.Parse("e21b164a-c705-4a80-9fce-f878be267c54"); // Act var actual = ImageConverter.Convert(entity).ArticleId; // Assert Assert.AreEqual(expected, actual); } // TEST METHOD ENDS
public string[] Convert(Image <Rgba32> image, float percentage, string ramp) { if (ramp == null) { throw new ArgumentNullException(nameof(ramp)); } var bytes = _imageConverter.Convert(image, (int)(image.Width * percentage), (int)(image.Height * percentage)); var text = _bytesConverter.Convert(bytes, ramp); return(text); }
public void ConvertTest() { ImageConverter target = new ImageConverter(); // TODO: Initialize to an appropriate value object value = null; // TODO: Initialize to an appropriate value Type targetType = null; // TODO: Initialize to an appropriate value object parameter = null; // TODO: Initialize to an appropriate value CultureInfo culture = null; // TODO: Initialize to an appropriate value object expected = null; // TODO: Initialize to an appropriate value object actual; actual = target.Convert(value, targetType, parameter, culture); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item == null) { return(base.SelectTemplate(item, container)); } DataTemplate template = null; if ((item is byte[]) || (item is System.Drawing.Image)) { bool useImageTemplate = false; try { var converter = new ImageConverter(); useImageTemplate = (converter.Convert(item, typeof(ImageSource), null, CultureInfo.CurrentCulture) != null); } catch (NotSupportedException) { //suppress the exception, the byte[] is not an image. convertedValue will remain null } if (useImageTemplate) { template = GenericContentTemplateSelector.GetImageTemplate(container); } } else if (item is ImageSource) { template = GenericContentTemplateSelector.GetImageTemplate(container); } else if (item is bool) { template = GenericContentTemplateSelector.BoolTemplate; } if (template == null) { template = GenericContentTemplateSelector.GetCommonTemplate(item, container); } if (template != null) { return(template); } return(base.SelectTemplate(item, container)); }
/// <summary> /// L /// </summary> /// <param name="model"></param> /// <returns></returns> Business.Models.Image IModelService <Business.Models.Image, Guid> .Create(Business.Models.Image model) { try { // Le generamos un id único al nuevo comentario model.Id = Guid.NewGuid(); // Insertamos datos en la base de datos this.database.Image.InsertOnSubmit(ImageConverter.Convert(model)); // Guardamos los cambios this.database.SubmitChanges(); return(model); } // TRY ENDS catch (Exception e) { Console.Out.WriteLine(e.Message); } // CATCH ENDS return(null); } // CREATE ENDS ------------------------------------------------------ //
private async Task LoadClientProfilePicture() { var client = await _clientService.GetById <ClientModel>(APIService.LoggedUserId); if (client != null) { if (client.ProfilePicture.Length != 0) { ImageConverter converter = new ImageConverter(); UserImage.Source = (ImageSource)converter.Convert(client.ProfilePicture, null, null, null); UserImage.WidthRequest = 400; } else { UserImage.Source = ImageSource.FromResource("openRoads.Mobile.Resources.userAvatar.png"); UserImage.WidthRequest = 400; } } }
} // DELETE ENDS ------------------------------------------------------ // /// <summary> /// /// </summary> /// <param name="modelId"></param> /// <returns></returns> Business.Models.Image IModelService <Business.Models.Image, Guid> .Get(Guid modelId) { try { // Usamos una consulta LINQ para buscar la imagen en la base de datos var query = from image in this.database.Image where image.Id == modelId select image; // Si hay resultados, entonces buscamos el primero y lo devolvemos foreach (var result in query) { return(ImageConverter.Convert(result)); } // FOREACH ENDS } // TRY ENDS catch (Exception e) { Console.WriteLine(e.Message); } // CATCH ENDS return(null); } // GET ENDS --------------------------------------------------------- //
} // GET ENDS --------------------------------------------------------- // /// <summary> /// /// </summary> /// <returns></returns> IEnumerable <Business.Models.Image> IModelService <Business.Models.Image, Guid> .Get() { // La lista de imagenes List <Business.Models.Image> results = new List <Business.Models.Image>(); try { // Usamos una consulta LINQ para buscar la imagen en la base de datos var query = from Image in this.database.Image select Image; // Si hay resultados, entonces buscamos el primero y lo devolvemos foreach (var result in query) { results.Add(ImageConverter.Convert(result)); } // FOREACH ENDS } // TRY ENDS catch (Exception e) { Console.WriteLine(e.Message); } // CATCH ENDS return(results); } // GET ENDS --------------------------------------------------------- //
//Load user image to small ButtonImage in navigation bar public static async Task LoadUserImage(APIService _service, ImageButton userImg) { //Get the logged user ClientModel user = await _service.GetById <ClientModel>(APIService.LoggedUserId); if (user != null) { //Check if user has a profile pic uploaded, if so set it to userImg btnImage if (user.ProfilePicture.Length != 0) { ImageConverter converter = new ImageConverter(); userImg.Source = (ImageSource)converter.Convert(user.ProfilePicture, null, null, null); userImg.HeightRequest = 45; userImg.CornerRadius = 25; } else { //If profile pic isn't uploaded set the image to static resource image for nonexistent images userImg.Source = ImageSource.FromResource("OpenRoads.Mobile.Resources.userAvatar.png"); userImg.HeightRequest = 45; userImg.CornerRadius = 25; } } }
public ImageBO Create(ImageBO image) { Image _image = imageConverter.Convert(image); _context.Images.Add(_image); _context.SaveChanges(); return(imageConverter.Convert(_image)); }
// Convert a multipage TIFF image to a PDF document. // This code uses the DynamicPDF Converter for .NET product. // It used the following namespace from the ceTe.DynamicPDF.Converter.NET NuGet package: // * ceTe.DynamicPDF.Conversion for the ImageConverter class static void ConvertExampleTwo() { ImageConverter imageConverter = new ImageConverter("../../../Resources/fw9_18.tif"); imageConverter.Convert("converter-output.pdf"); }
public override DataTemplate SelectTemplate( object item, DependencyObject container ) { if( item == null ) return base.SelectTemplate( item, container ); DataTemplate template = null; if( ( item is byte[] ) || ( item is System.Drawing.Image ) ) { bool useImageTemplate = false; try { var converter = new ImageConverter(); useImageTemplate = ( converter.Convert( item, typeof( ImageSource ), null, CultureInfo.CurrentCulture ) != null ); } catch( NotSupportedException ) { //suppress the exception, the byte[] is not an image. convertedValue will remain null } if( useImageTemplate ) { template = GenericContentTemplateSelector.GetImageTemplate( container ); } } else if( item is ImageSource ) { template = GenericContentTemplateSelector.GetImageTemplate( container ); } else if( item is bool ) { template = GenericContentTemplateSelector.BoolTemplate; } if( template == null ) { template = GenericContentTemplateSelector.GetCommonTemplate( item, container ); } if( template != null ) return template; return base.SelectTemplate( item, container ); }
private bool Update(bool RetrieveAgain) { if (isUpdatding) { return(false); } try { isUpdatding = true; var current = (App.Current as App).currentInfo; var currArray = (App.Current as App).currentInfoArray; if (currArray == null) { currArray = Enumerable.Empty <CreditInfo>().ToList(); } if (current == null) { SafeDispatcher.Run(() => { MessageBox.Show(AppResources.Whoops); NavigationService.Navigate(new Uri("/NotWorking.xaml", UriKind.Relative)); }); return(true); } int i = 0; int tot = currArray.Count + 1; foreach (var item in currArray.Concat(Enumerable.Repeat(current, 1))) { if (item == null || string.IsNullOrEmpty(item.Password) || string.IsNullOrEmpty(item.Username) || !NetworkInterface.GetIsNetworkAvailable()) { //Nothing to do here. continue; } if (RetrieveAgain) { SafeDispatcher.Run(() => { var pr = SystemTray.GetProgressIndicator(this); pr.Text = string.Format(AppResources.UpdateSingleNumber, item.Username); pr.IsIndeterminate = false; pr.Value = (((double)i++) / (double)tot); }); var tsk1 = CreditInfoRetriever.Get().RetrieveCreditInfo(item.Username, item.Password, item.Type, Guid.Empty); tsk1.Wait(); var nw = tsk1.Result; if (nw == null) { return(true); } SafeDispatcher.Run(() => item.Merge(nw)); var Img = new ImageConverter(); foreach (var itm in item.NumberInfos) { Utils.RenderTiles(itm.Number, itm); var smallpath = System.IO.Path.Combine(WPUtils.baseDir, string.Format("{0}_{1}_{2}.jpg", 159, 159, itm.Number)); var normalpath = System.IO.Path.Combine(WPUtils.baseDir, string.Format("{0}_{1}_{2}.jpg", 336, 336, itm.Number)); //var widepath = System.IO.Path.Combine(WPUtils.baseDir, string.Format("{0}_{1}_{2}.jpg", 691, 336, item.Number)); SafeDispatcher.Run(() => { foreach (var str in new[] { new[] { "336", "336" }, new[] { "159", "159" } /*, new[] { "691", "336" }*/ }) { var hubtile = FindControl <HubTile>(this.pivotNumbers.ItemContainerGenerator.ContainerFromIndex(pivotNumbers.SelectedIndex), str[0]); if (hubtile != null) { hubtile.Source = Img.Convert(new[] { str[0], str[1], (pivotNumbers.SelectedItem as NumberInfo).Number }, null, null, null) as BitmapImage; hubtile.Source = Img.Convert(new[] { str[0], str[1], (pivotNumbers.SelectedItem as NumberInfo).Number }, null, null, null) as BitmapImage; } } }); if (ShellTile.ActiveTiles.Any(t => t.NavigationUri.ToString().Contains(itm.Number))) { FlipTileData tileData = new FlipTileData { Title = " ", //WideBackgroundImage = new Uri("isostore:" + widepath, UriKind.Absolute), BackgroundImage = new Uri("isostore:" + normalpath, UriKind.Absolute), SmallBackgroundImage = new Uri("isostore:" + smallpath, UriKind.Absolute), BackBackgroundImage = new Uri("isostore:" + normalpath, UriKind.Absolute), //WideBackBackgroundImage = new Uri("isostore:" + widepath, UriKind.Absolute), }; ShellTile.ActiveTiles.Single(t => t.NavigationUri.ToString().Contains(itm.Number)).Update(tileData); } } } } Utils.SaveCreditState(current); Utils.SaveCreditState(currArray); return(true); } catch (Exception e) { SafeDispatcher.Run(() => MessageBox.Show(e.Message)); } finally { isUpdatding = false; } return(true); }
private async void ApplicationBarIconButton_Click(object sender, EventArgs e) { if ((sender as CimbalinoBeh.ApplicationBarIconButton).Text.ToLower() == "about") { NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative)); } else if ((sender as CimbalinoBeh.ApplicationBarIconButton).Text.ToLower() == "refresh") { (sender as CimbalinoBeh.ApplicationBarIconButton).IsEnabled = false; ShakeDetected(null, new ShakeDetectedEventArgs(true)); (sender as CimbalinoBeh.ApplicationBarIconButton).IsEnabled = true; } else if ((sender as CimbalinoBeh.ApplicationBarIconButton).Text.ToLower() == "save") { Task task = null; if (CurrentApp.LicenseInformation.ProductLicenses.ContainsKey(IAPs.IAP_PushNotification)) { task = WPUtils.UploadCurrentData(); } var c = (App.Current as App).currentInfo; var c2 = (App.Current as App).currentInfoArray; Utils.SaveCreditState(c); Utils.SaveCreditState(c2); foreach (var model in pivotNumbers.ItemsSource.Cast <NumberInfo>()) { Utils.RenderTiles(model.Number, model); var tile = ShellTile.ActiveTiles.Where(t => t.NavigationUri.OriginalString.Contains(model.Number)); var smallpath = System.IO.Path.Combine(WPUtils.baseDir, string.Format("{0}_{1}_{2}.jpg", 159, 159, model.Number)); var normalpath = System.IO.Path.Combine(WPUtils.baseDir, string.Format("{0}_{1}_{2}.jpg", 336, 336, model.Number)); //var widepath = System.IO.Path.Combine(WPUtils.baseDir, string.Format("{0}_{1}_{2}.jpg", 691, 336, model.Number)); foreach (var item in tile) { item.Update(new FlipTileData { Title = " ", //WideBackgroundImage = new Uri("isostore:" + widepath, UriKind.Absolute), BackgroundImage = new Uri("isostore:" + normalpath, UriKind.Absolute), SmallBackgroundImage = new Uri("isostore:" + smallpath, UriKind.Absolute), BackBackgroundImage = new Uri("isostore:" + normalpath, UriKind.Absolute), //WideBackBackgroundImage = new Uri("isostore:" + widepath, UriKind.Absolute), }); } } var Img = new ImageConverter(); SafeDispatcher.Run(() => { foreach (var str in new[] { "336", "159" }) { for (int i = 0; i < pivotNumbers.Items.Count; i++) { var hubtile = FindControl <HubTile>(this.pivotNumbers.ItemContainerGenerator.ContainerFromIndex(i), str); if (hubtile != null) { hubtile.Source = Img.Convert(new[] { str, str, (pivotNumbers.Items[i] as NumberInfo).Number }, null, null, null) as BitmapImage; hubtile.Source = Img.Convert(new[] { str, str, (pivotNumbers.Items[i] as NumberInfo).Number }, null, null, null) as BitmapImage; } } } (new ToastPrompt { Message = AppResources.Saved, IsTimerEnabled = true, UseLayoutRounding = true, MillisecondsUntilHidden = 2500 }).Show(); }); if (task != null) { await task; } } }
public async Task ImagesProcessing() { var collection = _collectionProvider.GetCollection <Branch>(); var filter = new FilterDefinitionBuilder <Branch>().Where(b => b.IsDeleted == false); var imageConverter = new ImageConverter(); var sortDefinition = new SortDefinitionBuilder <Branch>().Ascending(b => b.Modified); var counter = 0; using (var cursor = await collection.FindAsync(filter, new FindOptions <Branch>() { Sort = sortDefinition })) { using (var logWriter = System.IO.File.AppendText($"imageProcessing-{DateTime.UtcNow.ToFileTimeUtc()}.txt")) { try { logWriter.WriteLine($"Image processing started at {DateTime.UtcNow}:"); while (await cursor.MoveNextAsync()) { var branches = cursor.Current; foreach (Branch branch in branches) { UpdateDefinition <Branch> updateBranch = null; string processedIcon = null; string processedImage = null; if (branch.Id != branch.PartnerId) { // branch if (!string.IsNullOrEmpty(branch.Image) || !string.IsNullOrEmpty(branch.Icon)) { updateBranch = Builders <Branch> . Update. Set(x => x.Icon, null). Set(x => x.Image, null); counter++; } } else if (branch.Id == branch.PartnerId) { // partner processedIcon = branch.Icon == null ? null : Convert.ToBase64String(imageConverter.Convert(Convert.FromBase64String(branch.Icon), ImageOptions.Icon)); processedImage = branch.Image == null ? null : Convert.ToBase64String(imageConverter.Convert(Convert.FromBase64String(branch.Image), ImageOptions.Image)); if (branch.Icon?.Length != processedIcon?.Length || branch.Image?.Length != processedImage?.Length) { updateBranch = Builders <Branch> . Update. Set(x => x.Modified, DateTime.UtcNow). Set(x => x.Icon, processedIcon). Set(x => x.Image, processedImage); counter++; } } if (updateBranch != null) { var filterBranch = new FilterDefinitionBuilder <Branch>().Where(b => b.Id == branch.Id); var resultOfProcessing = await collection.UpdateOneAsync(filterBranch, updateBranch); Assert.IsTrue(resultOfProcessing.ModifiedCount == 1); logWriter.WriteLine($"____________________________________________{counter}______________________________________________"); logWriter.WriteLine($"Image processing for BranchId = {branch.Id} with partnerId = {branch.PartnerId}"); logWriter.WriteLine($"Icon and (or) Image were processed for branch with Id = {branch.Id}"); logWriter.WriteLine($"Icon original size: {branch.Icon?.Length}, after processing: {processedIcon?.Length}"); logWriter.WriteLine($"Image original size: {branch.Image?.Length}, after processing: {processedImage?.Length}"); logWriter.WriteLine("____________________________________________________________________________________________________"); } } } logWriter.WriteLine($"Image processing finished at {DateTime.UtcNow}"); } catch (Exception ex) { logWriter.WriteLine(ex); logWriter.Dispose(); } } } }
public override DataTemplate SelectTemplate( object item, DependencyObject container ) { DataTemplate template = null; bool useImageTemplate = false; if( ( item is byte[] ) || ( item is System.Drawing.Image ) ) { ImageConverter converter = new ImageConverter(); object convertedValue = null; try { convertedValue = converter.Convert( item, typeof( ImageSource ), null, System.Globalization.CultureInfo.CurrentCulture ); } catch( NotSupportedException ) { //suppress the exception, the byte[] is not an image. convertedValue will remain null } if( convertedValue != null ) useImageTemplate = true; } else if( item is ImageSource ) { useImageTemplate = true; } else if( item is bool ) { template = GenericContentTemplateSelector.BoolTemplate; } if( useImageTemplate ) { template = GenericContentTemplateSelector.ImageTemplate; DataGridContext dataGridContext = DataGridControl.GetDataGridContext( container ); DataGridControl parentGrid = ( dataGridContext != null ) ? dataGridContext.DataGridControl : null; } if( template == null ) template = base.SelectTemplate( item, container ); return template; }