public Task<WithLoadingResult<Stream>> GetStream(string identifier, CancellationToken token) { try { var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); var result = WithLoadingResult.Encapsulate(Context.Assets.Open(identifier, Access.Streaming), LoadingResult.ApplicationBundle, imageInformation); return Task.FromResult(result); } catch (Java.IO.FileNotFoundException) { return Task.FromResult(WithLoadingResult.Encapsulate((Stream)null, LoadingResult.NotFound)); } catch (Java.IO.IOException) { return Task.FromResult(WithLoadingResult.Encapsulate((Stream)null, LoadingResult.NotFound)); } catch (FileNotFoundException) { return Task.FromResult(WithLoadingResult.Encapsulate((Stream)null, LoadingResult.NotFound)); } catch (IOException) { return Task.FromResult(WithLoadingResult.Encapsulate((Stream)null, LoadingResult.NotFound)); } }
public Task<WithLoadingResult<Stream>> GetStream(string identifier, CancellationToken token) { // Resource name is always without extension string resourceName = Path.GetFileNameWithoutExtension(identifier); int resourceId = 0; if (!_resourceIdentifiersCache.TryGetValue(resourceName, out resourceId)) { resourceId = Context.Resources.GetIdentifier(resourceName.ToLower(), "drawable", Context.PackageName); _resourceIdentifiersCache.TryAdd(resourceName.ToLower(), resourceId); } Stream stream = null; if (resourceId != 0) { stream = Context.Resources.OpenRawResource(resourceId); } else { return Task.FromResult(WithLoadingResult.Encapsulate((Stream)null, LoadingResult.NotFound)); } var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); var result = WithLoadingResult.Encapsulate(stream, LoadingResult.CompiledResource, imageInformation); return Task.FromResult(result); }
public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { StorageFile file = null; try { var filePath = Path.GetDirectoryName(identifier); if (!string.IsNullOrWhiteSpace(filePath)) { file = await StorageFile.GetFileFromPathAsync(identifier); } } catch (Exception) { } if (file != null) { var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(identifier); token.ThrowIfCancellationRequested(); var stream = await file.OpenStreamForReadAsync(); return new Tuple<Stream, LoadingResult, ImageInformation>(stream, LoadingResult.Disk, imageInformation); } throw new FileNotFoundException(identifier); }
public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { var imageInformation = new ImageInformation(); var stream = await parameters.Stream?.Invoke(token); return new Tuple<Stream, LoadingResult, ImageInformation>(stream, LoadingResult.Stream, imageInformation); }
public static Texture ConvertImageToTexture(Bitmap theImage, out int iWidth, out int iHeight) { iWidth = 0; iHeight = 0; if (theImage == null) return (Texture)null; try { Texture texture = (Texture)null; using (MemoryStream memoryStream = new MemoryStream()) { ImageInformation srcInformation = new ImageInformation(); theImage.Save((Stream)memoryStream, ImageFormat.Bmp); memoryStream.Flush(); memoryStream.Seek(0L, SeekOrigin.Begin); texture = TextureLoader.FromStream(GUIGraphicsContext.DX9Device, (Stream)memoryStream, 0, 0, 1, Usage.None, Format.X8R8G8B8, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, 0, ref srcInformation); memoryStream.Close(); iWidth = srcInformation.Width; iHeight = srcInformation.Height; } return texture; } catch (Exception ex) { Log.Info("Picture.ConvertImageToTexture( {0}x{1} ) exception err:{2} stack:{3}", (object)iWidth, (object)iHeight, (object)ex.Message, (object)ex.StackTrace); } return (Texture)null; }
public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { // Resource name is always without extension string resourceName = Path.GetFileNameWithoutExtension(identifier); int resourceId = 0; if (!_resourceIdentifiersCache.TryGetValue(resourceName, out resourceId)) { token.ThrowIfCancellationRequested(); resourceId = Context.Resources.GetIdentifier(resourceName.ToLower(), "drawable", Context.PackageName); _resourceIdentifiersCache.TryAdd(resourceName.ToLower(), resourceId); } if (resourceId == 0) throw new FileNotFoundException(identifier); token.ThrowIfCancellationRequested(); Stream stream = Context.Resources.OpenRawResource(resourceId); if (stream == null) throw new FileNotFoundException(identifier); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(identifier); return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation)); }
public void Add(string key, ImageInformation imageInformation, WriteableBitmap bitmap) { if (string.IsNullOrWhiteSpace(key) || bitmap == null) return; var weakRef = new WeakReference<WriteableBitmap>(bitmap); _reusableBitmaps.TryAdd(key, new Tuple<WeakReference<WriteableBitmap>, ImageInformation>(weakRef, imageInformation)); }
public void Add(string key, ImageInformation imageInformation, UIImage value) { if (string.IsNullOrWhiteSpace(key) || value == null) return; _imageInformations.TryAdd(key, imageInformation); _cache.SetCost(value, new NSString(key), value.GetMemorySize()); }
public D3DTexture2D(Texture pTexture, ImageInformation pImageInfo, string szName) { m_pTexture = pTexture; m_pImageInfo = pImageInfo; m_szName = szName; m_pBaseSurface = pTexture.GetSurfaceLevel(0); m_nFrames = 1; }
public void Add(string key, ImageInformation imageInformation, SelfDisposingBitmapDrawable bitmap) { if (string.IsNullOrWhiteSpace(key) || bitmap == null || bitmap.Handle == IntPtr.Zero || !bitmap.HasValidBitmap || _cache.ContainsKey(key)) return; _imageInformations.TryAdd(key, imageInformation); _cache.Add(key, bitmap); }
public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { string file = null; int scale = (int)ScaleHelper.Scale; if (scale > 1) { var filename = Path.GetFileNameWithoutExtension(identifier); var extension = Path.GetExtension(identifier); const string pattern = "{0}@{1}x{2}"; while (scale > 1) { token.ThrowIfCancellationRequested(); var tmpFile = string.Format(pattern, filename, scale, extension); if (FileStore.Exists(tmpFile)) { file = tmpFile; break; } scale--; } } if (string.IsNullOrEmpty(file) && FileStore.Exists(identifier)) { file = identifier; } token.ThrowIfCancellationRequested(); if (!string.IsNullOrEmpty(file)) { var stream = FileStore.GetInputStream(file, true); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(file); var result = (LoadingResult)(int)parameters.Source; if (parameters.LoadingPlaceholderPath == identifier) result = (LoadingResult)(int)parameters.LoadingPlaceholderSource; else if (parameters.ErrorPlaceholderPath == identifier) result = (LoadingResult)(int)parameters.ErrorPlaceholderSource; return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>( stream, result, imageInformation)); } throw new FileNotFoundException(identifier); }
public Task<WithLoadingResult<Stream>> GetStream(string identifier, CancellationToken token) { if (!FileStore.Exists(identifier)) { return Task.FromResult(WithLoadingResult.Encapsulate((Stream)null, LoadingResult.NotFound)); } var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(identifier); var result = WithLoadingResult.Encapsulate(FileStore.GetInputStream(identifier, false), LoadingResult.Disk, imageInformation); return Task.FromResult(result); }
public async static Task<WriteableBitmap> ToBitmapImageAsync(this Stream imageStream, Tuple<int, int> downscale, bool useDipUnits, InterpolationMode mode, ImageInformation imageInformation = null) { if (imageStream == null) return null; using (IRandomAccessStream image = new RandomStream(imageStream)) { if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0)) { using (var downscaledImage = await image.ResizeImage(downscale.Item1, downscale.Item2, mode, useDipUnits, imageInformation).ConfigureAwait(false)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage); downscaledImage.Seek(0); WriteableBitmap resizedBitmap = null; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); using (var s = downscaledImage.AsStream()) { resizedBitmap.SetSource(s); } }); return resizedBitmap; } } else { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image); image.Seek(0); WriteableBitmap bitmap = null; if (imageInformation != null) { imageInformation.SetCurrentSize((int)decoder.PixelWidth, (int)decoder.PixelHeight); imageInformation.SetOriginalSize((int)decoder.PixelWidth, (int)decoder.PixelHeight); } await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); bitmap.SetSource(imageStream); }); return bitmap; } } }
public async Task<WithLoadingResult<Stream>> GetStream(string identifier, CancellationToken token) { var cachedStream = await DownloadCache.GetStreamAsync(identifier, token, Parameters.CacheDuration, Parameters.CustomCacheKey, Parameters.CacheType).ConfigureAwait(false); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); var allowDiskCaching = Parameters.CacheType.HasValue == false || Parameters.CacheType == CacheType.All || Parameters.CacheType == CacheType.Disk; if (allowDiskCaching) { imageInformation.SetFilePath(await DownloadCache.GetDiskCacheFilePathAsync(identifier, Parameters.CustomCacheKey)); } return WithLoadingResult.Encapsulate(cachedStream.ImageStream, cachedStream.RetrievedFromDiskCache ? LoadingResult.DiskCache : LoadingResult.Internet, imageInformation); }
public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { token.ThrowIfCancellationRequested(); var stream = Context.Assets.Open(identifier, Access.Streaming); if (stream == null) throw new FileNotFoundException(identifier); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>( stream, LoadingResult.ApplicationBundle, imageInformation)); }
public async static Task<WriteableBitmap> ToBitmapImageAsync(this Stream imageStream, Tuple<int, int> downscale, bool downscaleDipUnits, InterpolationMode mode, ImageInformation imageInformation = null) { if (imageStream == null) return null; using (IRandomAccessStream image = imageStream.AsRandomAccessStream()) { if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0)) { using (var downscaledImage = await image.ResizeImage(downscale.Item1, downscale.Item2, mode, downscaleDipUnits, imageInformation).ConfigureAwait(false)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage); downscaledImage.Seek(0); WriteableBitmap resizedBitmap = null; await MainThreadDispatcher.Instance.PostAsync(async () => { resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); await resizedBitmap.SetSourceAsync(downscaledImage); }); return resizedBitmap; } } else { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image); image.Seek(0); WriteableBitmap bitmap = null; if (imageInformation != null) { imageInformation.SetCurrentSize((int)decoder.PixelWidth, (int)decoder.PixelHeight); imageInformation.SetOriginalSize((int)decoder.PixelWidth, (int)decoder.PixelHeight); } await MainThreadDispatcher.Instance.PostAsync(async () => { bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); await bitmap.SetSourceAsync(image); }); return bitmap; } } }
public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { var downloadedData = await DownloadCache.DownloadAndCacheIfNeededAsync(identifier, parameters, Configuration, token).ConfigureAwait(false); if (token.IsCancellationRequested) { downloadedData?.ImageStream?.Dispose(); token.ThrowIfCancellationRequested(); } var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(downloadedData?.FilePath); return new Tuple<Stream, LoadingResult, ImageInformation>( downloadedData?.ImageStream, downloadedData.RetrievedFromDiskCache ? LoadingResult.DiskCache : LoadingResult.Internet, imageInformation); }
public async Task<UIImageData> GetData(string identifier, CancellationToken token) { var downloadedData = await DownloadCache.GetAsync(identifier, token, Parameters.CacheDuration, Parameters.CustomCacheKey, Parameters.CacheType).ConfigureAwait(false); var bytes = downloadedData.Bytes; var path = downloadedData.CachedPath; var result = downloadedData.RetrievedFromDiskCache ? LoadingResult.DiskCache : LoadingResult.Internet; var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(await DownloadCache.GetDiskCacheFilePathAsync(identifier, Parameters.CustomCacheKey)); return new UIImageData() { Data = bytes, Result = result, ResultIdentifier = path, ImageInformation = imageInformation }; }
public virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { if (!FileStore.Exists(identifier)) { throw new FileNotFoundException(identifier); } token.ThrowIfCancellationRequested(); var stream = FileStore.GetInputStream(identifier, true); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(identifier); return Task.FromResult(new Tuple<Stream, LoadingResult, ImageInformation>( stream, LoadingResult.Disk, imageInformation)); }
public async virtual Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token) { StorageFile file = null; try { string resPath = identifier.TrimStart('\\', '/'); if (!resPath.StartsWith(@"Assets\") && !resPath.StartsWith("Assets/")) { resPath = @"Assets\" + resPath; } var imgUri = new Uri("ms-appx:///" + resPath); file = await StorageFile.GetFileFromApplicationUriAsync(imgUri); } catch (Exception) { try { var imgUri = new Uri("ms-appx:///" + identifier); file = await StorageFile.GetFileFromApplicationUriAsync(imgUri); } catch (Exception) { } } if (file != null) { var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(file.Path); token.ThrowIfCancellationRequested(); var stream = await file.OpenStreamForReadAsync(); return new Tuple<Stream, LoadingResult, ImageInformation>(stream, LoadingResult.CompiledResource, imageInformation); } throw new FileNotFoundException(identifier); }
public async Task <WithLoadingResult <Stream> > GetStream(string identifier, CancellationToken token) { StorageFile file = null; try { string resPath = identifier.TrimStart('\\', '/'); if (!resPath.StartsWith(@"Assets\") && !resPath.StartsWith("Assets/")) { resPath = @"Assets\" + resPath; } var imgUri = new Uri("ms-appx:///" + resPath); file = await StorageFile.GetFileFromApplicationUriAsync(imgUri); } catch (Exception) { try { var imgUri = new Uri("ms-appx:///" + identifier); file = await StorageFile.GetFileFromApplicationUriAsync(imgUri); } catch (Exception) { } } if (file != null) { var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(file.Path); return(WithLoadingResult.Encapsulate(await file.OpenStreamForReadAsync(), LoadingResult.CompiledResource, imageInformation)); } return(WithLoadingResult.Encapsulate <Stream>(null, LoadingResult.CompiledResource)); }
public async Task <bool> BrowseForImageAsync() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); var file = await picker.PickSingleFileAsync(); if (file != null) { this.IsBusy = true; var fileProperties = await file.Properties.GetImagePropertiesAsync(); byte[] imageBytes = await file.AsByteArrayAsync(); var image = new ImageInformation() { DisplayName = file.DisplayName, Description = "(no description)", Tags = new ObservableCollection <string>(), FileBytes = imageBytes, Url = file.Path, ImageHeight = (int)fileProperties.Height, ImageWidth = (int)fileProperties.Width, }; image.Url = await Helpers.StorageHelper.SaveToTemporaryFileAsync("VisionServices", file.Name, imageBytes); this.CurrentImage = image; this.IsBusy = false; } return(file != null); }
private void lv_Click(object sender, EventArgs e)//lv的Click事件。 { ImageInformation tempInformation = new ImageInformation(); foreach (ListViewItem lvi in image_listView.SelectedItems) //选中项遍历 { tempInformation.ImageNumber = lvi.SubItems[1].Text; tempInformation.PartsName = lvi.SubItems[2].Text; tempInformation.UpdateTime = DateTime.Parse(lvi.SubItems[3].Text); tempInformation.CompanyName = lvi.SubItems[4].Text; tempInformation.CompanyNumber = lvi.SubItems[5].Text; tempInformation.ProductName = lvi.SubItems[6].Text; tempInformation.ProductType = lvi.SubItems[7].Text; tempInformation.Path = lvi.SubItems[8].Text; } Spaper spaper = new Spaper(); spaper.GetPaper(tempInformation); //this.Hide(); spaper.Show(); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ImageInformation image = value as ImageInformation; if (image != null) { if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.iOS) { return((!(image.File is byte[] file)) ? null : ImageSource.FromStream(() => new System.IO.MemoryStream(file))); } else { return(image.Url); } } else { return(null); } }
private async Task <DataResolverResult> ResolveFromAssetCatalogAsync(string fileName, string identifier, TaskParameter parameters, CancellationToken token) { #if __IOS__ || __TVOS__ if (!UIDevice.CurrentDevice.CheckSystemVersion(9, 0)) { return(null); } #endif NSDataAsset asset = null; try { await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() => asset = new NSDataAsset(identifier, NSBundle.MainBundle)).ConfigureAwait(false); } catch { } if (asset == null && fileName != identifier) { try { await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() => asset = new NSDataAsset(fileName, NSBundle.MainBundle)).ConfigureAwait(false); } catch { } } if (asset != null) { token.ThrowIfCancellationRequested(); var stream = asset.Data?.AsStream(); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); return(new DataResolverResult(stream, LoadingResult.CompiledResource, imageInformation)); } return(null); }
private async void LoopChange() { var r = new Random(); var delay = TimeSpan.FromSeconds(10); while (true) { await Task.Delay(delay); if (this.currentLayout.Count > 0) { var index = r.Next(this.currentLayout.Count - 1); var current = this.currentLayout[index]; if (current != null) { var information = new ImageInformation(current.Size, current.X, current.Y, true); this.targetTiles.Add(information); SetTileInformation(information, this.targetLayout); } } } }
public Task <Tuple <Stream, LoadingResult, ImageInformation> > Resolve(string identifier, TaskParameter parameters, CancellationToken token) { var fileName = Path.GetFileNameWithoutExtension(identifier); var extension = Path.GetExtension(identifier).TrimStart('.'); var bundle = NSBundle._AllBundles.FirstOrDefault(bu => !string.IsNullOrEmpty(bu.PathForResource(fileName, extension))); if (bundle != null) { var url = bundle.GetUrlForResource(fileName, extension); var stream = FileStore.GetInputStream(url.Path, true); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(url.Path); return(Task.FromResult(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation))); } throw new FileNotFoundException(identifier); }
public string LoadTexture(Device device) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "PNG Image (*.png)|*.png"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { try { string path = dialog.FileName; string fileName = Path.GetFileNameWithoutExtension(path); ImageInformation info = TextureLoader.ImageInformationFromFile(path); Texture texture = TextureLoader.FromFile(device, path, info.Width, info.Height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.None, Filter.None, 0); if (textures.ContainsKey(fileName)) { MessageBox.Show("Texture already added", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(String.Empty); } else { textures.Add(fileName, texture); return(fileName); } } catch (Exception e) { error = e.Message; return(String.Empty); } } return(String.Empty); }
protected override void LoadTexture(string folder) { ImageInformation info = new ImageInformation(); try { // First look for the texture in the same folder as the input folder info = TextureLoader.ImageInformationFromFile(fileName); } catch { try { // Couldn't find it, look in the media folder fileName = Utility.FindMediaFile(fileName, folder); info = TextureLoader.ImageInformationFromFile(fileName); } catch (MediaNotFoundException) { // Couldn't find it anywhere, skip it return; } } switch (info.ResourceType) { case ResourceType.Textures: texture = TextureLoader.FromFile(Framework.Instance.Device, fileName); break; case ResourceType.CubeTexture: texture = TextureLoader.FromCubeFile(Framework.Instance.Device, fileName); break; case ResourceType.VolumeTexture: texture = TextureLoader.FromVolumeFile(Framework.Instance.Device, fileName); break; } }
public ModelTexture LoadTexture(IPackageIndexer packageIndexer, string texturePath, Device device) { using (var stream = ModelTextureManager.OpenTexture(packageIndexer, texturePath)) { var pos = stream.Position; lock (_textures) { if (!_textures.TryGetValue(texturePath, out ModelTexture texture)) { var info = ImageInformation.FromStream(stream); stream.Seek(pos, SeekOrigin.Begin); texture = new ModelTexture(texturePath, Texture.FromStream(device, stream), info); _textures.Add(texturePath, texture); } else { texture.AddRef(); } return(texture); } } }
public void Add(string key, ImageInformation imageInformation, SharedEvasImage value) { if (string.IsNullOrWhiteSpace(key) || value == null || value.Handle == IntPtr.Zero) { return; } if (_imageInformations.ContainsKey(key)) { Remove(key, false); } var byteSize = imageInformation.CurrentWidth * imageInformation.CurrentHeight * 4; lock (_lock) { _currentCacheSize += byteSize; if (_currentCacheSize > _maxCacheSize) { if (ImageService.Instance.Config.VerboseMemoryCacheLogging) { _logger.Debug($"MemoryCache Size Exceed {_currentCacheSize/1024.0}kb"); } if (_lruQueue.Last != null) { var removedKey = _lruQueue.Last.Value; _lruQueue.RemoveLast(); Remove(removedKey); } } value.AddRef(); _imageInformations.TryAdd(key, imageInformation); _cache.Add(key, value); _lruQueue.AddFirst(key); } }
public Task <Tuple <Stream, LoadingResult, ImageInformation> > Resolve(string identifier, TaskParameter parameters, CancellationToken token) { if (!identifier.StartsWith("resource://", StringComparison.OrdinalIgnoreCase)) { throw new Exception("Only resource:// scheme is supported"); } Uri uri = new Uri(identifier); Assembly assembly = null; var parts = uri.OriginalString.Substring(11).Split('?'); string resourceName = parts.First(); if (parts.Count() > 1) { var name = Uri.UnescapeDataString(uri.Query.Substring(10)); var assemblyName = new AssemblyName(name); assembly = Assembly.Load(assemblyName); } if (assembly == null) { MethodInfo callingAssemblyMethod = typeof(Assembly).GetTypeInfo().GetDeclaredMethod("GetCallingAssembly"); assembly = (Assembly)callingAssemblyMethod.Invoke(null, new object[0]); } var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(identifier); var stream = assembly.GetManifestResourceStream(resourceName); return(Task.FromResult(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.EmbeddedResource, imageInformation))); }
public void LoadDropFiles(ViewerForm viewer, string[] files) { try { if (files != null) { for (int i = 0; i < files.Length; i++) { try { RasterImage image = _codecs.Load(files[i]); ImageInformation info = new ImageInformation(image, files[i]); if (i == 0 && viewer != null) { viewer.Initialize(info, _paintProperties, false); } else { NewImage(info); } } catch (Exception ex) { Messager.ShowFileOpenError(this, files[i], ex); } } } } catch (Exception ex) { Messager.ShowError(this, ex); } finally { UpdateControls(); } }
private void LoadPackedGraphics(int index) { // return ; PackedTexture bigOne = _packedTextures[index]; const Format useFormat = Format.A8R8G8B8; //if (IsCompressedTextureFormatOk(Format.Dxt5)) //{ // Log.Debug("TexturePacker: Using DXT5 texture format"); // useFormat = Format.Dxt5; //} if (bigOne.texture == null) { bigOne.textureNo = -1; string fileName = String.Format(@"{0}\packedgfx2{1}.png", GUIGraphicsContext.SkinCacheFolder, index); var info2 = new ImageInformation(); Texture tex = TextureLoader.FromFile(GUIGraphicsContext.DX9Device, fileName, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, useFormat, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, 0, ref info2); bigOne.texture = tex; bigOne.texture.Disposing -= TextureDisposing; bigOne.texture.Disposing += TextureDisposing; Log.Info("TexturePacker: Loaded {0} texture:{1}x{2} miplevels:{3}", fileName, info2.Width, info2.Height, tex.LevelCount); } }
private void _miFileOpen_Click(object sender, EventArgs e) { try { ImageInformation info = LoadImage(); if (info != null) { NewImage(info); } if (ActiveViewerForm != null) { AddImageToUndoList(ActiveViewerForm.Viewer.Image); } } catch (Exception ex) { Messager.ShowError(this, ex); } finally { UpdateControls(); } }
/// <summary> /// Creates a texture /// </summary> public void CreateTexture(int tex) { // Get the texture node here TextureNode tn = GetTextureNode(tex); // Make sure there's a texture to create if ((tn.Filename == null) || (tn.Filename.Length == 0)) { return; } // Find the texture string path = Utility.FindMediaFile(tn.Filename); // Create the new texture ImageInformation info = new ImageInformation(); tn.Texture = TextureLoader.FromFile(device, path, D3DX.Default, D3DX.Default, D3DX.Default, Usage.None, Format.Unknown, Pool.Managed, (Filter)D3DX.Default, (Filter)D3DX.Default, 0, ref info); // Store dimensions tn.Width = (uint)info.Width; tn.Height = (uint)info.Height; }
public void MakeTexture(Device device, byte[] txData) { try { var information = ImageInformation.FromMemory(txData); this.sz画像サイズ = new Size(information.Width, information.Height); this.rc全画像 = new Rectangle(0, 0, this.sz画像サイズ.Width, this.sz画像サイズ.Height); this.colorKey = 0; this.szテクスチャサイズ = this.t指定されたサイズを超えない最適なテクスチャサイズを返す(device, this.sz画像サイズ); // lock ( lockobj ) // { //Trace.TraceInformation( "CTexture() start: " ); this.texture = Texture.FromMemory(device, txData, this.sz画像サイズ.Width, this.sz画像サイズ.Height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.Point, Filter.None, this.colorKey); //Trace.TraceInformation( "CTexture() end: " ); // } this.bSharpDXTextureDispose完了済み = false; } catch { this.Dispose(); // throw new CTextureCreateFailedException( string.Format( "テクスチャの生成に失敗しました。\n{0}", strファイル名 ) ); throw new CTextureCreateFailedException(string.Format("テクスチャの生成に失敗しました。\n")); } }
private void fillTxtBx(ImageInformation imInfo) { string flagStr = buildFlagsStr(); string fadeStr = " Close Fade: " + fade[0] + "\tFar Fade: " + fade[1]; string alphaStr = hasAlpha ? "Has Alpha" : "No Alpha"; flagStr = flagStr.Length > 1 ? flagStr : "None"; textBox1.Text = "\r\n"; textBox1.Text += " Flags: " + flagStr + "\r\n"; textBox1.Text += fadeStr + "\r\n"; textBox1.Text += " Format: " + imInfo.Format + "\t" + alphaStr + "\r\n"; textBox1.Text += " MipLevels: " + imInfo.MipLevels + "\tDepth: " + imInfo.Depth + "\r\n"; textBox1.Text += " Height: " + imInfo.Height + "\tWidth:" + imInfo.Width + "\r\n"; textBox1.SelectionStart = 0; }
#pragma warning disable CS1998 // 이 비동기 메서드에는 'await' 연산자가 없으며 메서드가 동시에 실행됩니다. public virtual async Task <DataResolverResult> Resolve(string identifier, TaskParameter parameters, CancellationToken token) #pragma warning restore CS1998 // 이 비동기 메서드에는 'await' 연산자가 없으며 메서드가 동시에 실행됩니다. { try { if (TrimmedResource.ContainsKey(identifier)) { identifier = TrimmedResource[identifier]; } var data = Application.GetResourceStream(new Uri(identifier, UriKind.Relative)); var image = new ImageInformation(); image.SetPath(identifier); image.SetFilePath(identifier); token.ThrowIfCancellationRequested(); return(new DataResolverResult(data.Stream, LoadingResult.CompiledResource, image)); } catch (IOException io) { throw new FileNotFoundException(identifier, io); } }
/// <summary> /// Creates a texture /// </summary> public void CreateTexture(int tex) { // Get the texture node here TextureNode tn = GetTextureNode(tex); // Make sure there's a texture to create if (string.IsNullOrEmpty(tn.Filename)) { return; } // Create the new texture var info = new ImageInformation(); using (var stream = ContentManager.GetFileStream("GUI/Textures", tn.Filename)) { tn.Texture = Texture.FromStream(Engine.Device, stream, D3DX.Default, D3DX.Default, D3DX.Default, Usage.None, Format.Unknown, Pool.Managed, Filter.Default, Filter.Default, 0); } // Store dimensions tn.Width = (uint)info.Width; tn.Height = (uint)info.Height; }
Task <Tuple <Stream, LoadingResult, ImageInformation> > GetBase64Stream(string data, ImageInformation imageInformation) { var streamBase64 = new MemoryStream(Convert.FromBase64String(data)); return(Task.FromResult(new Tuple <Stream, LoadingResult, ImageInformation>( streamBase64, LoadingResult.EmbeddedResource, imageInformation))); }
private Task <DataResolverResult> ResolveFromBundlesAsync(string fileName, string identifier, TaskParameter parameters, CancellationToken token) { NSBundle bundle = null; var ext = Path.GetExtension(identifier)?.TrimStart(new char[] { '.' }); var tmpPath = Path.GetDirectoryName(identifier)?.Trim('/'); var filenamePath = string.IsNullOrWhiteSpace(tmpPath) ? null : tmpPath + "/"; var hasExtension = !string.IsNullOrWhiteSpace(ext); var fileTypes = hasExtension ? new[] { ext } : _fileTypes; foreach (var fileType in fileTypes) { string file = null; string lastPath = null; token.ThrowIfCancellationRequested(); var scale = (int)ScaleHelper.Scale; if (scale > 1) { while (scale > 1) { token.ThrowIfCancellationRequested(); var tmpFile = string.Format("{0}@{1}x", fileName, scale); bundle = NSBundle._AllBundles.FirstOrDefault(bu => { lastPath = string.IsNullOrWhiteSpace(filenamePath) ? bu.PathForResource(tmpFile, fileType) : bu.PathForResource(tmpFile, fileType, filenamePath); return(!string.IsNullOrWhiteSpace(lastPath)); }); if (bundle != null) { file = tmpFile; break; } scale--; } } token.ThrowIfCancellationRequested(); if (file == null) { bundle = NSBundle._AllBundles.FirstOrDefault(bu => { lastPath = string.IsNullOrWhiteSpace(filenamePath) ? bu.PathForResource(fileName, fileType) : bu.PathForResource(fileName, fileType, filenamePath); return(!string.IsNullOrWhiteSpace(lastPath)); }); } token.ThrowIfCancellationRequested(); if (bundle != null) { var stream = FileStore.GetInputStream(lastPath, true); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(lastPath); var result = new DataResolverResult(stream, LoadingResult.CompiledResource, imageInformation); return(Task.FromResult(result)); } } return(Task.FromResult <DataResolverResult>(null)); }
// Shamelessly copied from React-Native: https://github.com/facebook/react-native/blob/2cbc9127560c5f0f89ae5aa6ff863b1818f1c7c3/Libraries/Image/RCTImageUtils.m public static UIImage ToImage(this NSData data, CGSize destSize, nfloat destScale, RCTResizeMode resizeMode = RCTResizeMode.ScaleAspectFit, ImageInformation imageinformation = null, bool allowUpscale = false) { using (var sourceRef = CGImageSource.FromData(data)) { var imageProperties = GetImageProperties(sourceRef); if (imageProperties == null) { throw new BadImageFormatException("Image is null"); } if (imageinformation != null) { if (imageProperties.PixelWidth.HasValue && imageProperties.PixelHeight.HasValue) { imageinformation.SetOriginalSize(imageProperties.PixelWidth.Value, imageProperties.PixelHeight.Value); } } var sourceSize = new CGSize((nfloat)imageProperties.PixelWidth, (nfloat)imageProperties.PixelHeight); if (destSize.IsEmpty) { destSize = sourceSize; if (destScale <= 0) { destScale = 1; } } else if (destScale <= 0) { destScale = ScaleHelper.Scale; } // Calculate target size CGSize targetSize = RCTTargetSize(sourceSize, 1, destSize, destScale, resizeMode, allowUpscale); CGSize targetPixelSize = RCTSizeInPixels(targetSize, destScale); int maxPixelSize = (int)Math.Max( Math.Min(sourceSize.Width, targetPixelSize.Width), Math.Min(sourceSize.Height, targetPixelSize.Height) ); var options = new CGImageThumbnailOptions() { ShouldAllowFloat = true, CreateThumbnailWithTransform = true, CreateThumbnailFromImageAlways = true, MaxPixelSize = maxPixelSize, ShouldCache = false, }; UIImage image = null; // gif if (sourceRef.ImageCount > 1) { image = GifHelper.AnimateGif(sourceRef, destScale); } else { // Get thumbnail using (var imageRef = sourceRef.CreateThumbnail(0, options)) { if (imageRef != null) { // Return image image = new UIImage(imageRef, destScale, UIImageOrientation.Up); } } } if (imageinformation != null && image != null) { int width = (int)image.Size.Width; int height = (int)image.Size.Height; imageinformation.SetCurrentSize(width.PointsToPixels(), height.PointsToPixels()); } return(image); } }
public async Task <IDecodedImage <Bitmap> > DecodeAsync(Stream stream, string path, ImageSource source, ImageInformation imageInformation, TaskParameter parameters) { var result = new DecodedImage <Bitmap>(); using (var gifDecoder = new GifHelper()) { var insampleSize = 1; // DOWNSAMPLE if (parameters.DownSampleSize != null && (parameters.DownSampleSize.Item1 > 0 || parameters.DownSampleSize.Item2 > 0)) { // Calculate inSampleSize var downsampleWidth = parameters.DownSampleSize.Item1; var downsampleHeight = parameters.DownSampleSize.Item2; if (parameters.DownSampleUseDipUnits) { downsampleWidth = downsampleWidth.DpToPixels(); downsampleHeight = downsampleHeight.DpToPixels(); } await gifDecoder.ReadHeaderAsync(stream).ConfigureAwait(false); insampleSize = BaseDecoder.CalculateInSampleSize(gifDecoder.Width, gifDecoder.Height, downsampleWidth, downsampleHeight, false); } await gifDecoder.ReadAsync(stream, insampleSize).ConfigureAwait(false); gifDecoder.Advance(); imageInformation.SetOriginalSize(gifDecoder.Width, gifDecoder.Height); if (insampleSize > 1) { imageInformation.SetCurrentSize(gifDecoder.DownsampledWidth, gifDecoder.DownsampledHeight); } else { imageInformation.SetCurrentSize(gifDecoder.Width, gifDecoder.Height); } result.IsAnimated = gifDecoder.FrameCount > 1 && Configuration.AnimateGifs; if (result.IsAnimated && Configuration.AnimateGifs) { result.AnimatedImages = new AnimatedImage <Bitmap> [gifDecoder.FrameCount]; for (var i = 0; i < gifDecoder.FrameCount; i++) { var animatedImage = new AnimatedImage <Bitmap> { Delay = gifDecoder.GetDelay(i), Image = await gifDecoder.GetNextFrameAsync() }; result.AnimatedImages[i] = animatedImage; gifDecoder.Advance(); } } else { result.IsAnimated = false; result.Image = await gifDecoder.GetNextFrameAsync(); } if (result.Image != null) { imageInformation.SetOriginalSize(result.Image.Width, result.Image.Height); imageInformation.SetCurrentSize(result.Image.Width, result.Image.Height); } else if (result.AnimatedImages != null) { if (result.AnimatedImages.Length > 0) { if (result.AnimatedImages[0].Image != null) { imageInformation.SetOriginalSize(result.AnimatedImages[0].Image.Width, result.AnimatedImages[0].Image.Height); imageInformation.SetCurrentSize(result.AnimatedImages[0].Image.Width, result.AnimatedImages[0].Image.Height); } } } return(result); } }
private static Texture LoadGraphic(string fileName, long lColorKey, int iMaxWidth, int iMaxHeight, out int width, out int height) { width = 0; height = 0; Image imgSrc = null; Texture texture = null; try { #if DO_RESAMPLE imgSrc=Image.FromFile(fileName); if (imgSrc==null) return null; //Direct3D prefers textures which height/width are a power of 2 //doing this will increases performance //So the following core resamples all textures to //make sure all are 2x2, 4x4, 8x8, 16x16, 32x32, 64x64, 128x128, 256x256, 512x512 int w=-1,h=-1; if (imgSrc.Width >2 && imgSrc.Width < 4) w=2; if (imgSrc.Width >4 && imgSrc.Width < 8) w=4; if (imgSrc.Width >8 && imgSrc.Width < 16) w=8; if (imgSrc.Width >16 && imgSrc.Width < 32) w=16; if (imgSrc.Width >32 && imgSrc.Width < 64) w=32; if (imgSrc.Width >64 && imgSrc.Width <128) w=64; if (imgSrc.Width >128 && imgSrc.Width <256) w=128; if (imgSrc.Width >256 && imgSrc.Width <512) w=256; if (imgSrc.Width >512 && imgSrc.Width <1024) w=512; if (imgSrc.Height >2 && imgSrc.Height < 4) h=2; if (imgSrc.Height >4 && imgSrc.Height < 8) h=4; if (imgSrc.Height >8 && imgSrc.Height < 16) h=8; if (imgSrc.Height >16 && imgSrc.Height < 32) h=16; if (imgSrc.Height >32 && imgSrc.Height < 64) h=32; if (imgSrc.Height >64 && imgSrc.Height <128) h=64; if (imgSrc.Height >128 && imgSrc.Height <256) h=128; if (imgSrc.Height >256 && imgSrc.Height <512) h=256; if (imgSrc.Height >512 && imgSrc.Height <1024) h=512; if (w>0 || h>0) { if (h > w) w=h; Log.Info("TextureManager: resample {0}x{1} -> {2}x{3} {4}", imgSrc.Width,imgSrc.Height, w,w,fileName); Image imgResampled=Resample(imgSrc,w, h); imgSrc.SafeDispose(); imgSrc=imgResampled; imgResampled=null; } #endif Format fmt = Format.A8R8G8B8; ImageInformation info2 = new ImageInformation(); texture = TextureLoader.FromFile(GUIGraphicsContext.DX9Device, fileName, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, fmt, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)lColorKey, ref info2); width = info2.Width; height = info2.Height; } catch (InvalidDataException e1) // weird : should have been FileNotFoundException when file is missing ?? { //we need to catch this on higer level. throw e1; } catch (Exception) { Log.Error("TextureManager: LoadGraphic - invalid thumb({0})", fileName); Format fmt = Format.A8R8G8B8; string fallback = GUIGraphicsContext.GetThemedSkinFile(@"\media\" + "black.png"); ImageInformation info2 = new ImageInformation(); texture = TextureLoader.FromFile(GUIGraphicsContext.DX9Device, fallback, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, fmt, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)lColorKey, ref info2); width = info2.Width; height = info2.Height; } finally { if (imgSrc != null) { imgSrc.SafeDispose(); } } return texture; }
public async static Task <ImageInformation> RetrieveImageFromObjectStorageAsync(ImageInformation image) { StorageAccountSettings storageAccountSettings = Common.CurrentStorageAccountSettings; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountSettings.ConnectionString); CloudBlobClient client = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = client.GetContainerReference(storageAccountSettings.DownloadsContainerName); CloudBlockBlob blob = null; bool blobExists = false; try { do { blob = container.GetBlockBlobReference(image.FileName); blobExists = await blob.ExistsAsync(); if (blobExists) { image.Photo = new byte[blob.Properties.Length]; await blob.DownloadToByteArrayAsync(image.Photo, 0); image.ThumbnailUrl = blob.Uri.OriginalString; image.ImageUrl = blob.Uri.OriginalString.Replace("-downloads", "-uploads"); await blob.FetchAttributesAsync(); image.Caption = (blob.Metadata.ContainsKey("caption")) ? blob.Metadata["caption"] + "" : "(unable to caption)"; image.Tags = (blob.Metadata.ContainsKey("tags")) ? (blob.Metadata["tags"] + "").Split(',').ToList() : new List <string>(); } else { await Task.Delay(500); } }while (!blobExists); } catch (Exception ex) { } return(image); }
/// <summary> /// This method converts a GDI image to a DirectX Textures /// </summary> /// <param name="theImage">GDI Image</param> /// <param name="iWidth">width of returned texture</param> /// <param name="iHeight">height of returned texture</param> /// <returns>Texture with image or null if image could not be loaded</returns> public static Texture ConvertImageToTexture(Bitmap theImage, out int iWidth, out int iHeight) { iWidth = 0; iHeight = 0; if (theImage == null) return null; // Texture texture=null; try { Texture texture = null; using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { ImageInformation info2 = new ImageInformation(); theImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); stream.Flush(); stream.Seek(0, System.IO.SeekOrigin.Begin); texture = TextureLoader.FromStream( GUIGraphicsContext.DX9Device, stream, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, Format.X8R8G8B8, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)0, ref info2); stream.Close(); iWidth = info2.Width; iHeight = info2.Height; } return texture; } catch (Exception ex) { Log.Info("Picture.ConvertImageToTexture( {0}x{1} ) exception err:{2} stack:{3}", iWidth, iHeight, ex.Message, ex.StackTrace); } return null; }
/// <summary> /// Initialize the device objects. Load the texture or if it does not exist, create it. /// </summary> public void InitializeDeviceObjects() { BinaryFormatter b = new BinaryFormatter(); Stream s = null; bool needsCreation = false; string strCache = String.Format(@"{0}\fonts\{1}_{2}.dds", GUIGraphicsContext.SkinCacheFolder, _fontName, _fontHeight); try { // If file does not exist //needsCreation = !File.Exists(strCache); if (!needsCreation) { try { ImageInformation info = new ImageInformation(); _textureFont = TextureLoader.FromFile(GUIGraphicsContext.DX9Device, strCache, 0, 0, //width/height 1, //miplevels 0, Format.Unknown, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, 0, ref info); s = File.Open(strCache + ".bxml", FileMode.Open, FileAccess.Read); _textureCoords = (float[,])b.Deserialize(s); s.Close(); _spacingPerChar = (int)_textureCoords[_EndCharacter - _StartCharacter, 0]; _textureScale = _textureCoords[_EndCharacter - _StartCharacter + 1, 0]; _textureHeight = info.Height; _textureWidth = info.Width; Log.Debug(" Loaded font:{0} height:{1} texture:{2}x{3} chars:[{4}-{5}] miplevels:{6}", _fontName, _fontHeight, _textureWidth, _textureHeight, _StartCharacter, _EndCharacter, _textureFont.LevelCount); } catch (InvalidDataException) // weird : should have been FileNotFoundException when file is missing ?? { needsCreation = true; } catch (Exception) { // Deserialisation failed. Maybe the language changed or the font cache got manipulated. Log.Error("GUIFont: Failed to load font {0} from cache. Trying to recreate it...", _fontName); MediaPortal.Util.Utils.FileDelete(strCache); MediaPortal.Util.Utils.FileDelete(strCache + ".bxml"); needsCreation = true; } } if (needsCreation) { Log.Debug("TextureLoader.CreateFile {0}", strCache); // Make sure directory exists try { Directory.CreateDirectory(String.Format(@"{0}\fonts\", GUIGraphicsContext.SkinCacheFolder)); // Create bitmap with the fonts using (Bitmap bmp = CreateFontBitmap()) { // Save bitmap to stream using (MemoryStream imageStream = new MemoryStream()) { bmp.Save(imageStream, ImageFormat.Bmp); // Reset and load from steam imageStream.Position = 0; Format format = Format.Dxt3; if (GUIGraphicsContext.GetTexturePoolType() == Pool.Default) { format = Format.Unknown; } ImageInformation info = new ImageInformation(); _textureFont = TextureLoader.FromStream(GUIGraphicsContext.DX9Device, imageStream, (int)imageStream.Length, 0, 0, //width/height 1, //miplevels 0, format, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, 0, ref info); // Finally save texture and texture coords to disk TextureLoader.Save(strCache, ImageFileFormat.Dds, _textureFont); s = File.Open(strCache + ".bxml", FileMode.CreateNew, FileAccess.ReadWrite); b.Serialize(s, (object)_textureCoords); s.Close(); Log.Debug("Saving font:{0} height:{1} texture:{2}x{3} chars:[{4}-{5}] miplevels:{6}", _fontName, _fontHeight, _textureWidth, _textureHeight, _StartCharacter, _EndCharacter, _textureFont.LevelCount); } } } catch (Exception) {} } try { _textureFont.Disposing -= new EventHandler(_textureFont_Disposing); _textureFont.Disposing += new EventHandler(_textureFont_Disposing); SetFontEgine(); _d3dxFont = new Microsoft.DirectX.Direct3D.Font(GUIGraphicsContext.DX9Device, _systemFont); } catch (Exception) { Log.Error("GUIFont: Failed to D3D..."); } } finally { if (s != null) s.SafeDispose(); } }
public static int LoadFromMemory(Image memoryImage, string name, long lColorKey, int iMaxWidth, int iMaxHeight) { Log.Debug("TextureManager: load from memory: {0}", name); string cacheName = name; string cacheKey = name.ToLower(); CachedTexture cached; if (_cacheTextures.TryGetValue(cacheKey, out cached)) { return cached.Frames; } if (memoryImage == null) { return 0; } if (memoryImage.FrameDimensionsList == null) { return 0; } if (memoryImage.FrameDimensionsList.Length == 0) { return 0; } try { CachedTexture newCache = new CachedTexture(); newCache.Name = cacheName; FrameDimension oDimension = new FrameDimension(memoryImage.FrameDimensionsList[0]); newCache.Frames = memoryImage.GetFrameCount(oDimension); if (newCache.Frames != 1) { return 0; } //load gif into texture using (MemoryStream stream = new MemoryStream()) { memoryImage.Save(stream, ImageFormat.Png); ImageInformation info2 = new ImageInformation(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); Texture texture = TextureLoader.FromStream( GUIGraphicsContext.DX9Device, stream, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, Format.A8R8G8B8, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)lColorKey, ref info2); newCache.Width = info2.Width; newCache.Height = info2.Height; newCache.texture = new CachedTexture.Frame(cacheName, texture, 0); } memoryImage.SafeDispose(); memoryImage = null; newCache.Disposed += new EventHandler(cachedTexture_Disposed); _cacheTextures[cacheKey] = newCache; Log.Debug("TextureManager: added: memoryImage " + " total count: " + _cacheTextures.Count + ", mem left (MB): " + ((uint)GUIGraphicsContext.DX9Device.AvailableTextureMemory / 1048576)); return newCache.Frames; } catch (Exception ex) { Log.Error("TextureManager: exception loading texture memoryImage"); Log.Error(ex); } return 0; }
/// <summary> /// Creates a texture /// </summary> public void CreateTexture(int tex) { // Get the texture node here TextureNode tn = GetTextureNode(tex); // Make sure there's a texture to create if ((tn.Filename == null) || (tn.Filename.Length == 0)) return; // Find the texture string path = Utility.FindMediaFile(tn.Filename); // Create the new texture ImageInformation info = new ImageInformation(); tn.Texture = TextureLoader.FromFile(device, path, D3DX.Default, D3DX.Default, D3DX.Default, Usage.None, Format.Unknown, Pool.Managed, (Filter)D3DX.Default, (Filter)D3DX.Default, 0, ref info); // Store dimensions tn.Width = (uint)info.Width; tn.Height = (uint)info.Height; }
Task <Tuple <Stream, LoadingResult, ImageInformation> > GetRAWStream(string data, ImageInformation imageInformation) { var stream = new MemoryStream(Encoding.UTF8.GetBytes(data)); return(Task.FromResult(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.EmbeddedResource, imageInformation))); }
private static void DrawTextUsingTexture(FontManagerDrawText draw, int fontSize) { bool textureCached = false; int cacheSlot = 0; FontTexture drawingTexture = new FontTexture(); foreach (FontTexture cachedTexture in _listFontTextures) { if (cachedTexture.text == draw.text && cachedTexture.size == fontSize) { textureCached = true; drawingTexture = cachedTexture; break; } cacheSlot++; } Size size = new Size(0, 0); if (textureCached) { //keep commonly used textures at the top of the pile _listFontTextures.RemoveAt(cacheSlot); _listFontTextures.Add(drawingTexture); } else // texture needs to be cached { Texture texture = null; float textwidth = 0, textheight = 0; MeasureText(draw.text, ref textwidth, ref textheight, fontSize); size.Width = (int)textwidth; size.Height = (int)textheight; try { // The MemoryStream must be kept open for the lifetime of the bitmap using (MemoryStream imageStream = new MemoryStream()) { using (Bitmap bitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAlias; g.TextContrast = 0; g.DrawString(draw.text, CachedSystemFont(fontSize), Brushes.White, new Point((int)0, (int)0), StringFormat.GenericTypographic); bitmap.Save(imageStream, ImageFormat.Bmp); imageStream.Position = 0; Format format = Format.Dxt3; if (GUIGraphicsContext.GetTexturePoolType() == Pool.Default) { format = Format.Unknown; } ImageInformation info = new ImageInformation(); try { texture = TextureLoader.FromStream(GUIGraphicsContext.DX9Device, imageStream, (int)imageStream.Length, 0, 0, 1, 0, format, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, 0, ref info); } catch (OutOfVideoMemoryException oovme) { Log.Error("GUIFontManager: OutOfVideoMemory in DrawTextUsingTexture - {0}", oovme.Message); } catch (OutOfMemoryException oome) { Log.Error("GUIFontManager: OutOfMemory in DrawTextUsingTexture - {0}", oome.Message); } } } } } catch (Exception ex) { Log.Error("GUIFontManager: Error in DrawTextUsingTexture - {0}", ex.Message); } MeasureText(draw.text, ref textwidth, ref textheight, fontSize); size.Width = (int)textwidth; size.Height = (int)textheight; FontTexture newTexture = new FontTexture(); newTexture.text = draw.text; newTexture.texture = texture; newTexture.size = fontSize; if (_listFontTextures.Count >= _maxCachedTextures) { //need to clear this and not rely on the finalizer FontTexture disposableFont = _listFontTextures[0]; _listFontTextures.RemoveAt(0); disposableFont.Dispose(); } _listFontTextures.Add(newTexture); drawingTexture = newTexture; } _d3dxSprite.Draw(drawingTexture.texture, new Rectangle(0, 0, size.Width, size.Height), Vector3.Empty, new Vector3((int)draw.xpos, (int)draw.ypos, 0), (int)draw.color); }
private static void InternalDDSFromStream(Stream stream, Device device, int streamOffset, bool loadMipMap, int offsetMipMaps, out SharpDX.Direct3D9.Texture texture) { var fileStream = stream as FileStream; byte[] data = fileStream != null ? null : SharpDX.Utilities.ReadStream(stream); int maxTextureDimension = MyRender.GraphicsDevice.Capabilities.MaxTextureWidth; if (IntPtr.Size == 4 || MyRender.GraphicsDevice.AvailableTextureMemory < 1024 * 1024 * 600) { maxTextureDimension = 2048; } ImageInformation imageInfo; if (fileStream != null) { imageInfo = GetImageInfoFromFileW(fileStream.Name); } else { imageInfo = ImageInformation.FromMemory(data); } var textureWidth = imageInfo.Width; var textureHeight = imageInfo.Height; textureWidth = Math.Max(1, textureWidth >> offsetMipMaps); textureHeight = Math.Max(1, textureHeight >> offsetMipMaps); int loadMipmapOffset = offsetMipMaps; while (textureWidth > maxTextureDimension || textureHeight > maxTextureDimension) { loadMipmapOffset++; textureWidth = Math.Max(1, textureWidth >> 1); textureHeight = Math.Max(1, textureHeight >> 1); } if (offsetMipMaps == 0 && loadMipmapOffset == 0) { if (fileStream != null) { texture = SharpDX.Direct3D9.Texture.FromFile(device, fileStream.Name, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0); } else { texture = SharpDX.Direct3D9.Texture.FromMemory(device, data, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0); } } else if (loadMipmapOffset > 0) { var skipFilter = (Filter)D3DXSkipDDSMipLevels((uint)loadMipmapOffset); if (fileStream != null) { texture = SharpDX.Direct3D9.Texture.FromFile(device, fileStream.Name, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, skipFilter, 0); } else { texture = SharpDX.Direct3D9.Texture.FromMemory(device, data, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, skipFilter, 0); } } else { if (fileStream != null) { texture = SharpDX.Direct3D9.Texture.FromFile(device, fileStream.Name, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0); } else { texture = SharpDX.Direct3D9.Texture.FromMemory(device, data, 0, 0, 0, Usage.None, Format.Unknown, Pool.Default, Filter.None, Filter.None, 0); } int width = MipMapSize(offsetMipMaps, texture.GetLevelDescription(0).Width); int height = MipMapSize(offsetMipMaps, texture.GetLevelDescription(0).Height); int maxLevels = Math.Min(MaxMipMapLevels(width), MaxMipMapLevels(height)); int actualLevels = Math.Min(maxLevels, texture.LevelCount - offsetMipMaps); Format format = texture.GetLevelDescription(0).Format; Texture offsetedTexture = new Texture(device, width, height, actualLevels, Usage.Dynamic, format, Pool.Default); for (int i = offsetMipMaps, j = 0; j < actualLevels; i++, j++) { int levelWidth = MipMapSize(j, width); int levelHeight = MipMapSize(j, height); SharpDX.DataStream ds; texture.LockRectangle(i, LockFlags.ReadOnly, out ds); texture.UnlockRectangle(i); SharpDX.DataStream ds2; offsetedTexture.LockRectangle(j, LockFlags.None, out ds2); ds2.Position = 0; ds2.Write(ds.DataPointer, 0, (int)MipMapSizeInBytes(levelWidth, levelHeight, format)); offsetedTexture.UnlockRectangle(j); } texture.Dispose(); texture = offsetedTexture; } }
private void LoadPackedGraphics(int index) { // return ; PackedTexture bigOne = _packedTextures[index]; Format useFormat = Format.A8R8G8B8; //if (IsCompressedTextureFormatOk(Format.Dxt5)) //{ // Log.Debug("TexturePacker: Using DXT5 texture format"); // useFormat = Format.Dxt5; //} if (bigOne.texture == null) { bigOne.textureNo = -1; string fileName = String.Format(@"{0}\packedgfx2{1}.png", GUIGraphicsContext.SkinCacheFolder, index); ImageInformation info2 = new ImageInformation(); Texture tex = TextureLoader.FromFile(GUIGraphicsContext.DX9Device, fileName, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, useFormat, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)0, ref info2); bigOne.texture = tex; bigOne.texture.Disposing -= new EventHandler(texture_Disposing); bigOne.texture.Disposing += new EventHandler(texture_Disposing); Log.Info("TexturePacker: Loaded {0} texture:{1}x{2} miplevels:{3}", fileName, info2.Width, info2.Height, tex.LevelCount); } }
public new void MakeTexture(Device device, string strファイル名, Format format, bool b黒を透過する, Pool pool) { if (!File.Exists(strファイル名)) // #27122 2012.1.13 from: ImageInformation では FileNotFound 例外は返ってこないので、ここで自分でチェックする。わかりやすいログのために。 { throw new FileNotFoundException(string.Format("ファイルが存在しません。\n[{0}]", strファイル名)); } Byte[] _txData = File.ReadAllBytes(strファイル名); bool b条件付きでサイズは2の累乗でなくてもOK = (device.Capabilities.TextureCaps & TextureCaps.NonPow2Conditional) != 0; bool bサイズは2の累乗でなければならない = (device.Capabilities.TextureCaps & TextureCaps.Pow2) != 0; bool b正方形でなければならない = (device.Capabilities.TextureCaps & TextureCaps.SquareOnly) != 0; // そもそもこんな最適化をしなくてよいのなら、さっさとbaseに処理を委ねて終了 if (!bサイズは2の累乗でなければならない && b条件付きでサイズは2の累乗でなくてもOK) { //Debug.WriteLine( Path.GetFileName( strファイル名 ) + ": 最適化は不要です。" ); base.MakeTexture(device, strファイル名, format, b黒を透過する, pool); return; } var information = ImageInformation.FromMemory(_txData); int orgWidth = information.Width, orgHeight = information.Height; int w = orgWidth, h = orgHeight, foldtimes; #region [ 折りたたみありで最適なテクスチャサイズがどうなるかを確認する(正方形にするかは考慮せず) ] if (orgWidth >= orgHeight) // 横長画像なら { this.b横長のテクスチャである = true; if (!GetFoldedTextureSize(ref w, ref h, out foldtimes)) { //Debug.WriteLine( Path.GetFileName( strファイル名 ) + ": 最適化を断念。" ); base.MakeTexture(device, strファイル名, format, b黒を透過する, pool); return; } } else // 縦長画像なら { this.b横長のテクスチャである = false; if (!GetFoldedTextureSize(ref h, ref w, out foldtimes)) // 縦横入れ替えて呼び出し { //Debug.WriteLine( Path.GetFileName( strファイル名 ) + ": 最適化を断念。" ); base.MakeTexture(device, strファイル名, format, b黒を透過する, pool); return; } } #endregion //Debug.WriteLine( Path.GetFileName( strファイル名 ) + ": texture最適化結果: width=" + w + ", height=" + h + ", 折りたたみ回数=" + foldtimes ); #region [ 折りたたみテクスチャ画像を作り、テクスチャ登録する ] // バイナリ(Byte配列)をBitmapに変換 MemoryStream mms = new MemoryStream(_txData); Bitmap bmpOrg = new Bitmap(mms); mms.Close(); Bitmap bmpNew = new Bitmap(w, h); Graphics g = Graphics.FromImage(bmpNew); for (int n = 0; n <= foldtimes; n++) { if (b横長のテクスチャである) { int x = n * w; int currentHeight = n * orgHeight; int currentWidth = (n < foldtimes) ? w : orgWidth - x; Rectangle r = new Rectangle(x, 0, currentWidth, orgHeight); Bitmap bmpTmp = bmpOrg.Clone(r, bmpOrg.PixelFormat); // ここがボトルネックになるようなら、後日unsafeコードにする。 g.DrawImage(bmpTmp, 0, currentHeight, currentWidth, orgHeight); bmpTmp.Dispose(); } else { int y = n * h; int currentWidth = n * orgWidth; int currentHeight = (n < foldtimes) ? h : orgHeight - y; Rectangle r = new Rectangle(0, y, orgWidth, currentHeight); Bitmap bmpTmp = bmpOrg.Clone(r, bmpOrg.PixelFormat); // ここがボトルネックになるようなら、後日unsafeコードにする。 g.DrawImage(bmpTmp, currentWidth, 0, orgWidth, currentHeight); bmpTmp.Dispose(); } } ; if (b黒を透過する) { bmpNew.MakeTransparent(Color.Black); } g.Dispose(); g = null; bmpOrg.Dispose(); bmpOrg = null; base.MakeTexture(device, bmpNew, format, b黒を透過する, pool); bmpNew.Dispose(); bmpNew = null; #endregion _orgWidth = orgWidth; _orgHeight = orgHeight; _foldtimes = foldtimes; this.sz画像サイズ = new Size(orgWidth, orgHeight); }
// TODO: Create with XOF /// <summary>Create the materials for the mesh</summary> public void CreateMaterials(string folder, Device device, GraphicsStream adjacency, ExtendedMaterial[] materials) { // Does the mesh have materials? if ((materials != null) && (materials.Length > 0)) { // Allocate the arrays for the materials meshMaterials = new Material[materials.Length]; meshTextures = new BaseTexture[materials.Length]; // Copy each material and create it's texture for(int i = 0; i < materials.Length; i++) { // Copy the material first meshMaterials[i] = materials[i].Material3D; // Is there a texture for this material? if ((materials[i].TextureFilename == null) || (materials[i].TextureFilename.Length == 0) ) continue; // No, just continue now ImageInformation info = new ImageInformation(); string textureFile = folder + materials[i].TextureFilename; try { // First look for the texture in the same folder as the input folder info = TextureLoader.ImageInformationFromFile(textureFile); } catch { try { // Couldn't find it, look in the media folder textureFile = Utility.FindMediaFile(materials[i].TextureFilename); info = TextureLoader.ImageInformationFromFile(textureFile); } catch (MediaNotFoundException) { // Couldn't find it anywhere, skip it continue; } } switch (info.ResourceType) { case ResourceType.Textures: meshTextures[i] = TextureLoader.FromFile(device, textureFile); break; case ResourceType.CubeTexture: meshTextures[i] = TextureLoader.FromCubeFile(device, textureFile); break; case ResourceType.VolumeTexture: meshTextures[i] = TextureLoader.FromVolumeFile(device, textureFile); break; } } } }
public virtual async Task <Tuple <Stream, LoadingResult, ImageInformation> > Resolve(string identifier, TaskParameter parameters, CancellationToken token) { NSBundle bundle = null; var filename = Path.GetFileNameWithoutExtension(identifier); var tmpPath = Path.GetDirectoryName(identifier).Trim('/'); var filenamePath = string.IsNullOrWhiteSpace(tmpPath) ? null : tmpPath + "/"; foreach (var fileType in fileTypes) { string file = null; var extension = Path.HasExtension(identifier) ? Path.GetExtension(identifier) : string.IsNullOrWhiteSpace(fileType) ? string.Empty : "." + fileType; token.ThrowIfCancellationRequested(); int scale = (int)ScaleHelper.Scale; if (scale > 1) { while (scale > 1) { token.ThrowIfCancellationRequested(); var tmpFile = string.Format("{0}@{1}x{2}", filename, scale, extension); bundle = NSBundle._AllBundles.FirstOrDefault(bu => { var path = string.IsNullOrWhiteSpace(filenamePath) ? bu.PathForResource(tmpFile, null) : bu.PathForResource(tmpFile, null, filenamePath); return(!string.IsNullOrWhiteSpace(path)); }); if (bundle != null) { file = tmpFile; break; } scale--; } } token.ThrowIfCancellationRequested(); if (file == null) { var tmpFile = string.Format(filename + extension); file = tmpFile; bundle = NSBundle._AllBundles.FirstOrDefault(bu => { var path = string.IsNullOrWhiteSpace(filenamePath) ? bu.PathForResource(tmpFile, null) : bu.PathForResource(tmpFile, null, filenamePath); return(!string.IsNullOrWhiteSpace(path)); }); } token.ThrowIfCancellationRequested(); if (bundle != null) { string path = !string.IsNullOrEmpty(filenamePath) ? bundle.PathForResource(file, null, filenamePath) : bundle.PathForResource(file, null); var stream = FileStore.GetInputStream(path, true); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(path); return(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation)); } token.ThrowIfCancellationRequested(); if (string.IsNullOrEmpty(fileType)) { //Asset catalog NSDataAsset asset = null; try { await MainThreadDispatcher.Instance.PostAsync(() => asset = new NSDataAsset(filename)).ConfigureAwait(false); } catch (Exception) { } if (asset != null) { token.ThrowIfCancellationRequested(); var stream = asset.Data?.AsStream(); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); return(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation)); } NSImage image = null; try { await MainThreadDispatcher.Instance.PostAsync(() => image = NSImage.ImageNamed(filename)).ConfigureAwait(false); } catch (Exception) { } if (image != null) { token.ThrowIfCancellationRequested(); var imageRep = new NSBitmapImageRep(image.AsTiff()); var stream = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png) .AsStream(); //var stream = image.AsPNG()?.AsStream(); var imageInformation = new ImageInformation(); imageInformation.SetPath(identifier); imageInformation.SetFilePath(null); return(new Tuple <Stream, LoadingResult, ImageInformation>( stream, LoadingResult.CompiledResource, imageInformation)); } } } throw new FileNotFoundException(identifier); }
public static int LoadFromMemoryEx(Image memoryImage, string name, long lColorKey, out Texture texture) { Log.Debug("TextureManagerEx: load from memory: {0}", name); string cacheName = name; string cacheKey = cacheName.ToLowerInvariant(); texture = null; CachedTexture cached; if (_cacheTextures.TryGetValue(cacheKey, out cached)) { return cached.Frames; } if (memoryImage == null) { return 0; } try { CachedTexture newCache = new CachedTexture(); newCache.Name = cacheName; newCache.Frames = 1; //load gif into texture using (MemoryStream stream = new MemoryStream()) { memoryImage.Save(stream, ImageFormat.Png); ImageInformation info2 = new ImageInformation(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); texture = TextureLoader.FromStream( GUIGraphicsContext.DX9Device, stream, 0, 0, //width/height 1, //mipslevels Usage.Dynamic, //Usage.Dynamic, Format.A8R8G8B8, Pool.Default, Filter.None, Filter.None, (int)lColorKey, ref info2); newCache.Width = info2.Width; newCache.Height = info2.Height; newCache.Texture = new TextureFrame(cacheName, texture, 0); } newCache.Disposed += new EventHandler(cachedTexture_Disposed); _cacheTextures[cacheKey] = newCache; Log.Debug("TextureManager: added: memoryImage " + " total count: " + _cacheTextures.Count + ", mem left (MB): " + ((uint)GUIGraphicsContext.DX9Device.AvailableTextureMemory / 1048576)); return newCache.Frames; } catch (Exception ex) { Log.Error("TextureManager: exception loading texture memoryImage"); Log.Error(ex); } return 0; }
public async static Task <byte[]> RetrieveOriginalImageFromObjectStorageAsync(ImageInformation image) { StorageAccountSettings storageAccountSettings = Common.CurrentStorageAccountSettings; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountSettings.ConnectionString); CloudBlobClient client = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = client.GetContainerReference(storageAccountSettings.UploadsContainerName); CloudBlockBlob blob = null; byte[] originalImageBytes = null; bool blobExists = false; try { blob = container.GetBlockBlobReference(image.FileName); blobExists = await blob.ExistsAsync(); if (blobExists) { originalImageBytes = new byte[blob.StreamWriteSizeInBytes]; await blob.DownloadToByteArrayAsync(originalImageBytes, 0); } } catch (Exception ex) { } return(originalImageBytes); }
public static int Load(string fileNameOrg, long lColorKey, int iMaxWidth, int iMaxHeight, bool persistent) { string fileName = GetFileName(fileNameOrg); string cacheKey = fileName.ToLowerInvariant(); if (String.IsNullOrEmpty(fileName)) { return 0; } CachedTexture cached; if (_cacheTextures.TryGetValue(cacheKey, out cached)) { return cached.Frames; } string extension = Path.GetExtension(fileName).ToLowerInvariant(); if (extension == ".gif") { Image theImage = null; try { try { theImage = ImageFast.FromFile(fileName); } catch (FileNotFoundException) { Log.Warn("TextureManager: texture: {0} does not exist", fileName); return 0; } catch (Exception) { Log.Warn("TextureManager: Fast loading texture {0} failed using safer fallback", fileName); theImage = Image.FromFile(fileName); } if (theImage != null) { CachedTexture newCache = new CachedTexture(); newCache.Name = fileName; FrameDimension oDimension = new FrameDimension(theImage.FrameDimensionsList[0]); newCache.Frames = theImage.GetFrameCount(oDimension); int[] frameDelay = new int[newCache.Frames]; for (int num2 = 0; (num2 < newCache.Frames); ++num2) { frameDelay[num2] = 0; } // Getting Frame duration of an animated Gif image try { int num1 = 20736; PropertyItem item1 = theImage.GetPropertyItem(num1); if (item1 != null) { byte[] buffer1 = item1.Value; for (int num2 = 0; (num2 < newCache.Frames); ++num2) { frameDelay[num2] = (((buffer1[(num2 * 4)] + (256 * buffer1[((num2 * 4) + 1)])) + (65536 * buffer1[((num2 * 4) + 2)])) + (16777216 * buffer1[((num2 * 4) + 3)])); } } } catch (Exception) { } for (int i = 0; i < newCache.Frames; ++i) { theImage.SelectActiveFrame(oDimension, i); //load gif into texture using (MemoryStream stream = new MemoryStream()) { theImage.Save(stream, ImageFormat.Png); ImageInformation info2 = new ImageInformation(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); Texture texture = TextureLoader.FromStream( GUIGraphicsContext.DX9Device, stream, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, Format.A8R8G8B8, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)lColorKey, ref info2); newCache.Width = info2.Width; newCache.Height = info2.Height; newCache[i] = new TextureFrame(fileName, texture, (frameDelay[i] / 5) * 50); } } theImage.SafeDispose(); theImage = null; newCache.Disposed += new EventHandler(cachedTexture_Disposed); if (persistent && !_persistentTextures.ContainsKey(cacheKey)) { _persistentTextures[cacheKey] = true; } _cacheTextures[cacheKey] = newCache; //Log.Info(" TextureManager:added:" + fileName + " total:" + _cache.Count + " mem left:" + GUIGraphicsContext.DX9Device.AvailableTextureMemory.ToString()); return newCache.Frames; } } catch (Exception ex) { Log.Error("TextureManager: exception loading texture {0}", fileName); Log.Error(ex); } return 0; } try { int width, height; if (MediaPortal.Util.Utils.FileExistsInCache(fileName)) { Texture dxtexture = LoadGraphic(fileName, lColorKey, iMaxWidth, iMaxHeight, out width, out height); if (dxtexture != null) { CachedTexture newCache = new CachedTexture(); newCache.Name = fileName; newCache.Frames = 1; newCache.Width = width; newCache.Height = height; newCache.Texture = new TextureFrame(fileName, dxtexture, 0); newCache.Disposed += new EventHandler(cachedTexture_Disposed); if (persistent && !_persistentTextures.ContainsKey(cacheKey)) { _persistentTextures[cacheKey] = true; } _cacheTextures[cacheKey] = newCache; return 1; } } } catch (Exception) { return 0; } return 0; }