public async Task<ImageSource> GetImageAsync(string url, ImageOptions options = null, bool canCache = false) { ImageSource retVal; if (canCache && _cachedImages.TryGetValue(url, out retVal)) return retVal; return await Task.Run(() => { try { var request = (HttpWebRequest) WebRequest.Create(url); using (var response = (HttpWebResponse) request.GetResponse()) { using (var stream = response.GetResponseStream()) { if (stream != null) return ProcessImageStream(options, stream, url); } } } catch (Exception ex) { Debug.WriteLine("Failed to get image: " + ex.Message); } return null; }); }
public async Task<ImageSource> GetImageAsync(string url, ImageOptions options = null, bool canCache = false) { ImageSource retVal; if (canCache && _cachedImages.TryGetValue(url, out retVal)) return retVal; return await Task.Run(() => { try { var image = UIImage.LoadFromData(NSData.FromUrl(new NSUrl(url))); if (image == null) return null; retVal = ProcessImage(options, image); if (canCache) _cachedImages[url] = retVal; return retVal; } catch { return null; } }); }
public async Task<ImageSource> GetImageAsync(string baseUrl, string resource = "/", string username = null, string password = null, int timeout = 10000, Dictionary<string, string> headers = null, ImageOptions options = null, bool canCache = false) { ImageSource retVal; var uriBuilder = new UriBuilder(baseUrl) { Fragment = resource }; var key = uriBuilder.Uri.ToString(); if (canCache && _cachedImages.TryGetValue(key, out retVal)) return retVal; var bytes = await _restConnection.MakeRawGetRequestAsync(baseUrl, resource, username, password, timeout, headers); if (bytes == null) return null; var image = GetUIImageFromBase64(Convert.ToBase64String(bytes)); if (image == null) return null; retVal = ProcessImage(options, image); if (canCache) _cachedImages[key] = retVal; return retVal; }
public static void InImageRepresentation() { // Setup GroupDocs.Viewer config ViewerConfig config = new ViewerConfig(); config.StoragePath = @"C:\storage"; // Create image handler ViewerImageHandler imageHandler = new ViewerImageHandler(config); string guid = "document.xlsx"; // Set image options to show grid lines ImageOptions options = new ImageOptions(); options.CellsOptions.ShowHiddenSheets = true; DocumentInfoContainer container = imageHandler.GetDocumentInfo(new DocumentInfoOptions(guid)); foreach (PageData page in container.Pages) Console.WriteLine("Page number: {0}, Page Name: {1}, IsVisible: {2}", page.Number, page.Name, page.IsVisible); List<PageImage> pages = imageHandler.GetPages(guid, options); foreach (PageImage page in pages) { Console.WriteLine("Page number: {0}", page.PageNumber); // Page image stream Stream imageContent = page.Stream; } }
public static void Add_Watermark_For_Image() { Console.WriteLine("***** {0} *****", "Add Watermark to Image page representation"); /* ********************* SAMPLE ********************* */ // Setup GroupDocs.Viewer config ViewerConfig config = new ViewerConfig(); config.StoragePath = @"C:\storage"; // Create image handler ViewerImageHandler imageHandler = new ViewerImageHandler(config); string guid = "word.doc"; ImageOptions options = new ImageOptions(); // Set watermark properties Watermark watermark = new Watermark("This is watermark text"); watermark.Color = System.Drawing.Color.Blue; watermark.Position = WatermarkPosition.Diagonal; watermark.Width = 100; options.Watermark = watermark; // Get document pages image representation with watermark List<PageImage> pages = imageHandler.GetPages(guid, options); }
public async Task<ImageSource> GetImageAsync(PhotoSource source, ImageOptions options = null) { switch (source) { case PhotoSource.Camera: return await GetImageFromCameraAsync(options); default: return await GetImageFromExistingAsync(options); } }
/// <summary> /// Rotate page in Image mode /// </summary> public static void Reorder_Pages_In_Image_Mode() { Console.WriteLine("***** {0} *****", "Reorder pages in Image mode"); /* ********************* SAMPLE ********************* */ /* ******************** Reorder 1st and 2nd pages *********************** */ // Setup GroupDocs.Viewer config ViewerConfig config = new ViewerConfig(); config.StoragePath = @"C:\storage"; // Create image handler ViewerImageHandler imageHandler = new ViewerImageHandler(config); string guid = "word.doc"; int pageNumber = 1; int newPosition = 2; // Perform page reorder ReorderPageOptions options = new ReorderPageOptions(guid, pageNumber, newPosition); imageHandler.ReorderPage(options); /* ******************** Retrieve all document pages including transformation *********************** */ // Set image options to include reorder transformations ImageOptions imageOptions = new ImageOptions { Transformations = Transformation.Reorder }; // Get image representation of all document pages, including reorder transformations List<PageImage> pages = imageHandler.GetPages(guid, imageOptions); /* ******************** Retrieve all document pages excluding transformation *********************** */ // Set image options NOT to include ANY transformations ImageOptions noTransformationsOptions = new ImageOptions { Transformations = Transformation.None // This is by default }; // Get image representation of all document pages, without transformations List<PageImage> pagesWithoutTransformations = imageHandler.GetPages(guid, noTransformationsOptions); // Get image representation of all document pages, without transformations List<PageImage> pagesWithoutTransformations2 = imageHandler.GetPages(guid); }
public static void Run() { //Initialize viewer config ViewerConfig viewerConfig = new ViewerConfig(); viewerConfig.StoragePath = "c:\\storage"; //Initialize viewer handler ViewerImageHandler viewerImageHandler = new ViewerImageHandler(viewerConfig); //Set encoding Encoding encoding = Encoding.GetEncoding("shift-jis"); //Set image options ImageOptions imageOptions = new ImageOptions(); imageOptions.WordsOptions.Encoding = encoding; imageOptions.CellsOptions.Encoding = encoding; imageOptions.EmailOptions.Encoding = encoding; //Get words document pages with encoding string wordsDocumentGuid = "document.txt"; List<PageImage> wordsDocumentPages = viewerImageHandler.GetPages(wordsDocumentGuid, imageOptions); //Get cells document pages with encoding string cellsDocumentGuid = "document.csv"; List<PageImage> cellsDocumentPages = viewerImageHandler.GetPages(cellsDocumentGuid, imageOptions); //Get email document pages with encoding string emailDocumentGuid = "document.msg"; List<PageImage> emailDocumentPages = viewerImageHandler.GetPages(emailDocumentGuid, imageOptions); //Get words document info with encoding DocumentInfoOptions wordsDocumentInfoOptions = new DocumentInfoOptions(wordsDocumentGuid); wordsDocumentInfoOptions.WordsDocumentInfoOptions.Encoding = encoding; DocumentInfoContainer wordsDocumentInfoContainer = viewerImageHandler.GetDocumentInfo(wordsDocumentInfoOptions); //Get cells document info with encoding DocumentInfoOptions cellsDocumentInfoOptions = new DocumentInfoOptions(cellsDocumentGuid); cellsDocumentInfoOptions.CellsDocumentInfoOptions.Encoding = encoding; DocumentInfoContainer cellsDocumentInfoContainer = viewerImageHandler.GetDocumentInfo(cellsDocumentInfoOptions); //Get email document info with encoding DocumentInfoOptions emailDocumentInfoOptions = new DocumentInfoOptions(emailDocumentGuid); emailDocumentInfoOptions.EmailDocumentInfoOptions.Encoding = encoding; DocumentInfoContainer emailDocumentInfoContainer = viewerImageHandler.GetDocumentInfo(emailDocumentInfoOptions); }
public async Task<ImageSource> GetImageAsync(string baseUrl, string resource = "/", string username = null, string password = null, int timeout = 10000, Dictionary<string, string> headers = null, ImageOptions options = null, bool canCache = false) { ImageSource retVal; var uriBuilder = new UriBuilder(baseUrl) {Fragment = resource}; var url = uriBuilder.Uri.ToString(); if (canCache && _cachedImages.TryGetValue(url, out retVal)) return retVal; var bytes = await _restConnection.MakeRawGetRequestAsync(baseUrl, resource, username, password, timeout, headers); if (bytes == null) return null; using (var ms = new MemoryStream(bytes)) return ProcessImageStream(options, ms, url); }
/// <summary> /// Perform multiple transformations in Image mode /// </summary> public static void Multiple_Transformations_For_Image() { Console.WriteLine("***** {0} *****", "Perform multiple transformations in Image mode"); /* ********************* SAMPLE ********************* */ // Setup GroupDocs.Viewer config ViewerConfig config = new ViewerConfig(); config.StoragePath = @"C:\storage"; // Create image handler ViewerImageHandler imageHandler = new ViewerImageHandler(config); string guid = "word.doc"; // Rotate first page 90 degrees imageHandler.RotatePage(new RotatePageOptions(guid, 1, 90)); // Rotate second page 180 degrees imageHandler.RotatePage(new RotatePageOptions(guid, 2, 180)); // Reorder first and second pages imageHandler.ReorderPage(new ReorderPageOptions(guid, 1, 2)); // Set options to include rotate and reorder transformations ImageOptions options = new ImageOptions { Transformations = Transformation.Rotate | Transformation.Reorder }; // Set watermark properties Watermark watermark = new Watermark("This is watermark text") { Color = System.Drawing.Color.Blue, Position = WatermarkPosition.Diagonal, Width = 100 }; options.Watermark = watermark; // Get document pages image representation with multiple transformations List<PageImage> pages = imageHandler.GetPages(guid, options); }
public static void InImageRepresentation() { // Setup GroupDocs.Viewer config ViewerConfig config = new ViewerConfig(); config.StoragePath = @"C:\storage"; // Create image handler ViewerImageHandler imageHandler = new ViewerImageHandler(config); string guid = "document.xlsx"; // Set image options to show grid lines ImageOptions options = new ImageOptions(); options.CellsOptions.ShowGridLines = true; List<PageImage> pages = imageHandler.GetPages(guid, options); foreach (PageImage page in pages) { Console.WriteLine("Page number: {0}", page.PageNumber); // Page image stream Stream imageContent = page.Stream; } }
public BitmapSource GetImage(ImageReference imageReference, ImageOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (imageReference.Name == null) { return(null); } var internalOptions = new InternalImageOptions(); internalOptions.BackgroundColor = options.BackgroundColor ?? GetColor(options.BackgroundBrush); var logicalSize = options.LogicalSize; if (logicalSize == new Size(0, 0)) { logicalSize = new Size(16, 16); } internalOptions.Dpi = GetDpi(options.DpiObject, options.Dpi); if (options.Zoom != new Size(0, 0)) { internalOptions.Dpi = new Size(internalOptions.Dpi.Width * options.Zoom.Width, internalOptions.Dpi.Height * options.Zoom.Height); } internalOptions.Dpi = Round(internalOptions.Dpi); if (internalOptions.Dpi.Width == 0 || internalOptions.Dpi.Height == 0) { return(null); } internalOptions.PhysicalSize = Round(new Size(logicalSize.Width * internalOptions.Dpi.Width / 96, logicalSize.Height * internalOptions.Dpi.Height / 96)); if (internalOptions.PhysicalSize.Width == 0 || internalOptions.PhysicalSize.Height == 0) { return(null); } if (imageReference.Assembly != null) { var name = imageReference.Name; foreach (var provider in GetProviders(imageReference.Assembly)) { var infos = provider.Value.GetImageSourceInfos(name); if (infos == null) { continue; } var infoList = new List <ImageSourceInfo>(infos); infoList.Sort((a, b) => { if (a.Size == b.Size) { return(0); } // Try exact size first if ((a.Size == internalOptions.PhysicalSize) != (b.Size == internalOptions.PhysicalSize)) { return(a.Size == internalOptions.PhysicalSize ? -1 : 1); } // Try any-size (xaml images) if ((a.Size == ImageSourceInfo.AnySize) != (b.Size == ImageSourceInfo.AnySize)) { return(a.Size == ImageSourceInfo.AnySize ? -1 : 1); } // Closest size (using height) if (a.Size.Height >= internalOptions.PhysicalSize.Height) { if (b.Size.Height < internalOptions.PhysicalSize.Height) { return(-1); } return(a.Size.Height.CompareTo(b.Size.Height)); } else { if (b.Size.Height >= internalOptions.PhysicalSize.Height) { return(1); } return(b.Size.Height.CompareTo(a.Size.Height)); } }); foreach (var info in infoList) { var bitmapSource = TryGetImage(info.Uri, internalOptions); if (bitmapSource != null) { return(bitmapSource); } } return(null); } return(null); } else { return(TryGetImage(imageReference.Name, internalOptions)); } }
public ActionResult GetDocumentPageImage(GetDocumentPageImageParameters parameters) { try { //parameters.IgnoreDocumentAbsence - not supported //parameters.InstanceIdToken - not supported string guid = parameters.Path; int pageIndex = parameters.PageIndex; int pageNumber = pageIndex + 1; /* * //NOTE: This feature is supported starting from version 3.2.0 * CultureInfo cultureInfo = string.IsNullOrEmpty(parameters.Locale) * ? new CultureInfo("en-Us") * : new CultureInfo(parameters.Locale); * * ViewerImageHandler viewerImageHandler = new ViewerImageHandler(viewerConfig, cultureInfo); */ var imageOptions = new ImageOptions { ConvertImageFileType = _convertImageFileType, Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor, parameters.WatermarkPosition, parameters.WatermarkWidth, parameters.WatermarkOpacity), Transformations = parameters.Rotate ? Transformation.Rotate : Transformation.None, CountPagesToRender = 1, PageNumber = pageNumber, JpegQuality = parameters.Quality.GetValueOrDefault(), PageNumbersToRender = new List <int>(new int[] { pageNumber }) }; if (parameters.Rotate && parameters.Width.HasValue) { DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid); int side = parameters.Width.Value; int pageAngle = documentInfoContainer.Pages[pageIndex].Angle; if (pageAngle == 90 || pageAngle == 270) { imageOptions.Height = side; } else { imageOptions.Width = side; } } /* * //NOTE: This feature is supported starting from version 3.2.0 * if (parameters.Quality.HasValue) * imageOptions.JpegQuality = parameters.Quality.Value; */ using (new InterProcessLock(guid)) { List <PageImage> pageImages = _imageHandler.GetPages(guid, imageOptions); PageImage pageImage = pageImages.Single(_ => _.PageNumber == pageNumber); return(File(pageImage.Stream, GetContentType(_convertImageFileType))); } } catch (Exception e) { return(this.JsonOrJsonP(new FailedResponse { Reason = e.Message }, null)); } }
public ActionResult GetDocumentPageImage(GetDocumentPageImageParameters parameters) { var guid = parameters.Path; var pageIndex = parameters.PageIndex; var pageNumber = pageIndex + 1; var imageOptions = new ImageOptions { ConvertImageFileType = _convertImageFileType, Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor, parameters.WatermarkPosition, parameters.WatermarkWidth), Transformations = parameters.Rotate ? Transformation.Rotate : Transformation.None, CountPagesToConvert = 1, PageNumber = pageNumber, JpegQuality = parameters.Quality.GetValueOrDefault() }; imageOptions.CellsOptions.OnePagePerSheet = false; if (parameters.Rotate && parameters.Width.HasValue) { DocumentInfoContainer documentInfoContainer = _imageHandler.GetDocumentInfo(guid); int pageAngle = documentInfoContainer.Pages[pageIndex].Angle; var isHorizontalView = pageAngle == 90 || pageAngle == 270; int sideLength = parameters.Width.Value; if (isHorizontalView) imageOptions.Height = sideLength; else imageOptions.Width = sideLength; } else if (parameters.Width.HasValue) { imageOptions.Width = parameters.Width.Value; } var pageImage = _imageHandler.GetPages(guid, imageOptions).Single(); return File(pageImage.Stream, Utils.GetMimeType(_convertImageFileType)); }
/// <summary> /// Gets the bitmap image async. /// </summary> /// <param name="options">The options.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task{BitmapImage}.</returns> public Task <BitmapImage> GetBitmapImageAsync(ImageOptions options, CancellationToken cancellationToken) { var url = _apiClient.GetImageUrl(Item, options); return(_imageManager.GetRemoteBitmapAsync(url, cancellationToken)); }
public string GetImageUrl(BaseItem item, ImageOptions options) { return(item is MusicGenre?Kernel.ApiClient.GetMusicGenreImageUrl(item.Name, options) : item is Genre?Kernel.ApiClient.GetGenreImageUrl(item.Name, options) : Kernel.ApiClient.GetImageUrl(item.ApiId, options)); }
private static async Task<ImageSource> GetImageFromExistingAsync(ImageOptions options = null) { var mediaPicker = new MediaPicker(); if (mediaPicker.PhotosSupported) { try { var style = UIApplication.SharedApplication.StatusBarStyle; var file = await mediaPicker.PickPhotoAsync(); UIApplication.SharedApplication.StatusBarStyle = style; return ProcessImageFile(options, file); } catch (Exception) { return null; } } return null; }
private string ProcessPage(Document doc, string destDir, string fileGUID, int pageCount, int imgQuality, Boolean combineImages) { string imgPaths = destDir + fileGUID;//Guid.NewGuid().ToString(); if (!Directory.Exists(imgPaths)) { Directory.CreateDirectory(imgPaths); } if (imgQuality == 0) { imgQuality = 100; } var result = ""; ImageOptions imageOptions = new ImageOptions(); imageOptions.JpegQuality = 100; var tifImagePath = string.Format(@"{0}\{1}.tif", imgPaths, fileGUID); doc.SaveToImage(0, doc.PageCount, tifImagePath, imageOptions); Utils.Tif2Jpeg(tifImagePath, imgQuality, false); //拼接图片 if (combineImages) { int imgCount = pageCount; if (imgCount > 0) { Bitmap resultImg = null; Graphics resultGraphics = null; Image tempImage; for (int i = 0; i < imgCount; i++) { var imgFile = imgPaths + "\\" + i + ".jpg"; if (File.Exists(imgFile)) { tempImage = Image.FromFile(imgFile); if (resultImg == null) { _imageHeight = tempImage.Height; resultImg = new Bitmap(tempImage.Width, tempImage.Height * imgCount); resultGraphics = Graphics.FromImage(resultImg); } if (i == 0) { resultGraphics.DrawImage(tempImage, 0, 0); } else { resultGraphics.DrawImage(tempImage, 0, _imageHeight * i); } tempImage.Dispose(); } } result = string.Format(@"{0}\{1}.jpg", imgPaths, fileGUID); ImageUtility.CompressAsJPG(resultImg, result, imgQuality); resultGraphics.Dispose(); } } else { result = string.Format(@"{0}\{1}.jpg", imgPaths, 0); } return(result); }
public HttpResponseMessage Get(int?width, string file, int page, string watermarkText, int?watermarkColor, WatermarkPosition?watermarkPosition, int?watermarkWidth, byte watermarkOpacity, int?rotate, int?zoom, int?height = null) { if (Utils.IsValidUrl(file)) { file = Utils.DownloadToStorage(file); } ViewerImageHandler handler = Utils.CreateViewerImageHandler(); if (rotate.HasValue) { if (rotate.Value > 0) { handler.ClearCache(file); } } ImageOptions options = new ImageOptions(); options.PageNumbersToRender = new List <int>(new int[] { page }); options.PageNumber = page; options.CountPagesToRender = 1; if (Path.GetExtension(file).ToLower().StartsWith(".xls")) { options.CellsOptions.OnePagePerSheet = false; options.CellsOptions.CountRowsPerPage = 150; } if (watermarkText != "") { options.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity); } if (width.HasValue) { int w = Convert.ToInt32(width); if (zoom.HasValue) { w = w + zoom.Value; } options.Width = w; } if (height.HasValue) { if (zoom.HasValue) { options.Height = options.Height + zoom.Value; } } if (rotate.HasValue) { if (rotate.Value > 0) { if (width.HasValue) { int side = options.Width; DocumentInfoContainer documentInfoContainer = handler.GetDocumentInfo(file); int pageAngle = documentInfoContainer.Pages[page - 1].Angle; if (pageAngle == 90 || pageAngle == 270) { options.Height = side; } else { options.Width = side; } } options.Transformations = Transformation.Rotate; handler.RotatePage(file, new RotatePageOptions(page, rotate.Value)); } } else { options.Transformations = Transformation.None; handler.RotatePage(file, new RotatePageOptions(page, 0)); } List <PageImage> list = handler.GetPages(file, options); PageImage pageImage = list.Single(_ => _.PageNumber == page); Stream stream = pageImage.Stream; var result = new HttpResponseMessage(HttpStatusCode.OK); Image image = Image.FromStream(stream); MemoryStream memoryStream = new MemoryStream(); image.Save(memoryStream, ImageFormat.Jpeg); result.Content = new ByteArrayContent(memoryStream.ToArray()); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); return(result); }
protected override void ExecuteLogic() { label_1 : int num1 = 1635697149; while (true) { int num2 = 1548539289; uint num3; bool flag1; bool flag2; bool flag3; int num4; switch ((num3 = (uint)(num1 ^ num2)) % 38U) { case 0: num1 = (int)num3 * 817388502 ^ 1516195468; continue; case 1: flag2 = this.Image != null; num1 = (int)num3 * -1552463733 ^ 739592665; continue; case 2: this.SelectedWindow = this.SelectWindowActivity.SelectedWindow; num1 = (int)num3 * -733277401 ^ 1266568570; continue; case 3: num1 = (int)num3 * -1743578341 ^ 1713332418; continue; case 4: int num5 = !flag1 ? -546791168 : (num5 = -883883698); int num6 = (int)num3 * -1435481213; num1 = num5 ^ num6; continue; case 5: num1 = (int)num3 * -799245333 ^ 396749115; continue; case 6: num1 = (int)num3 * -434010976 ^ 645501731; continue; case 7: num1 = (int)num3 * 1451608575 ^ -1742017971; continue; case 8: num1 = (int)num3 * -1755395908 ^ -1652353021; continue; case 9: num1 = (int)num3 * 153377764 ^ 731091885; continue; case 10: num1 = 246013867; continue; case 11: CaptureWindow.\u206D(CoreObject.log, \u003CModule\u003E.\u200E <string>(3242682282U), (object)this.SelectedWindow.ZoomWindowType, (object)this.SelectedWindow.Location); Engine engine = this.Engine; ZoomWindow selectedWindow = this.SelectedWindow; Rectangle empty = Rectangle.Empty; int num7 = 4; ImageOptions options = new ImageOptions(); int num8 = this.Options.DisplayAfterCapture ? 1 : 0; options.DisplayAfterCapture = num8 != 0; int num9 = this.Options.SaveAfterCapture ? 1 : 0; options.SaveToDisk = num9 != 0; this.Image = engine.CaptureImage(selectedWindow, empty, (ImageEnums.ImageType)num7, options); num1 = (int)num3 * -1488827451 ^ -613173373; continue; case 12: int num10 = !flag3 ? -1972703555 : (num10 = -1515655614); int num11 = (int)num3 * 1927289461; num1 = num10 ^ num11; continue; case 13: if (this.SelectedWindow == null) { num4 = 0; break; } num1 = (int)num3 * 1792190431 ^ 1064619847; continue; case 14: this.SetActivityState(ActivityState.Error, \u003CModule\u003E.\u202A <string>(912275313U)); num1 = 757508855; continue; case 15: flag3 = this.ExecuteSubActivity((ActivityBase)this.SelectWindowActivity, true) == ActivityState.Completed; num1 = (int)num3 * 1772573488 ^ 1028897029; continue; case 16: num1 = (int)num3 * -1054487102 ^ 1742145425; continue; case 17: this.SetActivityState(ActivityState.Completed, \u003CModule\u003E.\u206B <string>(3867918917U)); num1 = (int)num3 * 1120419981 ^ 402066348; continue; case 18: this.SetActivityState(ActivityState.Completed, \u003CModule\u003E.\u206B <string>(2080111643U)); num1 = (int)num3 * -1238688538 ^ -2060013967; continue; case 19: num1 = (int)num3 * -1187976472 ^ 200346330; continue; case 20: num1 = 792080381; continue; case 21: int num12 = !flag2 ? 453108687 : (num12 = 1372017575); int num13 = (int)num3 * 311536320; num1 = num12 ^ num13; continue; case 22: goto label_3; case 23: goto label_1; case 24: CaptureVideoWindow captureVideoWindow = new CaptureVideoWindow(this.SelectedWindow); int num14 = 1; captureVideoWindow.AutoGenerated = num14 != 0; this.CaptureVideoWindowActivity = captureVideoWindow; num1 = (int)num3 * -1758141322 ^ 721204073; continue; case 25: num1 = 977563480; continue; case 26: this.SelectWindowActivity = new SelectWindow((List <ZoomWindowType>)null); num1 = (int)num3 * 349946333 ^ -1482052610; continue; case 27: num1 = (int)num3 * -983910695 ^ 1637485102; continue; case 28: num1 = (int)num3 * -808091807 ^ -822898148; continue; case 29: num4 = this.SelectedWindow.ZoomWindowType == ZoomWindowType.Video ? 1 : 0; break; case 30: num1 = (int)num3 * -1494712737 ^ 226378392; continue; case 31: flag1 = this.SelectedWindow != null; num1 = 368755319; continue; case 32: num1 = (int)num3 * 527554281 ^ 2019595519; continue; case 33: this.Engine.AddActivity((ActivityBase)this.CaptureVideoWindowActivity, \u003CModule\u003E.\u200E <string>(1431255308U)); num1 = (int)num3 * 155247578 ^ -1947810375; continue; case 34: num1 = (int)num3 * 2034461845 ^ -549995181; continue; case 35: num1 = (int)num3 * -985650129 ^ 830264663; continue; case 36: this.SetActivityState(this.SelectWindowActivity.ActivityState, this.SelectWindowActivity.Status); num1 = 792080381; continue; case 37: this.SetActivityState(ActivityState.Error, \u003CModule\u003E.\u202A <string>(2450088578U)); num1 = (int)num3 * -1981441049 ^ -1828609235; continue; default: goto label_43; } int num15; num1 = num15 = num4 == 0 ? 827305074 : (num15 = 872145089); } label_43: return; label_3 :; }
#pragma warning disable 1998 public async Task<ImageSource> GetImageAsync(PhotoSource source, ImageOptions options = null) #pragma warning restore 1998 { return null; }
#pragma warning disable 1998 public async Task<ImageSource> GetProcessedImageSourceAsync(ImageSource imageSource, ImageOptions options) #pragma warning restore 1998 { throw new NotImplementedException(); }
public async Task<ImageSource> GetProcessedImageSourceAsync(ImageSource imageSource, ImageOptions options) { var uiImage = await imageSource.GetImageAsync(); return ProcessImageSource(options, uiImage); }
private static ImageSource ProcessImageSource(ImageOptions options, UIImage image) { if (options != null) { if (options.HasSizeSet) image = MaxResizeImage(image, options.MaxWidth, options.MaxHeight); if (options.FixOrientation) image = FixOrientation(image); } return GetImageSourceFromUIImage(image); }
private static ImageSource ProcessImageFile(ImageOptions options, MediaFile file) { if (file == null) return null; var image = UIImage.FromFile(file.Path); return ProcessImage(options, image); }
/// <summary> /// Rotate page in Image mode /// </summary> public static void Rotate_page_in_Image_mode() { Console.WriteLine("***** {0} *****", "Rotate page in Image mode"); /* ********************* SAMPLE ********************* */ string licensePath = @"D:\GroupDocs.Viewer.lic"; // Setup license GroupDocs.Viewer.License lic = new GroupDocs.Viewer.License(); lic.SetLicense(licensePath); /* ******************** SAMPLE BEGIN *********************** */ /* ******************** Rotate 1st page of the document by 90 deg *********************** */ // Setup GroupDocs.Viewer config ViewerConfig config = new ViewerConfig(); config.StoragePath = @"C:\storage"; // Create image handler ViewerImageHandler imageHandler = new ViewerImageHandler(config); string guid = "word.doc"; // Set rotation angle 90 for page number 1 RotatePageOptions rotateOptions = new RotatePageOptions(guid, 1, 90); // Perform page rotation imageHandler.RotatePage(rotateOptions); /* ******************** Retrieve all document pages including transformation *********************** */ // Set image options to include rotate transformations ImageOptions imageOptions = new ImageOptions { Transformations = Transformation.Rotate }; // Get image representation of all document pages, including rotate transformations List<PageImage> pages = imageHandler.GetPages(guid, imageOptions); /* ******************** Retrieve all document pages excluding transformation *********************** */ // Set image options NOT to include ANY transformations ImageOptions noTransformationsOptions = new ImageOptions { Transformations = Transformation.None // This is by default }; // Get image representation of all document pages, without transformations List<PageImage> pagesWithoutTransformations = imageHandler.GetPages(guid, noTransformationsOptions); // Get image representation of all document pages, without transformations List<PageImage> pagesWithoutTransformations2 = imageHandler.GetPages(guid); /********************* SAMPLE END *************************/ //foreach (PageImage page in pages) //{ // // Page number // Console.WriteLine("Page number: {0}", page.PageNumber); // // Page image stream // Stream imageContent = page.Stream; // using ( // FileStream file = new FileStream(string.Format(@"C:\{0}.png", page.PageNumber), // FileMode.Create, FileAccess.ReadWrite)) // { // MemoryStream xxx = new MemoryStream(); // page.Stream.CopyTo(xxx); // var arr = xxx.ToArray(); // file.Write(arr, 0, arr.Length); // } //} }
public int GetMinWidth(ImageType type) { var option = ImageOptions.FirstOrDefault(i => i.Type == type); return(option == null ? 0 : option.MinWidth); }
public string GetThumbImageUrl(BaseItemDto item, ImageOptions options) { throw new NotImplementedException(); }
private static async Task<ImageSource> GetImageFromCameraAsync(ImageOptions options = null) { var mediaPicker = new MediaPicker(); if (mediaPicker.IsCameraAvailable) { try { var style = UIApplication.SharedApplication.StatusBarStyle; var file = await mediaPicker.TakePhotoAsync(new StoreCameraMediaOptions()); UIApplication.SharedApplication.StatusBarStyle = style; options = options ?? new ImageOptions(); options.FixOrientation = true; return ProcessImageFile(options, file); } catch (Exception) { return null; } } return null; }
public ActionResult GetDocumentPageImage(GetDocumentPageImageParameters parameters) { var guid = parameters.Path; var pageIndex = parameters.PageIndex; var pageNumber = pageIndex + 1; var imageOptions = new ImageOptions { //ConvertImageFileType = _convertImageFileType, /*Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor, parameters.WatermarkPosition, parameters.WatermarkWidth),*/ //Transformations = parameters.Rotate ? Transformation.Rotate : Transformation.None, PageNumbersToConvert = new List<int>() { parameters.PageIndex }, PageNumber = pageNumber, //JpegQuality = parameters.Quality.GetValueOrDefault() }; DocumentInfoContainer documentInfoContainer = annotator.GetDocumentInfo(guid); if (parameters.Rotate && parameters.Width.HasValue) { int pageAngle = documentInfoContainer.Pages[pageIndex].Angle; var isHorizontalView = pageAngle == 90 || pageAngle == 270; int sideLength = parameters.Width.Value; if (isHorizontalView) imageOptions.Height = sideLength; else imageOptions.Width = sideLength; } else if (parameters.Width.HasValue) { imageOptions.Width = parameters.Width.Value; } string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/"; // If no cache - save images to temp folder string tempFolderPath = Path.Combine(HttpContext.Server.MapPath("~"), "Content", "TempStorage"); PageImage pageImage; string docFoldePath = Path.Combine(tempFolderPath, parameters.Path); if (!Directory.Exists(docFoldePath)) Directory.CreateDirectory(docFoldePath); string pageImageName = string.Format("{0}\\{1}.png", docFoldePath, pageIndex); if (!System.IO.File.Exists(pageImageName)) { pageImage = annotator.GetPages(guid, imageOptions).Single(); using (FileStream fileStream = new FileStream(pageImageName, FileMode.Create)) { pageImage.Stream.Seek(0, SeekOrigin.Begin); pageImage.Stream.CopyTo(fileStream); } pageImage.Stream.Position = 0; return File(pageImage.Stream, String.Format("image/{0}", "png")); } Stream stream = new MemoryStream(); using (FileStream fsSource = new FileStream(pageImageName, FileMode.Open, FileAccess.Read)) { fsSource.Seek(0, SeekOrigin.Begin); fsSource.CopyTo(stream); } stream.Position = 0; return File(stream, "image/png"); }
public ActionResult GetImageUrls(GetImageUrlsParameters parameters) { if (string.IsNullOrEmpty(parameters.Path)) { GetImageUrlsResponse empty = new GetImageUrlsResponse { imageUrls = new string[0] }; var serialized = new JavaScriptSerializer().Serialize(empty); return Content(serialized, "application/json"); } var imageOptions = new ImageOptions(); var imagePages = _imageHandler.GetPages(parameters.Path, imageOptions); // Save images some where and provide urls var urls = new List<string>(); var tempFolderPath = Path.Combine(Server.MapPath("~"), "Content", "TempStorage"); foreach (var pageImage in imagePages) { var docFoldePath = Path.Combine(tempFolderPath, parameters.Path); if (!Directory.Exists(docFoldePath)) Directory.CreateDirectory(docFoldePath); var pageImageName = string.Format("{0}\\{1}.png", docFoldePath, pageImage.PageNumber); using (var stream = pageImage.Stream) using (FileStream fileStream = new FileStream(pageImageName, FileMode.Create)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/"; urls.Add(string.Format("{0}Content/TempStorage/{1}/{2}.png", baseUrl, parameters.Path, pageImage.PageNumber)); } GetImageUrlsResponse result = new GetImageUrlsResponse { imageUrls = urls.ToArray() }; var serializedData = new JavaScriptSerializer().Serialize(result); return Content(serializedData, "application/json"); }
public int GetLimit(ImageType type) { var option = ImageOptions.FirstOrDefault(i => i.Type == type); return(option == null ? 1 : option.Limit); }
public ActionResult ViewDocument(ViewDocumentParameters request) { var fileName = Path.GetFileName(request.Path); var result = new ViewDocumentResponse { pageCss = new string[] {}, lic = true, pdfDownloadUrl = GetPdfDownloadUrl(request), pdfPrintUrl = GetPdfPrintUrl(request), url = GetFileUrl(request), path = request.Path, name = fileName }; var docInfo = _imageHandler.GetDocumentInfo(new DocumentInfoOptions(request.Path)); result.documentDescription = new FileDataJsonSerializer(docInfo.Pages, new FileDataOptions()).Serialize(true); result.docType = docInfo.DocumentType; result.fileType = docInfo.FileType; var imageOptions = new ImageOptions {Watermark = GetWatermark(request)}; var imagePages = _imageHandler.GetPages(request.Path, imageOptions); // Provide images urls var urls = new List<string>(); // If no cache - save images to temp folder //var tempFolderPath = Path.Combine(Microsoft.SqlServer.Server.MapPath("~"), "Content", "TempStorage"); var tempFolderPath = Path.Combine(HttpContext.Server.MapPath("~"), "Content", "TempStorage"); foreach (var pageImage in imagePages) { var docFoldePath = Path.Combine(tempFolderPath, request.Path); if (!Directory.Exists(docFoldePath)) Directory.CreateDirectory(docFoldePath); var pageImageName = string.Format("{0}\\{1}.png", docFoldePath, pageImage.PageNumber); using (var stream = pageImage.Stream) using (FileStream fileStream = new FileStream(pageImageName, FileMode.Create)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/"; urls.Add(string.Format("{0}Content/TempStorage/{1}/{2}.png", baseUrl, request.Path, pageImage.PageNumber)); } result.imageUrls = urls.ToArray(); var serializer = new JavaScriptSerializer {MaxJsonLength = int.MaxValue}; var serializedData = serializer.Serialize(result); return Content(serializedData, "application/json"); }
internal static void ApplyCustomizations(Arguments arguments, ref ImageOptions image, ref TitleOptions title) { Regex colorExtraction = new Regex(@"(\d+)"); if (arguments.ImageWidth != image.InitialWidth) { image.InitialWidth = arguments.ImageWidth; } if (arguments.ImageHeight != image.InitialHeight) { image.InitialHeight = arguments.ImageHeight; } if (!string.IsNullOrEmpty(arguments.BackgroundColor)) { byte[] colorVals = colorExtraction.Matches(arguments.BackgroundColor).Select(x => byte.Parse(x.Value) ).ToArray(); image.BackgroundColor = new Rgba32(colorVals[0], colorVals[1], colorVals[2], colorVals[3]); } if (arguments.HorizontalDistanceBetweenPoints != image.MinimumHorizontalClearance) { image.MinimumHorizontalClearance = arguments.HorizontalDistanceBetweenPoints; } if (arguments.VerticalDistanceToImageEdge != image.MinimumVerticalClearance) { image.MinimumVerticalClearance = arguments.VerticalDistanceToImageEdge; } if (arguments.CanImageBeResized != image.CanResize) { image.CanResize = arguments.CanImageBeResized; } if (arguments.DoAxesScaleIndependently != image.ScaleImageAxesIndepentently) { image.ScaleImageAxesIndepentently = arguments.DoAxesScaleIndependently; } if (!string.IsNullOrEmpty(arguments.TitleColor)) { byte[] colorVals = colorExtraction.Matches(arguments.TitleColor).Select(x => byte.Parse(x.Value) ).ToArray(); title.Color = new Rgba32(colorVals[0], colorVals[1], colorVals[2], colorVals[3]); } if (arguments.TitleLocation != title.Position) { title.Position = arguments.TitleLocation; } if (arguments.HorizontalOffset != title.XOffset) { title.XOffset = arguments.HorizontalOffset; } if (arguments.VerticalOffset != title.YOffset) { title.YOffset = arguments.VerticalOffset; } }
private static EMElement Create( TransformationData data, EMDocument doc, EMElementOrigin origin, EMElement parent, string url, string alt, string title, string convert, string width, string height, string convertQuality, string hexFillColor, string convertType, ImageOptions options) { ImageFormat imageFormatType; if (String.IsNullOrWhiteSpace(url)) { return(EMErrorElement.Create(doc, origin, parent, data, "EmptyLink", origin.Text)); } alt = alt.Replace("\"", """); if (title != null) { title = title.Replace("\"", """); } if (url.StartsWith("<") && url.EndsWith(">")) { url = url.Substring(1, url.Length - 2); // Remove <>'s surrounding URL, if present } if (String.IsNullOrWhiteSpace(alt)) { //if no alt text provided use the file name. alt = Regex.Replace(url, @".*[\\|/](.*)", "$1"); } var doConvert = !convert.ToLower().Equals("false") && data.Markdown.DefaultImageDoCompress; int widthIntConverted; int heightIntConverted; int quality; Color fillColor; if (doConvert) { //if we are converting try to get the other values //try parse the strings for width and height into integers try { widthIntConverted = Int32.Parse(width); } catch (FormatException) { widthIntConverted = 0; } try { heightIntConverted = Int32.Parse(height); } catch (FormatException) { heightIntConverted = 0; } try { quality = Int32.Parse(convertQuality); } catch (FormatException) { quality = data.Markdown.DefaultImageQuality; } try { fillColor = ImageConversion.GetColorFromHexString(hexFillColor); } catch (Exception) { fillColor = data.Markdown.DefaultImageFillColor; } if (String.IsNullOrWhiteSpace(convertType)) { convertType = data.Markdown.DefaultImageFormatExtension; imageFormatType = data.Markdown.DefaultImageFormat; } else { try { imageFormatType = ImageConversion.GetImageFormat(convertType.ToLower()); } catch (Exception) { return(EMErrorElement.Create( doc, origin, parent, data, "UnsupportedImageFileTypeConversion", Markdown.Unescape(url), convertType.ToLower())); } } } else { //set width and height to zero indicating to converter that we want to use the images values widthIntConverted = 0; heightIntConverted = 0; //set conversion type to itself, but do check it is a supported image type. convertType = Regex.Match(Markdown.Unescape(url), @"\.(png|gif|tga|bmp|jpg)", RegexOptions.IgnoreCase).Groups[1].Value; try { imageFormatType = ImageConversion.GetImageFormat(convertType.ToLower()); } catch (Exception) { return(EMErrorElement.Create( doc, origin, parent, data, "UnsupportedImageFileTypeConversion", Markdown.Unescape(url), convertType.ToLower())); } quality = 100; fillColor = data.Markdown.DefaultImageFillColor; } if (!String.IsNullOrWhiteSpace(convertType)) { try { var path = new EMLocalFilePath(Markdown.Unescape(url), doc, data, fileName => System.IO.Path.GetFileNameWithoutExtension(fileName) + "." + ImageConversion.GetImageExt(imageFormatType)); if (!path.IsImage) { throw new EMPathVerificationException(Language.Message("GivenPathIsNotAnImage", url)); } data.ImageDetails.Add( new ImageConversion( path.GetSource(), path.GetAbsolutePath(data), widthIntConverted, heightIntConverted, doConvert, imageFormatType, fillColor, quality)); return(new EMImage(doc, origin, parent, path, title, alt, options)); } catch (EMPathVerificationException e) { return(new EMErrorElement(doc, origin, parent, e.AddToErrorList(data, origin.Text))); } } throw new InvalidOperationException("Should not happen!"); }
public Property(Entity entity, PropertyInfo property) { if (property == null) { throw new ArgumentNullException("property"); } if (entity == null) { throw new ArgumentNullException("entity"); } Entity = entity; PropertyInfo = property; Name = property.Name; ColumnName = property.Name; ControlsAttributes = new Dictionary <string, object>(); // TODO: determine ColumnName TypeInfo = new PropertyTypeInfo(property.PropertyType, Attributes); ImageOptions = new ImageOptions(Attributes, Entity.Name); Value = new PropertyValue(TypeInfo); Template = new PropertyTemplate(Attributes, TypeInfo, IsForeignKey); if (TypeInfo.DataType == DataType.Numeric) { if (TypeInfo.IsFloatingPoint) { ControlsAttributes.Add("data-number-number-of-decimals", "4"); } if (TypeInfo.IsNullable) { ControlsAttributes.Add("data-number-value", ""); } } SetForeignKey(Attributes); SetDeleteOption(Attributes); IsKey = Attributes.OfType <KeyAttribute>().Any(); IsLinkKey = Attributes.OfType <LinkKeyAttribute>().Any(); var columnAttribute = Attributes.OfType <ColumnAttribute>().FirstOrDefault(); if (columnAttribute != null) { ColumnName = columnAttribute.Name; } var requiredAttribute = Attributes.OfType <RequiredAttribute>().FirstOrDefault(); if (requiredAttribute != null) { IsRequired = true; RequiredErrorMessage = requiredAttribute.ErrorMessage; } var displayAttribute = Attributes.OfType <DisplayAttribute>().FirstOrDefault(); if (displayAttribute != null) { DisplayName = displayAttribute.Name ?? Name.SplitCamelCase(); Description = displayAttribute.Description; GroupName = displayAttribute.GroupName ?? IlaroAdminResources.Others; } else { DisplayName = Name.SplitCamelCase(); GroupName = IlaroAdminResources.Others; } }
protected override async Task <Stream> CreateImageWriterStreamAsync(ImageConfiguration configuration, Stream output, long totalBytes) { Imaging.ImageFormat imageFormat = ImageFormatFactory.GetFormat(configuration.Format); var pixelStorageSerializer = new PixelStorageOptionsSerializer(); totalBytes += pixelStorageSerializer.CalculateStorageLength(imageFormat); ImageDimensions embeddedImageDimensions = null; PixelStorageOptions pixelStorageOptions; Stream embeddedImageStream = null; if (configuration.HasEmbeddedImage) { embeddedImageDimensions = new ImageDimensions(configuration.EmbeddedImage.Image); pixelStorageOptions = _pixelStorageCalculator.CalculatePixelStorageOptions( imageFormat, configuration.EmbeddedImage.EmbeddedPixelStorage, embeddedImageDimensions, totalBytes); embeddedImageStream = imageFormat.LoadPixelDataStream(configuration.EmbeddedImage.Image); } else { pixelStorageOptions = imageFormat.PixelStorageWithBitsPerChannel( 8, PixelStorageOptions.BitStorageMode.MostSignificantBits); } byte[] pixelStorageBytes = await pixelStorageSerializer.SerializeToBytesAsync(pixelStorageOptions); int embeddedImageRepeats; ImageOptions imageOptions = GenerateImageOptions( configuration, imageFormat, CalculateImageDimensions(imageFormat, pixelStorageOptions, embeddedImageDimensions, totalBytes, out embeddedImageRepeats)); Stream imageStream = imageFormat.CreateWriter(imageOptions).CreateOutputStream(output, true, EncodingConfiguration.BufferSize); await WriteHeaderAsync(imageStream); await imageStream.WriteAsync(pixelStorageBytes, 0, pixelStorageBytes.Length); if (configuration.HasEmbeddedImage) { var repeatingImageStream = new RepeatingStream(embeddedImageStream, embeddedImageRepeats); return(new PixelStorageWriterStream( imageStream, new SubStream( repeatingImageStream, imageStream.Position, repeatingImageStream.Length - repeatingImageStream.Position - imageStream.Position), pixelStorageOptions, leaveOpen: false, bufferSize: EncodingConfiguration.BufferSize)); } return(imageStream); }
internal void ImageOptionsChanged(ImageOptions imageOptions) { this.ImageOptions = imageOptions; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null) { var type = value.GetType(); var apiClient = SimpleIoc.Default.GetInstance <IExtendedApiClient>(); if (type == typeof(BaseItemDto)) { var imageType = parameter == null ? string.Empty : (string)parameter; // http://192.168.0.2:8096/mediabrowser/api/image?item.Id=d0aac36ee980d7dc0bcf8323b1884f70&maxheight=173&quality=90 var item = (BaseItemDto)value; return(GetDtoImage(item, imageType, apiClient)); } if (type == typeof(BaseItemPerson)) { var person = (BaseItemPerson)value; if (person.HasPrimaryImage) { var smallImageSize = parameter == null; return(apiClient.GetPersonImageUrl(person, new ImageOptions { MaxWidth = smallImageSize ? 99 : 200, Quality = 90 })); } } if (type == typeof(UserDto)) { var user = (UserDto)value; if (user.HasPrimaryImage) { var url = apiClient.GetUserImageUrl(user, new ImageOptions { MaxHeight = 173, MaxWidth = 173, Quality = 95 }); return(new Uri(url)); } } if (type == typeof(SearchHint)) { var searchHint = (SearchHint)value; var imageOptions = new ImageOptions { #if WP8 MaxHeight = 159, MaxWidth = 159 #else MaxHeight = 100, MaxWidth = 100 #endif }; switch (searchHint.Type) { case "Person": return(apiClient.GetPersonImageUrl(searchHint.Name, imageOptions)); case "Artist": return(apiClient.GetArtistImageUrl(searchHint.Name, imageOptions)); case "MusicGenre": case "GameGenre": return(apiClient.GetGenreImageUrl(searchHint.Name, imageOptions)); case "Studio": return(apiClient.GetStudioImageUrl(searchHint.Name, imageOptions)); default: return(apiClient.GetImageUrl(searchHint.ItemId, imageOptions)); } } if (type == typeof(BaseItemInfo)) { var item = (BaseItemInfo)value; var imageType = parameter == null ? string.Empty : (string)parameter; var imageOptions = new ImageOptions { ImageType = ImageType.Primary }; if (imageType.Equals("backdrop")) { imageOptions.ImageType = ImageType.Backdrop; imageOptions.MaxWidth = 480; } else { #if !WP8 imageOptions.MaxHeight = 220; #else imageOptions.MaxHeight = 440; #endif } return(apiClient.GetImageUrl(item.Id, imageOptions)); } } return(""); }
public FileService(IWebHostEnvironment env, IOptions <ImageOptions> options) { this.env = env; this.options = options.Value; }
public static List <PageImage> LoadPageImageList(ViewerImageHandler handler, String filename, ImageOptions options) { try { return(handler.GetPages(filename, options)); } catch (Exception x) { throw x; } }
public ActionResult ViewDocument(ViewDocumentParameters request) { var fileName = Path.GetFileName(request.Path); var result = new ViewDocumentResponse { pageCss = new string[] {}, lic = true, pdfDownloadUrl = GetPdfDownloadUrl(request), pdfPrintUrl = GetPdfPrintUrl(request), url = GetFileUrl(request), path = request.Path, name = fileName }; var docInfo = _imageHandler.GetDocumentInfo(new DocumentInfoOptions(request.Path)); result.documentDescription = new FileDataJsonSerializer(docInfo.Pages, new FileDataOptions()).Serialize(true); result.docType = docInfo.DocumentType; result.fileType = docInfo.FileType; var imageOptions = new ImageOptions { Watermark = GetWatermark(request) }; var imagePages = _imageHandler.GetPages(request.Path, imageOptions); // Provide images urls var urls = new List <string>(); // If no cache - save images to temp folder //var tempFolderPath = Path.Combine(Microsoft.SqlServer.Server.MapPath("~"), "Content", "TempStorage"); var tempFolderPath = Path.Combine(HttpContext.Server.MapPath("~"), "Content", "TempStorage"); foreach (var pageImage in imagePages) { var docFoldePath = Path.Combine(tempFolderPath, request.Path); if (!Directory.Exists(docFoldePath)) { Directory.CreateDirectory(docFoldePath); } var pageImageName = string.Format("{0}\\{1}.png", docFoldePath, pageImage.PageNumber); using (var stream = pageImage.Stream) using (FileStream fileStream = new FileStream(pageImageName, FileMode.Create)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/"; urls.Add(string.Format("{0}Content/TempStorage/{1}/{2}.png", baseUrl, request.Path, pageImage.PageNumber)); } result.imageUrls = urls.ToArray(); var serializer = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; var serializedData = serializer.Serialize(result); return(Content(serializedData, "application/json")); }
private ImageSource ProcessImageStream(ImageOptions options, Stream stream, string url) { var bitmap = Image.FromStream(stream); if (options != null) { if (options.HasSizeSet) bitmap = MaxResizeImage(bitmap, options.MaxWidth, options.MaxHeight); } using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Jpeg); ms.Seek(0, SeekOrigin.Begin); var numBytesToRead = (int)ms.Length; var bytes = new byte[numBytesToRead]; ms.Read(bytes, 0, numBytesToRead); var imageSource = ImageSource.FromStream(() => new MemoryStream(bytes)); _cachedImages[url] = imageSource; return imageSource; } }
private EMImage(EMDocument doc, EMElementOrigin origin, EMElement parent, EMLocalFilePath path, string title, string alt, ImageOptions options) : base(doc, origin, parent) { Path = path; Title = title; Alt = alt; Options = options; }
protected void Page_Load(object sender, EventArgs e) { var file = GetValueFromQueryString("file"); var attachment = GetValueFromQueryString("attachment"); int page = Convert.ToInt32(GetValueFromQueryString("page")); int?width = Convert.ToInt32(GetValueFromQueryString("width")); int?height = Convert.ToInt32(GetValueFromQueryString("width")); if (Utils.IsValidUrl(file)) { file = Utils.DownloadToStorage(file); } string watermarkText = GetValueFromQueryString("watermarkText"); int? watermarkColor = Convert.ToInt32(GetValueFromQueryString("watermarkColor")); WatermarkPosition watermarkPosition = (WatermarkPosition)Enum.Parse(typeof(WatermarkPosition), GetValueFromQueryString("watermarkPosition"), true); string widthFromQuery = GetValueFromQueryString("watermarkWidth"); int? watermarkWidth = GetValueFromQueryString("watermarkWidth") == "null" ? null : (int?)Convert.ToInt32(GetValueFromQueryString("watermarkWidth")); byte watermarkOpacity = Convert.ToByte(GetValueFromQueryString("watermarkOpacity")); ViewerImageHandler handler = Utils.CreateViewerImageHandler(); ImageOptions o = new ImageOptions(); List <int> pageNumberstoRender = new List <int>(); pageNumberstoRender.Add(page); o.PageNumbersToRender = pageNumberstoRender; o.PageNumber = page; o.CountPagesToRender = 1; if (width.HasValue) { o.Width = Convert.ToInt32(width); } if (height.HasValue) { o.Height = Convert.ToInt32(height); } if (watermarkText != "") { o.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity); } Stream stream = null; DocumentInfoContainer info = handler.GetDocumentInfo(file); // Iterate over the attachments collection foreach (AttachmentBase attachmentBase in info.Attachments.Where(x => x.Name == attachment)) { List <PageImage> pages = handler.GetPages(attachmentBase); foreach (PageImage attachmentPage in pages.Where(x => x.PageNumber == page)) { stream = attachmentPage.Stream; } ; } var result = new HttpResponseMessage(HttpStatusCode.OK); System.Drawing.Image image = System.Drawing.Image.FromStream(stream); MemoryStream memoryStream = new MemoryStream(); image.Save(memoryStream, ImageFormat.Jpeg); HttpContext.Current.Response.ContentType = "image/jpeg"; memoryStream.WriteTo(HttpContext.Current.Response.OutputStream); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); }
protected void Page_Load(object sender, EventArgs e) { _config = new ViewerConfig { StoragePath = _storagePath, UseCache = true }; ViewerImageHandler imageHandler = (ViewerImageHandler)HttpContext.Current.Session["imageHandler"]; ViewerHtmlHandler htmlHandler = (ViewerHtmlHandler)HttpContext.Current.Session["htmlHandler"]; GetDocumentPageImageParameters parameters = new GetDocumentPageImageParameters(); foreach (String key in Request.QueryString.AllKeys) { if (!string.IsNullOrEmpty(Request.QueryString[key])) { var propertyInfo = parameters.GetType().GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); propertyInfo.SetValue(parameters, ChangeType(Request.QueryString[key], propertyInfo.PropertyType), null); } } string guid = parameters.Path; int pageIndex = parameters.PageIndex; int pageNumber = pageIndex + 1; var displayName = parameters.Path; /* * //NOTE: This feature is supported starting from version 3.2.0 * CultureInfo cultureInfo = string.IsNullOrEmpty(parameters.Locale) * ? new CultureInfo("en-Us") * : new CultureInfo(parameters.Locale); * * ViewerImageHandler viewerImageHandler = new ViewerImageHandler(viewerConfig, cultureInfo); */ var imageOptions = new ImageOptions { //ConvertImageFileType = _convertImageFileType, ConvertImageFileType = ConvertImageFileType.JPG, JpegQuality = 100, Watermark = Utils.GetWatermark(parameters.WatermarkText, parameters.WatermarkColor, parameters.WatermarkPosition, parameters.WatermarkWidth), Transformations = parameters.Rotate ? Transformation.Rotate : Transformation.None }; if (parameters.Rotate && parameters.Width.HasValue) { DocumentInfoContainer documentInfoContainer = imageHandler.GetDocumentInfo(guid); int side = parameters.Width.Value; int pageAngle = documentInfoContainer.Pages[pageIndex].Angle; if (pageAngle == 90 || pageAngle == 270) { imageOptions.Height = side; } else { imageOptions.Width = side; } } /* * //NOTE: This feature is supported starting from version 3.2.0 * if (parameters.Quality.HasValue) * imageOptions.JpegQuality = parameters.Quality.Value; */ using (new InterProcessLock(guid)) { List <PageImage> pageImages = imageHandler.GetPages(guid, imageOptions); PageImage pageImage = pageImages.Single(_ => _.PageNumber == pageNumber); var fileStream = pageImage.Stream; // return File(pageImage.Stream, GetContentType(_convertImageFileType)); byte[] Bytes = new byte[fileStream.Length]; fileStream.Read(Bytes, 0, Bytes.Length); string contentDispositionString = "attachment; filename=\"" + displayName + "\""; contentDispositionString = new ContentDisposition { FileName = displayName, Inline = true }.ToString(); HttpContext.Current.Response.ContentType = "image/jpeg"; HttpContext.Current.Response.AddHeader("Content-Disposition", contentDispositionString); HttpContext.Current.Response.AddHeader("Content-Length", fileStream.Length.ToString()); try { HttpContext.Current.Response.OutputStream.Write(Bytes, 0, Bytes.Length); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (HttpException x) { // Ignore it. } } }
private static object GetDtoImage(BaseItemDto item, string imageType, IExtendedApiClient apiClient) { if (item.ImageTags.IsNullOrEmpty()) { return(""); } var imageOptions = new ImageOptions { Quality = 90, #if WP8 MaxHeight = 336, #else MaxHeight = 173, #endif ImageType = ImageType.Primary }; if (imageType.Equals("logo", StringComparison.OrdinalIgnoreCase)) { imageOptions.ImageType = ImageType.Logo; } else if (imageType.Equals("backdrop")) { imageOptions.MaxHeight = 800; imageOptions.ImageType = ImageType.Backdrop; var images = apiClient.GetBackdropImageUrls(item, imageOptions); if (!images.IsNullOrEmpty()) { return(images.FirstOrDefault()); } } else if (imageType.Equals("primaryorbackdrop")) { if (!item.HasPrimaryImage) { imageOptions.MaxHeight = 800; imageOptions.ImageType = ImageType.Backdrop; var images = apiClient.GetBackdropImageUrls(item, imageOptions); if (!images.IsNullOrEmpty()) { return(images.FirstOrDefault()); } } } else if (imageType.Equals("backdropsmall", StringComparison.OrdinalIgnoreCase)) { #if WP8 imageOptions.MaxHeight = 336; #else imageOptions.MaxHeight = 173; #endif imageOptions.ImageType = ImageType.Backdrop; var images = apiClient.GetBackdropImageUrls(item, imageOptions); if (!images.IsNullOrEmpty()) { return(images.FirstOrDefault()); } } else if (imageType.Equals("banner", StringComparison.OrdinalIgnoreCase)) { imageOptions.MaxHeight = 140; imageOptions.ImageType = ImageType.Banner; } else if (imageType.Equals("art", StringComparison.OrdinalIgnoreCase)) { imageOptions.ImageType = ImageType.Art; } else if (imageType.Equals("thumbnail", StringComparison.OrdinalIgnoreCase)) { imageOptions.ImageType = ImageType.Thumb; } else if (imageType.Equals("icon", StringComparison.OrdinalIgnoreCase)) { #if WP8 imageOptions.MaxHeight = 159; #else imageOptions.MaxHeight = 90; #endif } else if (imageType.Equals("poster", StringComparison.OrdinalIgnoreCase)) { #if WP8 imageOptions.MaxHeight = 675; #else imageOptions.MaxHeight = 450; #endif } else if (imageType.Equals("episode", StringComparison.OrdinalIgnoreCase)) { #if WP8 imageOptions.MaxHeight = 382; #else imageOptions.MaxHeight = 255; #endif } else { #if WP8 imageOptions.MaxHeight = 300; #else imageOptions.MaxHeight = 200; #endif } try { string url = item.Type == "Series" ? apiClient.GetImageUrl(item.Id, imageOptions) : apiClient.GetImageUrl(item, imageOptions); return(url); } catch { return(""); } }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null) { var type = value.GetType(); var manager = SimpleIoc.Default.GetInstance <IConnectionManager>(); var apiClient = manager.GetApiClient(App.ServerInfo.Id); if (type == typeof(BaseItemDto)) { var imageType = parameter == null ? string.Empty : (string)parameter; // http://192.168.0.2:8096/mediabrowser/api/image?item.Id=d0aac36ee980d7dc0bcf8323b1884f70&maxheight=173&quality=90 var item = (BaseItemDto)value; return(GetDtoImage(item, imageType, apiClient)); } if (type == typeof(BaseItemPerson)) { var person = (BaseItemPerson)value; if (person.HasPrimaryImage) { var smallImageSize = parameter == null; return(apiClient.GetPersonImageUrl(person, new ImageOptions { MaxWidth = smallImageSize ? 99 : 200, Quality = Constants.ImageQuality, EnableImageEnhancers = App.SpecificSettings.EnableImageEnhancers })); } } if (type == typeof(UserDto)) { var user = (UserDto)value; if (user.HasPrimaryImage) { var url = apiClient.GetUserImageUrl(user, new ImageOptions { MaxHeight = 250, MaxWidth = 250, Quality = Constants.ImageQuality }); return(new Uri(url)); } } if (type == typeof(SearchHint)) { var searchHint = (SearchHint)value; var imageOptions = new ImageOptions { EnableImageEnhancers = App.SpecificSettings.EnableImageEnhancers, MaxHeight = 159, MaxWidth = 159, Quality = Constants.ImageQuality }; switch (searchHint.Type) { case "MusicGenre": case "GameGenre": return(apiClient.GetGenreImageUrl(searchHint.Name, imageOptions)); default: return(apiClient.GetImageUrl(searchHint.ItemId, imageOptions)); } } if (type == typeof(BaseItemInfo)) { var item = (BaseItemInfo)value; var imageType = parameter == null ? string.Empty : (string)parameter; var imageOptions = new ImageOptions { EnableImageEnhancers = App.SpecificSettings.EnableImageEnhancers, ImageType = ImageType.Primary, Quality = Constants.ImageQuality }; if (imageType.Equals("backdrop")) { imageOptions.ImageType = ImageType.Backdrop; imageOptions.MaxWidth = 480; } else { imageOptions.MaxHeight = 440; } return(apiClient.GetImageUrl(item.Id, imageOptions)); } if (type == typeof(ChannelInfoDto)) { var item = (ChannelInfoDto)value; var imageOptions = new ImageOptions { ImageType = ImageType.Primary, MaxHeight = 122, Quality = Constants.ImageQuality }; return(item.HasPrimaryImage ? apiClient.GetImageUrl(item, imageOptions) : string.Empty); } if (type == typeof(TimerInfoDto)) { var item = (TimerInfoDto)value; var imageOptions = new ImageOptions { ImageType = ImageType.Primary, Quality = Constants.ImageQuality, MaxHeight = 250 }; return(item.ProgramInfo.HasPrimaryImage ? apiClient.GetImageUrl(item.ProgramInfo, imageOptions) : string.Empty); } if (type == typeof(SyncJob)) { var item = (SyncJob)value; var imageOptions = new ImageOptions { ImageType = ImageType.Primary, Quality = Constants.ImageQuality, MaxHeight = 250, Tag = item.PrimaryImageTag }; return(string.IsNullOrEmpty(item.PrimaryImageItemId) ? string.Empty : apiClient.GetImageUrl(item.PrimaryImageItemId, imageOptions)); } if (type == typeof(SyncJobItem)) { var item = (SyncJobItem)value; var imageOptions = new ImageOptions { ImageType = ImageType.Primary, Quality = Constants.ImageQuality, MaxHeight = 250, Tag = item.PrimaryImageTag }; return(string.IsNullOrEmpty(item.PrimaryImageItemId) ? string.Empty : apiClient.GetImageUrl(item.PrimaryImageItemId, imageOptions)); } } return(""); }
public AddImageAssetCommand(IMongoCollection <ImageAsset> assetCollection, IOptions <ImageOptions> imageOptions) { _assetCollection = assetCollection; _imageOptions = imageOptions.Value; }
private static object GetDtoImage(BaseItemDto item, string imageType, IApiClient apiClient) { if (item.ImageTags.IsNullOrEmpty() && item.BackdropImageTags.IsNullOrEmpty()) { return(""); } var imageOptions = new ImageOptions { EnableImageEnhancers = App.SpecificSettings.EnableImageEnhancers, Quality = Constants.ImageQuality, MaxHeight = 336, ImageType = ImageType.Primary }; if (item.Type == "Recording") { imageOptions.MaxHeight = 250; } else if (item.Type == "Program") { imageOptions.MaxHeight = 250; } else if (imageType.Equals("logo", StringComparison.OrdinalIgnoreCase)) { imageOptions.ImageType = ImageType.Logo; } else if (imageType.Equals("backdrop")) { imageOptions.MaxHeight = 800; imageOptions.ImageType = ImageType.Backdrop; var images = apiClient.GetBackdropImageUrls(item, imageOptions); if (!images.IsNullOrEmpty()) { return(images.FirstOrDefault()); } } else if (imageType.Equals("primaryorbackdrop")) { if (!item.HasPrimaryImage) { imageOptions.MaxHeight = 800; imageOptions.ImageType = ImageType.Backdrop; var images = apiClient.GetBackdropImageUrls(item, imageOptions); if (!images.IsNullOrEmpty()) { return(images.FirstOrDefault()); } } } else if (imageType.Equals("backdropsmall", StringComparison.OrdinalIgnoreCase)) { imageOptions.MaxHeight = 336; imageOptions.ImageType = ImageType.Backdrop; var images = apiClient.GetBackdropImageUrls(item, imageOptions); if (!images.IsNullOrEmpty()) { return(images.FirstOrDefault()); } } else if (imageType.Equals("banner", StringComparison.OrdinalIgnoreCase)) { imageOptions.MaxHeight = 140; imageOptions.ImageType = ImageType.Banner; } else if (imageType.Equals("art", StringComparison.OrdinalIgnoreCase)) { imageOptions.ImageType = ImageType.Art; } else if (imageType.Equals("thumbnail", StringComparison.OrdinalIgnoreCase)) { imageOptions.ImageType = ImageType.Thumb; } else if (imageType.Equals("icon", StringComparison.OrdinalIgnoreCase)) { imageOptions.MaxHeight = 159; } else if (imageType.Equals("poster", StringComparison.OrdinalIgnoreCase)) { imageOptions.MaxHeight = 675; } else if (imageType.Equals("episode", StringComparison.OrdinalIgnoreCase)) { imageOptions.MaxHeight = 382; } else { imageOptions.MaxHeight = 300; } try { string url = item.Type == "Series" ? apiClient.GetImageUrl(item.Id, imageOptions) : apiClient.GetImageUrl(item, imageOptions); return(url); } catch { return(""); } }
public ActionResult Get(int?width, int?height, string file, int page, string watermarkText, int?watermarkColor, WatermarkPosition?watermarkPosition, int?watermarkWidth, byte watermarkOpacity, int?rotate, int?zoom) { if (Utils.IsValidUrl(file)) { file = Utils.DownloadToStorage(file); } ViewerImageHandler handler = Utils.CreateViewerImageHandler(); if (rotate.HasValue) { if (rotate.Value > 0) { handler.ClearCache(file); } } ImageOptions options = new ImageOptions(); options.PageNumbersToRender = new List <int>(new int[] { page }); options.PageNumber = page; options.CountPagesToRender = 1; if (Path.GetExtension(file).ToLower().StartsWith(".xls")) { options.CellsOptions.OnePagePerSheet = false; options.CellsOptions.CountRowsPerPage = 150; } if (watermarkText != "") { options.Watermark = Utils.GetWatermark(watermarkText, watermarkColor, watermarkPosition, watermarkWidth, watermarkOpacity); } if (width.HasValue) { int w = Convert.ToInt32(width); if (zoom.HasValue) { w = w + zoom.Value; } options.Width = w; } if (height.HasValue) { if (zoom.HasValue) { options.Height = options.Height + zoom.Value; } } if (rotate.HasValue) { if (rotate.Value > 0) { if (width.HasValue) { int side = options.Width; DocumentInfoContainer documentInfoContainer = handler.GetDocumentInfo(file); int pageAngle = documentInfoContainer.Pages[page - 1].Angle; if (pageAngle == 90 || pageAngle == 270) { options.Height = side; } else { options.Width = side; } } options.Transformations = Transformation.Rotate; handler.RotatePage(file, new RotatePageOptions(page, rotate.Value)); } } else { options.Transformations = Transformation.None; handler.RotatePage(file, new RotatePageOptions(page, 0)); } using (new InterProcessLock(file)) { List <PageImage> list = handler.GetPages(file, options); PageImage pageImage = list.Single(_ => _.PageNumber == page); return(File(pageImage.Stream, "image/png")); } }
/// <summary> /// /// </summary> /// <param name="options"></param> /// <returns></returns> public string Resize(ImageOptions options) { var path = ImagePath.TrimStart(new[] { '/', '\\' }); var match = path.Match(options.ResizePathPattern, RegexOptions.IgnoreCase); if (!match.Success) { return(options.EmptyImagePath); } var str_parameters = match.Groups["parameters"].Value; var str_size = match.Groups["size"].Value; var str_color = match.Groups["color"].Value; var imageSourcePath = Path.Combine(options.RootDirectory, path.Replace(str_parameters, string.Empty)); if (!File.Exists(imageSourcePath)) { var dotIndex = options.EmptyImagePath.LastIndexOf("."); return($"{options.EmptyImagePath.Substring(0, dotIndex)}{str_parameters}{options.EmptyImagePath.Substring(dotIndex)}"); } var size = str_size.Split('x'); var width = int.TryParse(size[0], out var w) ? w : 0; var height = int.TryParse(size[1], out var h) ? h : 0; if (width == 0 && height == 0) { return(null); } var image = Image.FromFile(imageSourcePath); if (width > 0 && height > 0) { image = image.Resize(width, height); if (!string.IsNullOrEmpty(str_color)) { var r = str_color.Substring(0, 2).FromRadix16(); var g = str_color.Substring(2, 2).FromRadix16(); var b = str_color.Substring(4, 2).FromRadix16(); var tmp = new Bitmap(width, height); tmp.Clear(Color.FromArgb(r, g, b)); tmp.Combine((new Point((width - image.Width) / 2, (height - image.Height) / 2), new Size(image.Width, image.Height), image)); image = tmp; } } else if (width == 0) { image = image.Resize(null, height); } else if (height == 0) { image = image.Resize(width, null); } var imageDestinationPath = Path.Combine(options.RootDirectory, path.Replace('/', Path.DirectorySeparatorChar)); using (image) image.CompressSave(imageDestinationPath, options.CompressFlag); return(path); }
public HttpResponseMessage LoadDocumentPage(PostedDataWrapper postedData) { try { // get/set parameters string documentGuid = postedData.guid; int pageNumber = postedData.page; bool htmlMode = postedData.htmlMode; string password = postedData.password; LoadedPageWrapper loadedPage = new LoadedPageWrapper(); string angle = "0"; // set options if (htmlMode) { HtmlOptions htmlOptions = new HtmlOptions(); htmlOptions.PageNumber = pageNumber; htmlOptions.CountPagesToRender = 1; htmlOptions.IsResourcesEmbedded = true; // set password for protected document if (!String.IsNullOrEmpty(password)) { htmlOptions.Password = password; } // get page HTML loadedPage.pageHtml = viewerHtmlHandler.GetPages(documentGuid, htmlOptions)[0].HtmlContent; // get page rotation angle angle = viewerHtmlHandler.GetDocumentInfo(documentGuid).Pages[pageNumber - 1].Angle.ToString(); } else { ImageOptions imageOptions = new ImageOptions(); imageOptions.PageNumber = pageNumber; imageOptions.CountPagesToRender = 1; // set password for protected document if (!String.IsNullOrEmpty(password)) { imageOptions.Password = password; } byte[] bytes; using (var memoryStream = new MemoryStream()) { viewerImageHandler.GetPages(documentGuid, imageOptions)[0].Stream.CopyTo(memoryStream); bytes = memoryStream.ToArray(); } string incodedImage = Convert.ToBase64String(bytes); loadedPage.pageImage = incodedImage; // get page rotation angle angle = viewerImageHandler.GetDocumentInfo(documentGuid).Pages[pageNumber - 1].Angle.ToString(); } loadedPage.angle = angle; // return loaded page object return(Request.CreateResponse(HttpStatusCode.OK, loadedPage)); } catch (Exception ex) { // set exception message ErrorMsgWrapper errorMsgWrapper = new ErrorMsgWrapper(); errorMsgWrapper.message = ex.Message; errorMsgWrapper.exception = ex; return(Request.CreateResponse(HttpStatusCode.OK, errorMsgWrapper)); } }
/// <summary> /// Gets an image url that can be used to download an image from the api /// </summary> /// <param name="year">The year.</param> /// <param name="options">The options.</param> /// <returns>System.String.</returns> public string GetYearImageUrl(int year, ImageOptions options) { var url = "Years/" + year + "/Images/" + options.ImageType; return(GetImageUrl(url, options, new QueryStringDictionary())); }