/// <summary> /// Loads an Image from a File by invoking GDI Plus instead of using build-in .NET methods, or falls back to Image.FromFile /// Can perform up to 10x faster /// </summary> /// <param name="filename">The filename to load</param> /// <returns>A .NET Image object</returns> public static Image LoadImageFastFromFile(string filename) { filename = Path.GetFullPath(filename); if (!File.Exists(filename)) { return(null); } Image imageFile = null; try { try { imageFile = ImageFast.FromFile(filename); } catch (Exception) { Logger.Debug("LoadImageFastFromFile: Reverting to slow ImageLoading for: " + filename); imageFile = Image.FromFile(filename); } } catch (FileNotFoundException fe) { Logger.Debug("LoadImageFastFromFile: Image does not exist: " + filename + " - " + fe.Message); return(null); } catch (Exception e) { // this probably means the image is bad Logger.Debug("LoadImageFastFromFile: Unable to load Imagefile (corrupt?): " + filename + " - " + e.Message); return(null); } return(imageFile); }
protected void SetImageToGui(string imageFilePath) { if (string.IsNullOrEmpty(imageFilePath)) { return; } string texture = GetTextureFromFile(imageFilePath); if (GUITextureManager.LoadFromMemory(ImageFast.FromFile(imageFilePath), texture, 0, 0, 0) > 0) { ThumbnailImage = texture; IconImage = texture; IconImageBig = texture; } // if selected and GUIActors is current window force an update of thumbnail GUIActors actorWindow = GUIWindowManager.GetWindow(GUIWindowManager.ActiveWindow) as GUIActors; if (actorWindow != null) { GUIListItem selectedItem = GUIControl.GetSelectedListItem(9816, 50); if (selectedItem == this) { GUIWindowManager.SendThreadMessage(new GUIMessage(GUIMessage.MessageType.GUI_MSG_ITEM_SELECT, GUIWindowManager.ActiveWindow, 0, 50, ItemId, 0, null)); } } }
/// <summary> /// /// </summary> /// <param name="imageFile"></param> /// <param name="faceSize"></param> /// <returns></returns> private Image MaskFace(string imageFile, int faceSize = 20) { //using ( Image image = Accord.Imaging.Image.FromFile( imageFile ) ) using (Image image = ImageFast.FromFile(imageFile)) { return(MaskFace(ResizeImage(RotateImage(image), OutSize), faceSize)); } }
private bool AddBitmap(PackedTextureNode root, Image rootImage, string file, out bool dontAdd) { bool result = false; dontAdd = false; Image bmp = null; try { bmp = ImageFast.FromFile(file); } catch (Exception) { Log.Warn("TexturePacker: Fast loading of texture {0} failed - trying safe fallback now", file); bmp = Image.FromFile(file); } //if (bmp.Width >= GUIGraphicsContext.Width || bmp.Height >= GUIGraphicsContext.Height) if (bmp.Width > (_maxTextureHeight / 2) || bmp.Height > (_maxTextureWidth / 2)) { Log.Warn("TexturePacker: Texture {0} is too large to be cached. Texture {1}x{2} - limit {3}x{4}", file, bmp.Width, bmp.Height, _maxTextureHeight, _maxTextureWidth); dontAdd = true; return(false); } string skinName = String.Format(@"{0}\media", GUIGraphicsContext.Skin).ToLower(); int pos = file.IndexOf(skinName); if (pos >= 0) { file = file.Remove(pos, skinName.Length); } string themeName = String.Format(@"{0}\themes", GUIGraphicsContext.Skin).ToLower(); pos = file.IndexOf(themeName); if (pos >= 0) { file = file.Remove(pos, themeName.Length); } if (file.StartsWith(@"\")) { file = file.Remove(0, 1); } result = Add(root, bmp, rootImage, file); bmp.SafeDispose(); bmp = null; return(result); }
public void BeginPaint(gView.Framework.Carto.IDisplay display, ICancelTracker cancelTracker) { try { byte[] buffer = new byte[_header.streamLength]; _stream.Position = _header.startPosition; _stream.Read(buffer, 0, _header.streamLength); _bm = (System.Drawing.Bitmap)ImageFast.FromStream(buffer); } catch { EndPaint(cancelTracker); } }
/// <summary> /// Loads an image FAST from file /// </summary> /// <param name="filename"></param> /// <returns></returns> public static Image LoadImage(string file) { if (string.IsNullOrEmpty(file) || !File.Exists(file)) { return(null); } Image img = null; try { img = ImageFast.FromFile(file); } catch { // Most likely a Zero Byte file but not always TraktLogger.Warning("Fast loading of texture {0} failed - trying safe fallback now", file); try { img = Image.FromFile(file); } catch { } } return(img); }
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 CachedTexture.Frame(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} - {1}", fileName, ex.Message); } 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 CachedTexture.Frame(fileName, dxtexture, 0); //Log.Info(" texturemanager:added:" + fileName + " total:" + _cache.Count + " mem left:" + GUIGraphicsContext.DX9Device.AvailableTextureMemory.ToString()); 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); }
private static Texture LoadGraphic(string fileName, long lColorKey, int iMaxWidth, int iMaxHeight, out int width, out int height) { width = 0; height = 0; #if DO_RESAMPLE Image imgSrc = null; #endif 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 ?? { Log.Debug("TextureManager: LoadGraphic - {0} error {1}, trying copy to Image first", fileName, e1.Message); using (Stream str = new MemoryStream()) { using (Image image = ImageFast.FromFile(fileName)) using (Bitmap result = new Bitmap(image.Width, image.Height)) using (Graphics g = Graphics.FromImage(result)) { g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); result.Save(str, ImageFormat.Png); } str.Position = 0; try { ImageInformation info2 = new ImageInformation(); texture = TextureLoader.FromStream(GUIGraphicsContext.DX9Device, str, 0, 0, //width/height 1, //mipslevels 0, //Usage.Dynamic, Format.A8R8G8B8, GUIGraphicsContext.GetTexturePoolType(), Filter.None, Filter.None, (int)lColorKey, ref info2); width = info2.Width; height = info2.Height; } catch (Exception e2) { //we need to catch this on higer level. throw e2; } } } catch (Exception ex) { Log.Error("TextureManager: LoadGraphic - invalid thumb({0}) {1}", fileName, ex.Message); 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; } #if DO_RESAMPLE finally { if (imgSrc != null) { imgSrc.SafeDispose(); } } #endif return(texture); }
private void ReadData(Image img, int[] StartEnd, int JumpX, int JumpY, int MinColorDiff, bool NoWhite, bool Wait) { //get image data to read faster ImageFast fast = new ImageFast(new Bitmap(img)); fast.LockBits(); //create dictionary with x/y coordinates and RGB colors Dictionary <string, List <int[]> > map = new Dictionary <string, List <int[]> >(); List <string> ColorHistory = new List <string>(); int[] lastRGB = { 0, 0, 0 }; //start reading image for (int x = StartEnd[0]; x < StartEnd[2]; x += JumpX) { for (int y = StartEnd[1]; y < StartEnd[3]; y += JumpY) { //get pixel rgb and check if is white int[] newRGB = fast.GetPixel(x, y); if (newRGB[0] > 230 && newRGB[1] > 230 && newRGB[2] > 230 && NoWhite) { continue; } lastRGB = newRGB; int lastDiff = 999999; foreach (string color in ColorHistory) { //check if color is in history int diff = RGBdiff(GetRGBFromString(color), newRGB); if (diff < MinColorDiff && diff < lastDiff) { if (diff < MinColorDiff && diff < lastDiff) { //if color is in history, change color to match lastDiff = diff; lastRGB = GetRGBFromString(color); } } } //add coordinates to current color List <int[]> cords = new List <int[]>(); if (map.ContainsKey(GetStringFromRGB(lastRGB))) { cords = map[GetStringFromRGB(lastRGB)]; cords.Add(new[] { x, y }); map[GetStringFromRGB(lastRGB)] = cords; } else { ColorHistory.Add(GetStringFromRGB(lastRGB)); map.Add(GetStringFromRGB(lastRGB), cords); } } } //end image read readedData.Add(map); Debug.WriteLine(string.Format("Thread {0} stopped.", currentThreads)); currentThreads -= 1; while (Wait) { if (currentThreads <= 0) { ReadEnded(); break; } } }
private void button1_Click(object sender, EventArgs e) { lbutton.Enabled = false; if (filenames.Count() == 0) { MessageBox.Show("No more images to show in directory", "All Done!"); actual.Text = ""; } iCount.Text = "Items: " + filenames.Count().ToString(); if (filenames.Count() >= 500) { maxImagesToShow = 500; } else { maxImagesToShow = filenames.Count(); } try { foreach (PictureBox pic in PictureBoxes) { pic.Dispose(); } flpThumbnails.Controls.Clear(); PictureBoxes = new List <PictureBox>(); for (int i = 0; i < maxImagesToShow; i++) { var filename = filenames[i]; PictureBox pic = new PictureBox(); int y = 200; int x = 200; pic.ClientSize = new Size(x, y); pic.Image = ImageFast.FromFile(filename); // If the image is too big, zoom. if ((pic.Image.Width > x) || (pic.Image.Height > y)) { pic.SizeMode = PictureBoxSizeMode.Zoom; } else { pic.SizeMode = PictureBoxSizeMode.CenterImage; } Label warn = new Label(); pic.BorderStyle = BorderStyle.FixedSingle; if (filename.Contains("logo")) { warn.Parent = pic; warn.ForeColor = Color.Red; warn.BackColor = Color.Black; warn.Font = new Font(DefaultFont, FontStyle.Bold); warn.Text = "LOGO"; warn.BringToFront(); } if (filename.Contains("flag")) { warn.Parent = pic; warn.ForeColor = Color.Red; warn.BackColor = Color.Black; warn.Font = new Font(DefaultFont, FontStyle.Bold); warn.Text = "FLAG"; warn.BringToFront(); } if (filename.Contains("prop")) { warn.Parent = pic; warn.ForeColor = Color.Red; warn.BackColor = Color.Black; warn.Font = new Font(DefaultFont, FontStyle.Bold); warn.Text = "PROP65"; warn.BringToFront(); } // Add a tooltip. FileInfo file_info = new FileInfo(filename); tipPicture.SetToolTip(pic, file_info.Name); pic.Tag = file_info; // Add the PictureBox to the FlowLayoutPanel. pic.Parent = flpThumbnails; int act = i + 1; actual.Text = act.ToString(); Application.DoEvents(); Thread.Sleep(10); } if (filenames.Count() >= 500) { filenames.RemoveRange(0, 500); } else { filenames.RemoveRange(0, filenames.Count()); } lbutton.Enabled = true; //handle lbutton { if (filenames.Count() >= 500) { lbutton.Text = "Load (500)"; } if (filenames.Count() < 500) { lbutton.Text = "Load (" + filenames.Count().ToString() + ")"; } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Oops! Something went wrong..."); } }