public async Task <IMediaModel> GenerateThumbImageFromVideo(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel) { IMediaModel returnValue = new MediaModel(); await Task.Run(() => { string outFilePath = System.IO.Path.Combine(argCurrentDataFolder.FullName, argNewMediaModel.OriginalFilePath); MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.SetDataSource(argExistingMediaModel.MediaStorageFilePath); Bitmap bitmap = retriever.GetFrameAtTime(1000); // try at 1 second as this is often a more flattering image if (bitmap != null) { //Save the bitmap var outStream = new FileStream(outFilePath, FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outStream); outStream.Close(); returnValue = argNewMediaModel; } }); return(returnValue); }
public bool FixSingleMediaFile(IMediaModel argMediaModel) { try { if (argMediaModel.IsOriginalFilePathValid) { //_CL.LogVariable("tt.OriginalFilePath", argMediaModel.OriginalFilePath); // //_CL.LogVariable("localMediaFolder.path", DataStore.Instance.AD.CurrentDataFolder.FullName); // //_CL.LogVariable("path", DataStore.Instance.AD.CurrentDataFolder.FullName + "\\" + argMediaModel.OriginalFilePath); DataStore.Instance.DS.MediaData[argMediaModel.HLinkKey.Value].MediaStorageFile = new FileInfoEx(argFileName: argMediaModel.OriginalFilePath, argUseCurrentDataFolder: true); } } catch (FileNotFoundException ex) { _commonNotifications.NotifyError(new ErrorInfo("FixSingleMediaFile", "File not found while loading media.Has the GRAMPS database been verified?") { { "Message", ex.Message }, { "Filename", argMediaModel.OriginalFilePath } }); _commonNotifications.NotifyException("Trying to add media file pointer", ex); } catch (Exception ex) { CommonLocalSettings.DataSerialised = false; _commonNotifications.NotifyException("Trying to add media file pointer", ex); throw; } return(false); }
/// <summary> /// Compares the specified a. /// </summary> /// <param name="argFirstMediaModel"> /// a. /// </param> /// <param name="argSecondMediaModel"> /// The b. /// </param> /// <returns> /// </returns> public new int Compare(object argFirstMediaModel, object argSecondMediaModel) { if (argFirstMediaModel is null) { throw new ArgumentNullException(nameof(argFirstMediaModel)); } if (argSecondMediaModel is null) { throw new ArgumentNullException(nameof(argSecondMediaModel)); } IMediaModel firstMediaModel = (MediaModel)argFirstMediaModel; IMediaModel secondMediaModel = (MediaModel)argSecondMediaModel; // Compare on date first int testFlag = DateTime.Compare(firstMediaModel.GDateValue.SortDate, secondMediaModel.GDateValue.SortDate); // If the same then on Description. Usual if there is no Date if (testFlag.Equals(0)) { testFlag = string.Compare(firstMediaModel.GDescription, secondMediaModel.GDescription, StringComparison.CurrentCulture); } return(testFlag); }
public async Task <ItemGlyph> GetThumbImageFromVideo(MediaModel argMediaModel) { ItemGlyph returnItemGlyph = argMediaModel.ModelItemGlyph; IMediaModel newMediaModel = UtilCreateNewMediaObject(argMediaModel, "~imagevideo", ".jpg"); IMediaModel videoImage; // Check if new image file already exists IMediaModel fileExists = DV.MediaDV.GetModelFromHLinkKey(newMediaModel.HLinkKey); if ((!fileExists.Valid) && argMediaModel.IsMediaStorageFileValid) { // check if we can get an image for the video videoImage = await _iocPlatformSpecific.GenerateThumbImageFromVideo(DataStore.Instance.AD.CurrentDataFolder.Value, argMediaModel, newMediaModel); returnItemGlyph = UtilSaveNewMediaObject(returnItemGlyph, videoImage, IconFont.FileArchive); } else { ErrorInfo t = UtilGetPostGlyphErrorInfo("File not found when trying to create image from video file", argMediaModel); _commonNotifications.NotifyError(t); } return(returnItemGlyph); }
/// <summary> /// Generates the tile binding wide. /// </summary> /// <param name="media"> /// The media. /// </param> /// <returns> /// </returns> private static TileBinding GenerateTileBindingWide(IMediaModel media) { return(new TileBinding() { Branding = TileBranding.NameAndLogo, ContentId = media.HLinkKey.Value, DisplayName = Package.Current.DisplayName, Content = new TileBindingContentAdaptive() { Children = { new AdaptiveGroup() { Children = { new AdaptiveSubgroup() { HintWeight = 1, Children = { new AdaptiveText() { Text = media.GDescription, HintStyle = AdaptiveTextStyle.Caption, HintWrap = true, HintMaxLines = 5, }, new AdaptiveText() { Text = media.GDateValue.ShortDateOrEmpty, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true, HintMaxLines = 1, }, }, }, new AdaptiveSubgroup() { HintWeight = 2, Children = { new AdaptiveImage() { Source = media.MediaStorageFilePath, }, }, }, }, }, }, }, }); }
public async static Task <bool> FixSingleMediaFile(IMediaModel argMediaModel) { try { if (argMediaModel.IsOriginalFilePathValid) { //_CL.LogVariable("tt.OriginalFilePath", argMediaModel.OriginalFilePath); // //_CL.LogVariable("localMediaFolder.path", DataStore.AD.CurrentDataFolder.FullName); // //_CL.LogVariable("path", DataStore.AD.CurrentDataFolder.FullName + "\\" + argMediaModel.OriginalFilePath); DataStore.DS.MediaData[argMediaModel.HLinkKey].MediaStorageFile = StoreFolder.FolderGetFile(DataStore.AD.CurrentDataFolder, argMediaModel.OriginalFilePath); } } catch (FileNotFoundException ex) { DataStore.CN.NotifyError("File (" + argMediaModel.OriginalFilePath + ") not found while loading media. Has the GRAMPS database been verified ? " + ex.ToString()); DataStore.CN.NotifyException("Trying to add media file pointer", ex); } catch (Exception ex) { CommonLocalSettings.DataSerialised = false; DataStore.CN.NotifyException("Trying to add media file pointer", ex); await DataStore.CN.MajorStatusDelete().ConfigureAwait(false); throw; } return(false); }
/// <summary> /// Generates the tile binding. /// </summary> /// <param name="media"> /// The media. /// </param> /// <returns> /// </returns> private static TileBinding GenerateTileBindingMedium(IMediaModel media) { return(new TileBinding() { Branding = TileBranding.NameAndLogo, Content = new TileBindingContentAdaptive() { Children = { new AdaptiveText() { Text = media.GDescription, HintStyle = AdaptiveTextStyle.Caption, HintWrap = true, HintMaxLines = 3, }, }, BackgroundImage = new TileBackgroundImage() { Source = media.MediaStorageFilePath, HintOverlay = 60, }, }, ContentId = media.HLinkKey.Value, DisplayName = Package.Current.DisplayName, }); }
public async Task <ItemGlyph> GetThumbImageFromPDF(MediaModel argMediaModel) { ItemGlyph returnItemGlyph = argMediaModel.ModelItemGlyph; IMediaModel newMediaModel = UtilCreateNewMediaObject(argMediaModel, "~imagepdf", ".jpg"); // TODO Having an issue where Gramps XML content type is not always correct if (argMediaModel.MediaStorageFile.FInfo.Extension != ".pdf") { _commonNotifications.DataLogEntryAdd($"??? {argMediaModel.Id} Inconsistant File Extension ({argMediaModel.MediaStorageFile.FInfo.Extension}) and MIME type ({argMediaModel.FileMimeType}/{argMediaModel.FileMimeSubType})"); return(argMediaModel.ModelItemGlyph); } IMediaModel pdfimage; // Check if new pdf image file already exists IMediaModel fileExists = DV.MediaDV.GetModelFromHLinkKey(newMediaModel.HLinkKey); if ((!fileExists.Valid) && (argMediaModel.IsMediaStorageFileValid)) { // check if we can get an image for the first page of the PDF pdfimage = await _iocPlatformSpecific.GenerateThumbImageFromPDF(DataStore.Instance.AD.CurrentDataFolder.Value, argMediaModel, newMediaModel); returnItemGlyph = UtilSaveNewMediaObject(returnItemGlyph, pdfimage, IconFont.FilePdf); } else { ErrorInfo t = UtilGetPostGlyphErrorInfo("File not found when trying to create image from PDF file", argMediaModel); _commonNotifications.NotifyError(t); } return(returnItemGlyph); }
private void OnTapGestureRecognizerTapped(object sender, EventArgs args) { Frame theFrame = sender as Frame; IMediaModel theModel = (theFrame.BindingContext as MediaDetailViewModel).CurrentMediaObject; OpenFileRequest t = new OpenFileRequest(theModel.GDescription, new ReadOnlyFile(theModel.MediaStorageFilePath)); Launcher.OpenAsync(t); }
private void ShowImage(IMediaModel argMediaModel) { if (argMediaModel.IsMediaStorageFileValid) { try { if (string.IsNullOrEmpty(argMediaModel.MediaStorageFilePath)) { ErrorInfo t = new ErrorInfo("The image file path is null") { { "Id", argMediaModel.Id } }; App.Current.Services.GetService <IErrorNotifications>().NotifyError(t); return; } // Input valid so start work CachedImage newMediaControl = new CachedImage { Source = argMediaModel.HLink.DeRef.MediaStorageFilePath, Margin = 3, Aspect = Aspect.AspectFit, BackgroundColor = Color.Transparent, CacheType = FFImageLoading.Cache.CacheType.All, DownsampleToViewSize = true, // HeightRequest = 100, // "{Binding MediaDetailImageHeight, // Source={x:Static common:CardSizes.Current}, Mode=OneWay}" HorizontalOptions = LayoutOptions.FillAndExpand, IsVisible = true, ErrorPlaceholder = "ic_launcher.png", LoadingPlaceholder = "ic_launcher.png", RetryCount = 3, RetryDelay = 1000 }; newMediaControl.Error += NewMediaControl_Error; HLinkVisualDisplayRoot.Children.Clear(); HLinkVisualDisplayRoot.Children.Add(newMediaControl); } catch (Exception ex) { ErrorInfo argDetail = new ErrorInfo { { "Type", "Image" }, { "Media Model Id", argMediaModel.Id }, { "Media Model Path", argMediaModel.MediaStorageFilePath }, }; App.Current.Services.GetService <IErrorNotifications>().NotifyException("HLinkVisualDisplay", ex, argExtraItems: argDetail); throw; } } }
public static IMediaModel SetHomeImage(IMediaModel argModel) { Contract.Requires(argModel != null); // Setup HomeImage argModel.HomeImageHLink.HLinkKey = argModel.HLinkKey; switch (argModel.FileMimeType) { case "application": { switch (argModel.FileMimeSubType) { case "pdf": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = CommonFontNamesFAS.FilePdf; break; } case "x-zip-compressed": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = CommonFontNamesFAS.FileArchive; break; } case "zip": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = CommonFontNamesFAS.FileArchive; break; } } break; } case "image": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.ThumbNail; argModel.HomeImageHLink.HomeSymbol = CommonFontNamesFAS.FileImage; break; } case "video": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = CommonFontNamesFAS.FileVideo; break; } } return(argModel); }
private IMediaModel UtilCreateNewMediaObject(MediaModel argSourceMediaModel, string argNewMediaHLPrefix, string argNewMediaFileExtension) { IMediaModel newMediaModel = argSourceMediaModel.Clone(); newMediaModel.InternalMediaFileOriginalHLink = argSourceMediaModel.HLinkKey; newMediaModel.HLinkKey.Value = argSourceMediaModel.HLinkKey.Value + argNewMediaHLPrefix; newMediaModel.OriginalFilePath = System.IO.Path.Combine(Constants.DirectoryImageCache, newMediaModel.HLinkKey.Value + argNewMediaFileExtension); return(newMediaModel); }
public static IMediaModel SetHomeImage(IMediaModel argModel) { // Setup HomeImage argModel.HomeImageHLink.HLinkKey = argModel.HLinkKey; switch (argModel.FileMimeType) { case "application": { switch (argModel.FileMimeSubType) { case "pdf": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = IconFont.FilePdf; break; } case "x-zip-compressed": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = IconFont.ZipBox; break; } case "zip": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = IconFont.ZipBox; break; } } break; } case "image": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.ThumbNail; argModel.HomeImageHLink.HomeSymbol = IconFont.Image; break; } case "video": { argModel.HomeImageHLink.HomeImageType = CommonEnums.HomeImageType.Symbol; argModel.HomeImageHLink.HomeSymbol = IconFont.Video; break; } } return(argModel); }
/// <summary> /// Converts from media model. /// </summary> /// <param name="argMediaModel"> /// The argument media model. /// </param> /// <exception cref="ArgumentNullException"> /// argMediaModel /// </exception> public void ConvertFromMediaModel(IMediaModel argMediaModel) { if (argMediaModel is null) { throw new ArgumentNullException(nameof(argMediaModel)); } // Copy fields GPriv = argMediaModel.Priv; HLinkKey = argMediaModel.HLinkKey; HomeImageType = CommonEnums.HomeImageType.ThumbNail; }
public ItemGlyph GetThumbImageFromZip(MediaModel argMediaModel) { try { ItemGlyph returnItemGlyph = argMediaModel.ModelItemGlyph; IMediaModel newMediaModel = UtilCreateNewMediaObject(argMediaModel, "~zipimage", ".jpg"); // TODO Having an issue where Gramps XML content type is not always correct if (argMediaModel.MediaStorageFile.FInfo.Extension != ".zip") { _commonNotifications.DataLogEntryAdd($"??? {argMediaModel.Id} Inconsistant File Extension ({argMediaModel.MediaStorageFile.FInfo.Extension}) and MIME type ({argMediaModel.FileMimeType}/{argMediaModel.FileMimeSubType})"); return(argMediaModel.ModelItemGlyph); } IMediaModel zipimage; // Check if new zip image file already exists IMediaModel fileExists = DV.MediaDV.GetModelFromHLinkKey(newMediaModel.HLinkKey); if ((!fileExists.Valid) && (argMediaModel.IsMediaStorageFileValid)) { // check if we can get an image for the first page of the PDF zipimage = StoreFile.ExtractZipFileFirstImage(DataStore.Instance.AD.CurrentDataFolder.Value, argMediaModel, newMediaModel); returnItemGlyph = UtilSaveNewMediaObject(returnItemGlyph, zipimage, IconFont.FileArchive); } else { ErrorInfo t = UtilGetPostGlyphErrorInfo("File not found when trying to create image from PDF file", argMediaModel); _commonNotifications.NotifyError(t); } return(returnItemGlyph); } catch (System.Exception ex) { ErrorInfo t = new ErrorInfo("Directory not found when trying to create image from PDF file") { { "Original ID", argMediaModel.Id }, { "Original File", argMediaModel.MediaStorageFilePath }, { "Clipped Id", argMediaModel.Id }, { "New path", "pdfimage" } }; App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t); return(new ItemGlyph()); } }
private void ShowImage(IMediaModel argMediaModel) { if (string.IsNullOrEmpty(argMediaModel.MediaStorageFilePath)) { DataStore.CN.NotifyError("The media file path is null for Id:" + argMediaModel.Id); return; } // Input valid so start work daSymbol.IsVisible = false; daImage.IsVisible = true; this.daImage.DownsampleToViewSize = true; this.daImage.Source = argMediaModel.MediaStorageFilePath; }
private void ShowMedia(IMediaModel argMediaModel) { if (argMediaModel.IsMediaStorageFileValid) { try { if (string.IsNullOrEmpty(argMediaModel.MediaStorageFilePath)) { ErrorInfo t = new ErrorInfo("The media file path is null") { { "Id", argMediaModel.Id } }; App.Current.Services.GetService <IErrorNotifications>().NotifyError(t); return; } // Input valid so start work MediaElement newMediaControl = new MediaElement { Aspect = Aspect.AspectFit, AutoPlay = false, ShowsPlaybackControls = true, BackgroundColor = Color.Transparent, HorizontalOptions = LayoutOptions.FillAndExpand, IsVisible = true, Margin = 3, Source = argMediaModel.HLink.DeRef.MediaStorageFilePath, VerticalOptions = LayoutOptions.FillAndExpand, }; HLinkVisualDisplayRoot.Children.Clear(); HLinkVisualDisplayRoot.Children.Add(newMediaControl); } catch (Exception ex) { ErrorInfo argDetail = new ErrorInfo { { "Type", "Image" }, { "Media Model Id", argMediaModel.Id }, { "Media Model Path", argMediaModel.MediaStorageFilePath }, }; App.Current.Services.GetService <IErrorNotifications>().NotifyException("HLinkVisualDisplay", ex, argExtraItems: argDetail); throw; } } }
/// <summary> /// Handles navigation inwards and gets the media model parameter. /// </summary> /// <returns> /// </returns> public override void HandleViewDataLoadEvent() { BaseCL.RoutineEntry("MediaDetailViewModel OnNavigatedTo"); CurrentHLinkMedia = CommonRoutines.GetHLinkParameter <HLinkMediaModel>((BaseParamsHLink)); // For cropped or internal media then show the original image IMediaModel tt = CurrentHLinkMedia.DeRef; if (tt.IsInternalMediaFile) { CurrentHLinkMedia = DV.MediaDV.GetModelFromHLinkKey(tt.InternalMediaFileOriginalHLink).HLink; } if (!(CurrentHLinkMedia is null)) { CurrentMediaObject = CurrentHLinkMedia.DeRef as MediaModel; if (!(CurrentMediaObject is null)) { BaseModelBase = CurrentMediaObject; BaseTitleIcon = Constants.IconMedia; MediaCard = CurrentMediaObject.ModelItemGlyph.ImageHLinkMediaModel; // Get basic details BaseDetail.Add(new CardListLineCollection("Media Detail") { new CardListLine("File Description:", CurrentMediaObject.GDescription), new CardListLine("File Mime Type:", CurrentMediaObject.FileMimeType), new CardListLine("File Content Type:", CurrentMediaObject.FileContentType), new CardListLine("File Mime SubType:", CurrentMediaObject.FileMimeSubType), new CardListLine("OriginalFilePath:", CurrentMediaObject.OriginalFilePath), }); // Get date card BaseDetail.Add(CurrentMediaObject.GDateValue.AsHLink("Media Date")); // Add standard details MediaModel t = CurrentMediaObject as MediaModel; BaseDetail.Add(DV.MediaDV.GetModelInfoFormatted(t)); } BaseCL.RoutineExit("MediaDetailViewModel OnNavigatedTo"); } }
/// <summary> /// Generates the content of the tile. /// </summary> /// <param name="argMedia"> /// The media. /// </param> /// <returns> /// </returns> private static TileContent GenerateTileContent(IMediaModel argMedia) { if (argMedia != null) { return(new TileContent() { Visual = new TileVisual() { TileMedium = GenerateTileBindingMedium(argMedia), TileWide = GenerateTileBindingWide(argMedia), TileLarge = GenerateTileBindingLarge(argMedia), }, }); } else { return(new TileContent()); } }
private void MediaImageFull_BindingContextChanged(object sender, EventArgs e) { Contract.Assert(sender != null); MediaImageFull mifModel = (sender as MediaImageFull); // Hide if not valid if ((!(mifModel.BindingContext is HLinkMediaModel argHLinkMediaModel)) || (!argHLinkMediaModel.Valid)) { mifModel.IsVisible = false; return; } if (argHLinkMediaModel == mifModel.CurrentHLinkMediaModel) { return; } IMediaModel t = argHLinkMediaModel.DeRef; if ((t.IsMediaStorageFileValid) && (t.IsImage)) { try { mifModel.daImage.Source = t.MediaStorageFilePath; mifModel.IsVisible = true; CurrentHLinkMediaModel = argHLinkMediaModel; return; } catch (Exception ex) { App.Current.Services.GetService <IErrorNotifications>().NotifyException("Exception in MediaImageFull control", ex); throw; } } // Nothing to display so hide mifModel.IsVisible = false; }
private static void HandleVMPropertyChanged(BindableObject bindable, object oldValue, object newValue) { MediaImageFull mifModel = (bindable as MediaImageFull); HLinkHomeImageModel argHLinkMediaModel = newValue as HLinkHomeImageModel; if (argHLinkMediaModel == mifModel.HLinkMediaModel) { return; } mifModel.HLinkMediaModel = argHLinkMediaModel; if (!(argHLinkMediaModel is null) && (argHLinkMediaModel.Valid)) { IMediaModel t = argHLinkMediaModel.DeRef; if ((t.IsMediaStorageFileValid) && (t.IsMediaFile)) { try { mifModel.daImage.Source = t.MediaStorageFilePath; var tt = mifModel.daImage.Source; mifModel.IsVisible = true; // TODO cleanup code so does nto use bindignContext if possible mifModel.BindingContext = argHLinkMediaModel; return; } catch (Exception ex) { DataStore.CN.NotifyException("Exception in MediaImageFull control", ex); throw; } } } // Nothing to display so hide mifModel.IsVisible = false; }
private ItemGlyph UtilSaveNewMediaObject(ItemGlyph argNewGlyph, IMediaModel argNewMediaModel, string argDefaultSymbol) { try { // Save new MediaObject if (argNewMediaModel.Valid) { argNewMediaModel.ModelItemGlyph.ImageType = CommonEnums.HLinkGlyphType.Image; argNewMediaModel.IsInternalMediaFile = true; // Do not show in media list as it is internal argNewMediaModel.MediaStorageFile = new FileInfoEx(argUseCurrentDataFolder: true, argFileName: argNewMediaModel.OriginalFilePath); addLater.Add(argNewMediaModel); argNewGlyph.ImageType = CommonEnums.HLinkGlyphType.Image; argNewGlyph.ImageHLink = argNewMediaModel.HLinkKey; return(argNewGlyph); } // Else argNewGlyph.ImageType = CommonEnums.HLinkGlyphType.Symbol; argNewGlyph.ImageSymbol = argDefaultSymbol; return(argNewGlyph); } catch (System.Exception ex) { ErrorInfo t = new ErrorInfo("Directory not found when trying to create image from PDF file") { { "Original ID", argNewMediaModel.Id }, { "Original File", argNewMediaModel.MediaStorageFilePath }, { "Clipped Id", argNewMediaModel.Id }, { "New path", "pdfimage" } }; App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t); return(new ItemGlyph()); } }
/// <summary> /// Generates the tile binding large. /// </summary> /// <param name="media"> /// The media. /// </param> /// <returns> /// </returns> private static TileBinding GenerateTileBindingLarge(IMediaModel media) { return(new TileBinding() { Branding = TileBranding.NameAndLogo, Content = new TileBindingContentAdaptive() { TextStacking = TileTextStacking.Bottom, Children = { new AdaptiveText() { Text = media.GDescription, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true, HintMaxLines = 6, }, new AdaptiveText() { Text = media.GDateValue.ShortDateOrEmpty, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true, HintMaxLines = 1, }, }, BackgroundImage = new TileBackgroundImage() { Source = media.MediaStorageFilePath, HintOverlay = 30, }, }, ContentId = media.HLinkKey.Value, DisplayName = Package.Current.DisplayName, }); }
/// <summary> /// Generates the content of the tile. /// </summary> /// <param name="media"> /// The media. /// </param> /// <returns> /// </returns> private static TileContent GenerateTileContent(IMediaModel media) { if (media != null) { // TODO until proper async image loading fixed //media.LoadImage(); return(new TileContent() { Visual = new TileVisual() { TileMedium = GenerateTileBindingMedium(media), TileWide = GenerateTileBindingWide(media), TileLarge = GenerateTileBindingLarge(media), }, }); } else { return(new TileContent()); } }
private static bool TryParseIntranetCreatorId(IMediaModel s, out Guid intranetCreatorId) { intranetCreatorId = Guid.Empty; return(!string.IsNullOrWhiteSpace(((IGenericPropertiesComposition)s).GenericProperties.IntranetUserId) && Guid.TryParse(((IGenericPropertiesComposition)s).GenericProperties.IntranetUserId, out intranetCreatorId)); }
private async Task <HLinkMediaModel> CreateClippedMediaModel(HLinkMediaModel argHLinkLoadImageModel) { if (argHLinkLoadImageModel is null) { throw new ArgumentNullException(nameof(argHLinkLoadImageModel)); } if (!argHLinkLoadImageModel.DeRef.Valid) { throw new ArgumentException("CreateClippedMediaModel argument is invalid", nameof(argHLinkLoadImageModel)); } IMediaModel returnMediaModel = await MainThread.InvokeOnMainThreadAsync(() => { // TODO cleanup code. Multiple copies of things in use IMediaModel theMediaModel = argHLinkLoadImageModel.DeRef; SKBitmap resourceBitmap = new SKBitmap(); IMediaModel newMediaModel = new MediaModel(); HLinkKey newHLinkKey = new HLinkKey($"{argHLinkLoadImageModel.HLinkKey.Value}-{argHLinkLoadImageModel.GCorner1X}{argHLinkLoadImageModel.GCorner1Y}{argHLinkLoadImageModel.GCorner2X}{argHLinkLoadImageModel.GCorner2Y}"); string outFileName = $"{newHLinkKey.Value}{"~crop"}.png"; if (newHLinkKey.Value == "_c5132553a185c9c51d8-35415065") { } Debug.WriteLine(newHLinkKey.Value); string outFilePath = Path.Combine(DataStore.Instance.AD.CurrentImageAssetsFolder.Path, outFileName); Debug.WriteLine(argHLinkLoadImageModel.DeRef.MediaStorageFilePath); // Check if already exists IMediaModel fileExists = DV.MediaDV.GetModelFromHLinkKey(newHLinkKey); if ((!fileExists.Valid) && theMediaModel.IsMediaStorageFileValid) { // Needs clipping using (StreamReader stream = new StreamReader(theMediaModel.MediaStorageFilePath)) { //resourceBitmap = SKBitmap.Decode(stream.BaseStream); // TODO See https://github.com/mono/SkiaSharp/issues/1621 SKImage img = SKImage.FromEncodedData(stream.BaseStream); resourceBitmap = SKBitmap.FromImage(img); } // Check for too large a bitmap //Debug.WriteLine("Image ResourceBitmap size: " + resourceBitmap.ByteCount); if (resourceBitmap.ByteCount > int.MaxValue - 1000) { // TODO Handle this better. Perhaps resize? Delete for now resourceBitmap = new SKBitmap(); } float crleft = (float)(argHLinkLoadImageModel.GCorner1X / 100d * theMediaModel.MetaDataWidth); float crright = (float)(argHLinkLoadImageModel.GCorner2X / 100d * theMediaModel.MetaDataWidth); float crtop = (float)(argHLinkLoadImageModel.GCorner1Y / 100d * theMediaModel.MetaDataHeight); float crbottom = (float)(argHLinkLoadImageModel.GCorner2Y / 100d * theMediaModel.MetaDataHeight); SKRect cropRect = new SKRect(crleft, crtop, crright, crbottom); SKBitmap croppedBitmap = new SKBitmap( (int)cropRect.Width, (int)cropRect.Height ); SKRect dest = new SKRect( 0, 0, cropRect.Width, cropRect.Height ); SKRect source = new SKRect( cropRect.Left, cropRect.Top, cropRect.Right, cropRect.Bottom); using (SKCanvas canvas = new SKCanvas(croppedBitmap)) { canvas.DrawBitmap(resourceBitmap, source, dest); } // create an image COPY SKImage image = SKImage.FromBitmap(croppedBitmap); // encode the image (defaults to PNG) SKData encoded = image.Encode(); // get a stream over the encoded data using (Stream stream = File.Open(outFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) { encoded.SaveTo(stream); } croppedBitmap.Dispose(); // ------------ Save new MediaObject newMediaModel = theMediaModel.Clone(); newMediaModel.HLinkKey = newHLinkKey; newMediaModel.OriginalFilePath = outFilePath; newMediaModel.MediaStorageFile = new FileInfoEx(argFileName: outFilePath); newMediaModel.IsInternalMediaFile = true; newMediaModel.InternalMediaFileOriginalHLink = theMediaModel.HLinkKey; newMediaModel.MetaDataHeight = cropRect.Height; newMediaModel.MetaDataWidth = cropRect.Width; // newMediaModel = SetHomeImage(newMediaModel); DataStore.Instance.DS.MediaData.Add((MediaModel)newMediaModel); } else { ErrorInfo t = new ErrorInfo("File not found when Region specified in ClipMedia") { { "Original ID", theMediaModel.Id }, { "Original File", theMediaModel.MediaStorageFilePath }, { "Clipped Id", argHLinkLoadImageModel.DeRef.Id } }; _iocCommonNotifications.NotifyError(t); } resourceBitmap.Dispose(); return(newMediaModel); }).ConfigureAwait(false); return(returnMediaModel.HLink); }
async Task <IMediaModel> IPlatformSpecific.GenerateThumbImageFromPDF(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel) { //MemoryStream stream = new MemoryStream(); //// Create memory stream from file stream. //fileStream.CopyTo(stream); //// Create data provider from bytes. //CGDataProvider provider = new CGDataProvider(stream.ToArray()); //try //{ // //Load a PDF file. // m_pdfDcument = new CGPDFDocument(provider); //} //catch (Exception) //{ //} ////Get PDF's page and convert as image. //using (CGPDFPage pdfPage = m_pdfDcument.GetPage(2)) //{ // //initialise image context. // UIGraphics.BeginImageContext(pdfPage.GetBoxRect(CGPDFBox.Media).Size); // // get current context. // CGContext context = UIGraphics.GetCurrentContext(); // context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f); // // Gets page's bounds. // CGRect bounds = new CGRect(pdfPage.GetBoxRect(CGPDFBox.Media).X, pdfPage.GetBoxRect(CGPDFBox.Media).Y, pdfPage.GetBoxRect(CGPDFBox.Media).Width, pdfPage.GetBoxRect(CGPDFBox.Media).Height); // if (pdfPage != null) // { // context.FillRect(bounds); // context.TranslateCTM(0, bounds.Height); // context.ScaleCTM(1.0f, -1.0f); // context.ConcatCTM(pdfPage.GetDrawingTransform(CGPDFBox.Crop, bounds, 0, true)); // context.SetRenderingIntent(CGColorRenderingIntent.Default); // context.InterpolationQuality = CGInterpolationQuality.Default; // // Draw PDF page in the context. // context.DrawPDFPage(pdfPage); // // Get image from current context. // pdfImage = UIGraphics.GetImageFromCurrentImageContext(); // UIGraphics.EndImageContext(); // } //} //// Get bytes from UIImage object. //using (var imageData = pdfImage.AsPNG()) //{ // imageBytes = new byte[imageData.Length]; // System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, imageBytes, 0, Convert.ToInt32(imageData.Length)); // //return bytes; //} ////Create image from bytes. //imageStream = new MemoryStream(imageBytes); ////Save the image. It is a custom method to save the image //Save("PDFtoImage.png", "image/png", imageStream); return(new MediaModel()); }
/// <summary> /// Extracts the first image from a zip file. /// </summary> /// <param name="archiveFilenameIn"> /// The archive filename in. /// </param> /// <param name="outFolder"> /// The out folder. /// </param> public static IMediaModel ExtractZipFileFirstImage(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel) { ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { FileStream fs = File.OpenRead(argExistingMediaModel.MediaStorageFilePath); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; // Ignore directories } string entryFileName = zipEntry.Name; // check for image TODO do proper mimetype mapping. See https://github.com/samuelneff/MimeTypeMap if (SharedSharp.Common.SharedSharpGeneral.MimeMimeTypeGet(CommonRoutines.MimeFileContentTypeGet(Path.GetExtension(zipEntry.Name))) != "image") { continue; } else { // set extension argNewMediaModel.OriginalFilePath = Path.ChangeExtension(argNewMediaModel.OriginalFilePath, Path.GetExtension(zipEntry.Name)); // Unzip the file byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Unzip file in buffered chunks. This is just as fast as unpacking to a // buffer the full size of the file, but does not waste memory. The "using" // will close the stream even if an exception occurs. using (FileStream streamWriter = File.Create(System.IO.Path.Combine(argCurrentDataFolder.FullName, argNewMediaModel.OriginalFilePath))) { StreamUtils.Copy(zipStream, streamWriter, buffer); } // exit early return(argNewMediaModel); } } fs.Close(); // Exit return(new MediaModel()); } catch (DirectoryNotFoundException ex) { ErrorInfo t = new ErrorInfo("Directory not found when trying to create image from ZIP file") { { "Original ID", argExistingMediaModel.Id }, { "Original File", argExistingMediaModel.MediaStorageFilePath }, { "Clipped Id", argNewMediaModel.Id }, { "New path", "pdfimage" } }; App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t); return(new MediaModel()); } catch (Exception ex) { ErrorInfo t = new ErrorInfo("Exception when trying to create image from ZIP file") { { "Original ID", argExistingMediaModel.Id }, { "Original File", argExistingMediaModel.MediaStorageFilePath }, { "Clipped Id", argNewMediaModel.Id } }; App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t); return(new MediaModel()); } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } }
public static async Task <HLinkMediaModel> CreateClippedMediaModel(HLinkLoadImageModel argHLinkLoadImageModel) { if (argHLinkLoadImageModel is null) { throw new ArgumentNullException(nameof(argHLinkLoadImageModel)); } if (!argHLinkLoadImageModel.DeRef.Valid) { throw new ArgumentException("CreateClippedMediaModel argument is invalid", nameof(argHLinkLoadImageModel)); } IMediaModel returnMediaModel = await MainThread.InvokeOnMainThreadAsync(() => { // TODO cleanup code. Multiple copies of things in use IMediaModel theMediaModel = argHLinkLoadImageModel.DeRef; SKBitmap resourceBitmap = new SKBitmap(); IMediaModel newMediaModel = new MediaModel(); string newHLinkKey = argHLinkLoadImageModel.HLinkKey + "-" + argHLinkLoadImageModel.GCorner1X + argHLinkLoadImageModel.GCorner1Y + argHLinkLoadImageModel.GCorner2X + argHLinkLoadImageModel.GCorner2Y; string outFileName = Path.Combine("Cropped", newHLinkKey + ".png"); string outFilePath = Path.Combine(DataStore.AD.CurrentDataFolder.FullName, outFileName); Debug.WriteLine(argHLinkLoadImageModel.DeRef.MediaStorageFilePath); // Check if already exists IMediaModel fileExists = DV.MediaDV.GetModelFromHLinkString(newHLinkKey); if ((!fileExists.Valid) && (theMediaModel.IsMediaStorageFileValid)) { // Needs clipping using (StreamReader stream = new StreamReader(theMediaModel.MediaStorageFilePath)) { resourceBitmap = SKBitmap.Decode(stream.BaseStream); } // Check for too large a bitmap Debug.WriteLine("Image ResourceBitmap size: " + resourceBitmap.ByteCount); if (resourceBitmap.ByteCount > int.MaxValue - 1000) { // TODO Handle this better. Perhaps resize? Delete for now resourceBitmap = new SKBitmap(); } float crleft = (float)(argHLinkLoadImageModel.GCorner1X / 100d * theMediaModel.MetaDataWidth); float crright = (float)(argHLinkLoadImageModel.GCorner2X / 100d * theMediaModel.MetaDataWidth); float crtop = (float)(argHLinkLoadImageModel.GCorner1Y / 100d * theMediaModel.MetaDataHeight); float crbottom = (float)(argHLinkLoadImageModel.GCorner2Y / 100d * theMediaModel.MetaDataHeight); SKRect cropRect = new SKRect(crleft, crtop, crright, crbottom); SKBitmap croppedBitmap = new SKBitmap( (int)cropRect.Width, (int)cropRect.Height ); SKRect dest = new SKRect( 0, 0, cropRect.Width, cropRect.Height ); SKRect source = new SKRect( cropRect.Left, cropRect.Top, cropRect.Right, cropRect.Bottom); using (SKCanvas canvas = new SKCanvas(croppedBitmap)) { canvas.DrawBitmap(resourceBitmap, source, dest); } // create an image COPY SKImage image = SKImage.FromBitmap(croppedBitmap); // encode the image (defaults to PNG) SKData encoded = image.Encode(); // get a stream over the encoded data using (Stream stream = File.Open(outFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) { encoded.SaveTo(stream); } croppedBitmap.Dispose(); // ------------ Save new MediaObject newMediaModel = theMediaModel.Copy(); newMediaModel.HLinkKey = newHLinkKey; newMediaModel.OriginalFilePath = outFileName; newMediaModel.MediaStorageFile = StoreFolder.FolderGetFile(DataStore.AD.CurrentDataFolder, outFileName);; newMediaModel.IsClippedFile = true; newMediaModel.MetaDataHeight = cropRect.Height; newMediaModel.MetaDataWidth = cropRect.Width; newMediaModel = SetHomeImage(newMediaModel); DataStore.DS.MediaData.Add((MediaModel)newMediaModel); } else { Dictionary <string, string> argErrorDetail = new Dictionary <string, string> { { "Original ID", theMediaModel.Id }, { "Original File", theMediaModel.MediaStorageFilePath }, { "Clipped Id", argHLinkLoadImageModel.DeRef.Id } }; DataStore.CN.NotifyError("File not found when Region specified in ClipMedia", argErrorDetail); } resourceBitmap.Dispose(); return(newMediaModel); }).ConfigureAwait(false); return(returnMediaModel.HLink); }
public async Task <IMediaModel> GenerateThumbImageFromVideo(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel) { //var asset = AVAsset.FromUrl(NSUrl.FromFilename(filePath)); //var imageGenerator = AVAssetImageGenerator.FromAsset(asset); //imageGenerator.AppliesPreferredTrackTransform = true; //var actualTime = asset.Duration; //CoreMedia.CMTime cmTime = new CoreMedia.CMTime(millisecond, 1000000); //NSError error; //var cgImage = imageGenerator.CopyCGImageAtTime(cmTime, out actualTime, out error); //return new UIImage(cgImage).AsJPEG().AsStream(); return(new MediaModel()); }