private static BitmapFrame ConvertFromIcon(Icon icon)
		{
			var memoryStream = new MemoryStream();
			icon.Save(memoryStream);
			memoryStream.Seek(0, SeekOrigin.Begin);
			return BitmapFrame.Create(memoryStream);
		}  
Ejemplo n.º 2
0
 Bitmap ExtractVistaIcon(Icon icoIcon)
 {
     Bitmap bmpPngExtracted = null;
     try
     {
         byte[] srcBuf = null;
         using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
         { icoIcon.Save(stream); srcBuf = stream.ToArray(); }
         const int SizeICONDIR = 6;
         const int SizeICONDIRENTRY = 16;
         int iCount = BitConverter.ToInt16(srcBuf, 4);
         for (int iIndex = 0; iIndex < iCount; iIndex++)
         {
             int iWidth = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex];
             int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1];
             int iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6);
             if (iWidth == 0 && iHeight == 0 && iBitCount == 32)
             {
                 int iImageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8);
                 int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12);
                 System.IO.MemoryStream destStream = new System.IO.MemoryStream();
                 System.IO.BinaryWriter writer = new System.IO.BinaryWriter(destStream);
                 writer.Write(srcBuf, iImageOffset, iImageSize);
                 destStream.Seek(0, System.IO.SeekOrigin.Begin);
                 bmpPngExtracted = new Bitmap(destStream); // This is PNG! :)
                 break;
             }
         }
     }
     catch { return null; }
     return bmpPngExtracted;
 }
Ejemplo n.º 3
0
 private static ImageSource ToImageSource(System.Drawing.Icon icon)
 {
     using var ms = new MemoryStream();
     icon.Save(ms);
     ms.Position = 0;
     return(BitmapFrame.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad));
 }
Ejemplo n.º 4
0
        private void btn_Manually_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog open = new OpenFileDialog())
            {
                open.Filter = "Game Executable|*.exe";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    string path = open.FileName;
                    Bitmap icon;
                    string key = Path.GetDirectoryName(path);
                    if (!imageList1.Images.ContainsKey(key))
                    {
                        using (System.Drawing.Icon sysicon = Icon.ExtractAssociatedIcon(path))
                        {
                            using (MemoryStream str = new MemoryStream())
                            {
                                sysicon.Save(str);
                                str.Position = 0;
                                icon         = (Bitmap)Image.FromStream(str);
                            }
                        }
                        this.imageList1.Images.Add(key, icon);
                    }

                    ListViewItem item = new ListViewItem(open.FileName, key);
                    this.list_Games.Items.Add(item);
                }
            }
        }
Ejemplo n.º 5
0
 public static byte[] IconToBytes(Icon icon)
 {
     using (var ms = new MemoryStream())
     {
         icon.Save(ms);
         return ms.ToArray();
     }
 }
Ejemplo n.º 6
0
 private byte[] GetIconBytes(Icon icon)
 {
     using (var ms = new MemoryStream())
     {
         icon.Save(ms);
         ms.Flush();
         return ms.GetBuffer();
     }
 }
Ejemplo n.º 7
0
        public static void ShowNotify(string header, string content, NotifyDuration duration     = NotifyDuration.Long,
                                      TypedEventHandler <ToastNotification, object> activateFunc = null,
                                      TypedEventHandler <ToastNotification, ToastDismissedEventArgs> dismissFunc = null,
                                      TypedEventHandler <ToastNotification, ToastFailedEventArgs> failFunc       = null, string iconPath = "", string APP_ID = "")
        {
            ComponentResourceManager resources = new ComponentResourceManager(typeof(frmMain));

            System.Drawing.Icon icon = (System.Drawing.Icon)resources.GetObject("$this.Icon");

            string filepath = Path.Combine(Environment.ExpandEnvironmentVariables(@"%AppData%"), "FoBots");

            Directory.CreateDirectory(filepath);
            if (!File.Exists(Path.Combine(filepath, "icon.ico")))
            {
                FileStream outStream = File.Create(Path.Combine(filepath, "icon.ico"));
                icon.Save(outStream);
                outStream.Flush();
                outStream.Close();
            }
            iconPath = Path.Combine(filepath, "icon.ico");
            ToastTemplateType toastTemplate     = ToastTemplateType.ToastImageAndText02;
            XmlDocument       toastXml          = ToastNotificationManager.GetTemplateContent(toastTemplate);
            XmlNodeList       toastTextElements = toastXml.GetElementsByTagName("text");

            toastTextElements[0].AppendChild(toastXml.CreateTextNode(header));
            toastTextElements[1].AppendChild(toastXml.CreateTextNode(content));
            XmlNodeList toastImageElements = toastXml.GetElementsByTagName("image");

            ((XmlElement)toastImageElements[0]).SetAttribute("src", iconPath);
            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");

            ((XmlElement)toastNode).SetAttribute("duration", Enum.GetName(typeof(NotifyDuration), duration));
            ToastNotification toast = new ToastNotification(toastXml);

            toast.Activated += activateFunc ?? ToastActivated;
            toast.Dismissed += dismissFunc ?? ToastDismissed;
            toast.Failed    += failFunc ?? ToastFailed;
            try
            {
                if (TryCreateShortcut(APP_ID))
                {
                    ToastNotificationManager.CreateToastNotifier(APP_ID + NotID).Show(toast);
                }
            }
            catch (Exception ex)
            {
                NLog.LogManager.Flush();
                var attachments = new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText(File.ReadAllText("log.foblog"), "log.foblog") };
                var properties  = new Dictionary <string, string> {
                    { "ShowNotify", i18n.getString("ShowingNotify") }
                };
                Crashes.TrackError(ex, properties, attachments);
            }
        }
Ejemplo n.º 8
0
        public IconHandler(sd.Icon icon)
        {
            var rect = new sw.Int32Rect(0, 0, icon.Width, icon.Height);
            var img  = swi.Imaging.CreateBitmapSourceFromHIcon(icon.Handle, rect, swmi.BitmapSizeOptions.FromEmptyOptions());

            Control = swmi.BitmapFrame.Create(img);
            using (var ms = new MemoryStream())
            {
                icon.Save(ms);
                ms.Position = 0;
                SetFrames(ms);
            }
        }
Ejemplo n.º 9
0
        private static Bitmap ExtractVistaIcon(Icon icon)
        {
            Bitmap extractedIcon = null;

            if (icon == null)
            {
                return extractedIcon;
            }

            try
            {
                byte[] srcBuf = null;
                using (var stream = new MemoryStream())
                {
                    icon.Save(stream);
                    srcBuf = stream.ToArray();
                }

                const int SizeICONDIR = 6;
                const int SizeICONDIRENTRY = 16;
                int iCount = BitConverter.ToInt16(srcBuf, 4);
                for (int iIndex = 0; iIndex < iCount; iIndex++)
                {
                    int width = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex];
                    int height = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1];
                    int bitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6);

                    if (width == 0 && height == 0 && bitCount == 32)
                    {
                        int imageSize = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 8);
                        int imageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 12);
                        using (var destStream = new MemoryStream())
                        {
                            var writer = new BinaryWriter(destStream);
                            writer.Write(srcBuf, imageOffset, imageSize);
                            destStream.Seek(0, SeekOrigin.Begin);

                            extractedIcon = new Bitmap(destStream); // This is PNG! :)
                            return extractedIcon;
                        }
                    }
                }
            }
            catch
            {
                return null;

            }

            return extractedIcon;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Converts the specified icon into a bitmap
        /// </summary>
        /// <param name="icon">icon to convert</param>
        /// <returns>bitmap representation of icon</returns>
        public static Bitmap ConvertIconToBitmap(Icon icon)
        {
            if (icon != null)
            {
                using (var memoryStream = new MemoryStream())
                {
                    icon.Save(memoryStream);
                    using (var bitmap = (Bitmap)Image.FromStream(memoryStream))
                    {
                        return new Bitmap(bitmap);
                    }
                }
            }

            return null;
        }
Ejemplo n.º 11
0
 public string IconToBytes(Icon icon)
 {
     try
     {
         using (MemoryStream ms = new MemoryStream())
         {
             icon.Save(ms);
             byte[] bytes = ms.ToArray();
             return Convert.ToBase64String(bytes);
         }
     }
     catch (Exception e)
     {
         return "";
     }
 }
Ejemplo n.º 12
0
        public static BitmapImage IconToBitmapImage(System.Drawing.Icon ico)
        {
            MemoryStream ms = new MemoryStream();

            ico.Save(ms);
            BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();

            bImg.BeginInit();
            bImg.StreamSource  = new MemoryStream(ms.ToArray());
            bImg.CreateOptions = BitmapCreateOptions.None;
            bImg.CacheOption   = BitmapCacheOption.Default;
            bImg.EndInit();

            ms.Close();

            return(bImg);
        }
Ejemplo n.º 13
0
        private void btnSaveIcon_Click(object sender, EventArgs e)
        {
            if (picSource.Image != null)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title  = "Specify a file name and file path";
                sfd.Filter = "Icon Files(*.ico)|*.ico";

                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    System.Drawing.Icon tempIcon = ((Bitmap)picSource.Image).CreateIcon(
                        (IconSizeDimensions)cmbIconSize.SelectedItem);

                    using (StreamWriter streamWriter = new StreamWriter(sfd.FileName, false))
                    {
                        tempIcon.Save(streamWriter.BaseStream);

                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                }
            }
        }
Ejemplo n.º 14
0
        private void SavePicture(string S_Name)
        {
            string[] arry     = S_Name.Split('.');
            Bitmap   Bmp      = new Bitmap((Bitmap)Image.FromFile(textBox1.Text + "\\" + S_Name), int.Parse(textBox3.Text), int.Parse(textBox4.Text));
            string   SaveName = textBox2.Text + "\\";

            IfNotFileCreat(SaveName);
            SaveName += (arry[0] + "." + SaveType);
            switch (SaveType)
            {
            case "Png": Bmp.Save(SaveName, ImageFormat.Png); break;

            case "Ico": Bmp.Save(SaveName, ImageFormat.Icon);
                System.Drawing.Icon  icon       = System.Drawing.Icon.FromHandle(Bmp.GetHicon());
                System.IO.FileStream fileStream = new System.IO.FileStream(SaveName, System.IO.FileMode.Create);
                icon.Save(fileStream);
                Bmp.Dispose();
                fileStream.Close();
                fileStream.Dispose();
                icon.Dispose();
                break;

            case "Emf": Bmp.Save(SaveName, ImageFormat.Emf); break;

            case "Jpg": Bmp.Save(SaveName, ImageFormat.Jpeg); break;

            case "Wmf": Bmp.Save(SaveName, ImageFormat.Wmf); break;

            case "Gif": Bmp.Save(SaveName, ImageFormat.Gif); break;

            case "Exif": Bmp.Save(SaveName, ImageFormat.Exif); break;

            case "Bmp": Bmp.Save(SaveName, ImageFormat.Bmp); break;

            default: break;
            }
        }
Ejemplo n.º 15
0
        public static AddinInstallerFile Build(string license, List<string> dependencies, string assembly, Icon icon)
        {
            var ret = new AddinInstallerFile();
            ret.License = license;

            if (icon != null)
            {
                var ims = new MemoryStream();
                icon.Save(ims);
                ret.Icon = ims.ToArray();
            }

            if (dependencies != null)
            {
                foreach (var dependency in dependencies)
                {
                    ret.Dependecies.Add(Path.GetFileName(dependency), File.ReadAllBytes(dependency));
                }
            }

            ret.Assembly = new KeyValuePair<string, byte[]>(Path.GetFileName(assembly), File.ReadAllBytes(assembly));

            return ret;
        }
Ejemplo n.º 16
0
		internal static void SaveAndCompare (string msg, Icon icon, bool alpha)
		{
			using (MemoryStream ms = new MemoryStream ()) {
				icon.Save (ms);
				ms.Position = 0;

				using (Icon loaded = new Icon (ms)) {
					Assert.AreEqual (icon.Height, loaded.Height, msg + ".Loaded.Height");
					Assert.AreEqual (icon.Width, loaded.Width, msg + ".Loaded.Width");

					using (Bitmap expected = icon.ToBitmap ()) {
						using (Bitmap actual = loaded.ToBitmap ()) {
							Assert.AreEqual (expected.Height, actual.Height, msg + ".Bitmap.Height");
							Assert.AreEqual (expected.Width, actual.Width, msg + ".Bitmap.Width");

							for (int y = 0; y < expected.Height; y++) {
								for (int x = 0; x < expected.Width; x++) {
									Color e = expected.GetPixel (x, y);
									Color a = actual.GetPixel (x, y);
									if (alpha)
										Assert.AreEqual (e.A, a.A, String.Format ("{0}:{1}x{2}:A", msg, x, y));
									Assert.AreEqual (e.R, a.R, String.Format ("{0}:{1}x{2}:R", msg, x, y));
									Assert.AreEqual (e.G, a.G, String.Format ("{0}:{1}x{2}:G", msg, x, y));
									Assert.AreEqual (e.B, a.B, String.Format ("{0}:{1}x{2}:B", msg, x, y));
								}
							}
						}
					}
				}
			}
		}
Ejemplo n.º 17
0
 /// <summary>
 /// convert Icon to base64 string </summary>
 public static string IconToString(Icon icon)
 {
     try
     {
         using (MemoryStream ms = new MemoryStream())
         {
             icon.Save(ms);
             byte[] bytes = ms.ToArray();
             return Convert.ToBase64String(bytes);
         }
     }
     catch (Exception e)
     {
         Program.log.write("IconToString error: " + e.Message);
         return "";
     }
 }
Ejemplo n.º 18
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }

            if (destinationType == typeof(Image) || destinationType == typeof(Bitmap))
            {
                Icon icon = value as Icon;
                if (icon != null)
                {
                    return(icon.ToBitmap());
                }
            }
            if (destinationType == typeof(string))
            {
                if (value != null)
                {
                    return(value.ToString());
                }
                else
                {
                    return(SR.GetString(SR.toStringNone));
                }
            }
            if (destinationType == typeof(byte[]))
            {
                if (value != null)
                {
                    MemoryStream ms = null;
                    try {
                        ms = new MemoryStream();
                        Icon icon = value as Icon;
                        if (icon != null)
                        {
                            icon.Save(ms);
                        }
                    }
                    finally {
                        if (ms != null)
                        {
                            ms.Close();
                        }
                    }
                    if (ms != null)
                    {
                        return(ms.ToArray());
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(new byte[0]);
                }
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
		private void CreateIcon(string path, bool useDefault = true) {
			var str = Legacy.UserSettings.ImageDir + @"\" + g.FileSafeTitle + ".ico";
			if (useDefault) {
				using (var stream = new FileStream(str, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
					Properties.Resources.icon.Save(stream);
					return;
				}
			}
			var icon = new Icon(path);
			using (var stream2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
				icon.Save(stream2);
				icon.Dispose();
			}
		}
Ejemplo n.º 20
0
 private void CreateIcon(String name, Icon icon)
 {
     using (Stream iconStream = new FileStream(name, FileMode.Create))
     {
         icon.Save(iconStream);
     }
     icon.Dispose();
 }
        private int SaveStreamResource(string resName, Stream s, string saveDir)
        {
            if (s == null)
                return 0;

            int count = 0;
            bool handled = false;
            string outputFile = GetOutputResourceFile(resName, saveDir);

            if (PathUtils.IsIconExt(outputFile))
            {
                try
                {
                    if (s.CanSeek)
                        s.Seek(0, SeekOrigin.Begin);
                    Icon ico = new Icon(s);
                    using (FileStream fs = File.Create(outputFile))
                    {
                        ico.Save(fs);
                    }
                    count++;
                    handled = true;
                }
                catch (ArgumentException) { }
            }
            else if (PathUtils.IsCursorExt(outputFile))
            {
                try
                {
                    //it seems there is no easy way to write cursor to file
                    //http://msdn.microsoft.com/en-us/library/ms997538.aspx
                    Cursor c = LoadCursor(s);
                    Bitmap bmp = ConvertToBitmap(c);
                    bmp.Save(outputFile + GetImageExt(bmp));
                    count++;
                    handled = true;
                }
                catch (Exception ex)
                {
                    _form.SetStatusText(String.Format("Failed to save {0}: {1}", resName, ex.Message));
                }                
            }
            else if (ResourceFile.Default.IsImageResource(outputFile))
            {
                try
                {
                    Bitmap bmp = new Bitmap(s);
                    bmp.Save(outputFile);
                    count++;
                    handled = true;
                }
                catch (ArgumentException) { }
            }
            else if (PathUtils.IsBamlExt(outputFile))
            {
                try
                {
                    string newOutputFile = Path.ChangeExtension(outputFile, ".xaml");
                    using (StreamWriter sw = File.CreateText(newOutputFile))
                    {
                        sw.WriteLine(DecompileBaml(s));
                    }
                    count++;
                    //handled = true; 
                }
                catch (Exception ex)
                {
                    _form.SetStatusText(String.Format("Failed to translate {0}: {1}", resName, ex.Message));
                }
            }

            if (!handled)
            {
                byte[] buffer = new byte[s.Length];
                if (s.CanSeek)
                {
                    s.Seek(0, SeekOrigin.Begin);
                }
                s.Read(buffer, 0, buffer.Length);
                using (FileStream fs = File.Create(outputFile))
                {
                    fs.Write(buffer, 0, buffer.Length);
                }
                count++;
            }

            return count;
        }
Ejemplo n.º 22
0
		[Test] // bug #410608
		public void Save_256 ()
		{
			string filepath = TestBitmap.getInFile ("bitmaps/323511.ico");

			using (Icon icon = new Icon (filepath)) {
				// bug #415809 fixed
				SaveAndCompare ("256", icon, true);
			}

			// binary comparison
			var orig = new MemoryStream (File.ReadAllBytes (filepath));
			var saved = new MemoryStream ();
			using (Icon icon = new Icon (filepath))
				icon.Save (saved);
			FileAssert.AreEqual (orig, saved, "binary comparison");
		}
Ejemplo n.º 23
0
        private int GetIconBitDepth(Icon icon)
        {
            if (icon == null)
            {
                throw new ArgumentNullException("icon");
            }

            byte[] data = null;
            using (MemoryStream stream = new MemoryStream())
            {
                icon.Save(stream);
                data = stream.ToArray();
            }

            return BitConverter.ToInt16(data, 12);
        }
Ejemplo n.º 24
0
        public static Bitmap ToBitmap(this Icon icon, int maxWidth, int maxHeight = -1,
                                      int maxDepth = 32, int minWidth = 1, int minHeight = -1, int minDepth = 1)
        {
            int matchingIndex  = -1;
            int matchingWidth  = 0;
            int matchingHeight = 0;
            int matchingDepth  = 0;

            if (maxHeight < 0)
            {
                maxHeight = maxWidth;
            }
            if (minHeight < 0)
            {
                minHeight = minWidth;
            }

            byte[] srcBuf = null;
            using (MemoryStream readStream = new MemoryStream())
            { icon.Save(readStream); srcBuf = readStream.ToArray(); }
            const int SizeICONDIR      = 6;
            const int SizeICONDIRENTRY = 16;
            int       iCount           = BitConverter.ToInt16(srcBuf, 4);

            for (int iIndex = 0; iIndex < iCount; iIndex++)
            {
                int iWidth  = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex];
                int iHeight = srcBuf[SizeICONDIR + SizeICONDIRENTRY * iIndex + 1];
                if (iWidth == 0)
                {
                    iWidth = 256;
                }
                if (iHeight == 0)
                {
                    iHeight = 256;
                }
                var iBitCount = BitConverter.ToInt16(srcBuf, SizeICONDIR + SizeICONDIRENTRY * iIndex + 6);
                if (iWidth < minWidth || iWidth > maxWidth ||
                    iHeight < minHeight || iHeight > maxHeight ||
                    iBitCount < minDepth || iBitCount > maxDepth)
                {
                    continue;
                }
                if (iWidth >= matchingWidth && iHeight >= matchingHeight && iBitCount >= matchingDepth)
                {
                    matchingIndex  = iIndex;
                    matchingWidth  = iWidth;
                    matchingHeight = iHeight;
                    matchingDepth  = iBitCount;
                    if (matchingWidth == maxWidth && matchingHeight == maxHeight && matchingDepth == maxDepth)
                    {
                        break;
                    }
                }
            }
            if (matchingIndex < 0)
            {
                return(null);
            }
            int iImageSize   = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * matchingIndex + 8);
            int iImageOffset = BitConverter.ToInt32(srcBuf, SizeICONDIR + SizeICONDIRENTRY * matchingIndex + 12);
            var magic        = Encoding.ASCII.GetString(srcBuf, iImageOffset + 1, 3);

            if (magic == "PNG")
            {
                // Bitmap class reads any PNG directly from stream
                var stream = new MemoryStream();
                var writer = new BinaryWriter(stream);
                writer.Write(srcBuf, iImageOffset, iImageSize);
                stream.Seek(0, SeekOrigin.Begin);
                return(new Bitmap(stream));
            }
            else
            {
                // BMP format, determine metadata
                const int BI_BITFIELDS      = 3;
                const int BI_ALPHABITFIELDS = 6;
                int       numColors         = srcBuf[SizeICONDIR + SizeICONDIRENTRY * matchingIndex + 2];
                if (numColors == 0 && matchingDepth <= 8)
                {
                    numColors = 1 << matchingDepth;
                }
                int headerSize        = BitConverter.ToInt32(srcBuf, iImageOffset);
                int compressionMethod = BitConverter.ToInt32(srcBuf, iImageOffset + 30);
                int pixelDataOffset   = headerSize + numColors * (headerSize == 12 ? 3 : 4);
                if (compressionMethod == BI_BITFIELDS)
                {
                    pixelDataOffset += 12;
                }
                if (compressionMethod == BI_ALPHABITFIELDS)
                {
                    pixelDataOffset += 16;
                }

                if (matchingDepth == 32)
                {
                    // BMP with 32 bits not directly supported, load pixels ourselves
                    unsafe
                    {
                        fixed(byte *srcBufPtr = srcBuf)
                        {
                            var pixels     = srcBufPtr + iImageOffset + pixelDataOffset;
                            var result     = new Bitmap(matchingWidth, matchingHeight, PixelFormat.Format32bppArgb);
                            var resultBits = result.LockBits(new Rectangle(0, 0, result.Width, result.Height),
                                                             ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                            byte *dest = (byte *)resultBits.Scan0;

                            for (int y = matchingHeight - 1; y >= 0; --y)
                            {
                                byte *src = pixels + y * resultBits.Stride;
                                for (int i = resultBits.Stride; i > 0; --i)
                                {
                                    *dest++ = *src++;
                                }
                            }
                            result.UnlockBits(resultBits);
                            return(result);
                        }
                    }
                }
                else
                {
                    bool upsideDown;

                    // Add size of BITMAPFILEHEADER
                    pixelDataOffset += 14;

                    // Fix DIB header info
                    if (headerSize == 12)
                    {
                        // BITMAPCOREHEADER
                        upsideDown = BitConverter.ToInt16(srcBuf, iImageOffset + 6) >= 0;
                        var w16 = Convert.ToInt16(matchingWidth);
                        var h16 = Convert.ToInt16(matchingHeight);
                        BitConverter.GetBytes(w16).CopyTo(srcBuf, iImageOffset + 4);
                        BitConverter.GetBytes(h16).CopyTo(srcBuf, iImageOffset + 6);
                        BitConverter.GetBytes(matchingDepth).CopyTo(srcBuf, iImageOffset + 10);
                    }
                    else
                    {
                        // BITMAPINFOHEADER
                        upsideDown = BitConverter.ToInt32(srcBuf, iImageOffset + 8) >= 0;
                        BitConverter.GetBytes(matchingWidth).CopyTo(srcBuf, iImageOffset + 4);
                        BitConverter.GetBytes(matchingHeight).CopyTo(srcBuf, iImageOffset + 8);
                        BitConverter.GetBytes(matchingDepth).CopyTo(srcBuf, iImageOffset + 14);
                    }

                    Bitmap result;
                    using (var stream = new MemoryStream())
                    {
                        var writer = new BinaryWriter(stream);

                        // Write BITMAPFILEHEADER
                        writer.Write(Encoding.ASCII.GetBytes("BM"));
                        writer.Write(iImageSize + 14);
                        writer.Write(0);
                        writer.Write(pixelDataOffset);

                        writer.Write(srcBuf, iImageOffset, iImageSize);
                        stream.Seek(0, SeekOrigin.Begin);
                        var tmp = new Bitmap(stream);
                        result = new Bitmap(tmp.Width, tmp.Height, PixelFormat.Format32bppArgb);
                        using (var g = Graphics.FromImage(result))
                        {
                            g.DrawImage(tmp, 0, 0);
                        }
                    }
                    int srcStride        = matchingWidth * matchingDepth / 8;
                    int srcStrideModulus = srcStride % 4;
                    if (srcStrideModulus != 0)
                    {
                        srcStride += 4 - srcStrideModulus;
                    }
                    var resultBits = result.LockBits(new Rectangle(0, 0, result.Width, result.Height),
                                                     ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
                    int extraBits = 32 - matchingWidth % 32;
                    if (extraBits == 32)
                    {
                        extraBits = 0;
                    }
                    int skipBytes = extraBits / 8;
                    if (extraBits % 8 != 0)
                    {
                        ++skipBytes;
                    }
                    unsafe
                    {
                        fixed(byte *srcBufPtr = srcBuf)
                        {
                            byte *andMask = srcBufPtr + iImageOffset + pixelDataOffset - 14 + matchingHeight * srcStride;
                            int   bitmask = 1 << 7;

                            for (int y = 0; y < matchingHeight; ++y)
                            {
                                byte *outLine = (byte *)resultBits.Scan0;
                                if (upsideDown)
                                {
                                    outLine += (matchingHeight - 1 - y) * resultBits.Stride;
                                }
                                else
                                {
                                    outLine += y * resultBits.Stride;
                                }

                                for (byte *outAlpha = outLine + 3; outAlpha < outLine + 4 * matchingWidth; outAlpha += 4)
                                {
                                    if ((*andMask & bitmask) > 0)
                                    {
                                        *outAlpha = 0;
                                    }
                                    bitmask >>= 1;
                                    if (bitmask == 0)
                                    {
                                        bitmask = 1 << 7;
                                        ++andMask;
                                    }
                                }
                                if (extraBits > 0)
                                {
                                    bitmask  = 1 << 7;
                                    andMask += skipBytes;
                                }
                            }
                        }
                    }
                    result.UnlockBits(resultBits);
                    return(result);
                }
            }
        }
Ejemplo n.º 25
0
        public static byte[] GetBytes(Icon icon)
        {
            if (icon == null)
                return new byte[0];

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            icon.Save(stream);
            return stream.GetBuffer();
        }
Ejemplo n.º 26
0
        private static byte[] GetIconData(Icon ico)
        {
            var ms = new MemoryStream();

            ico.Save(ms);
            return ms.ToArray();
        }
Ejemplo n.º 27
0
 private static byte[] GetIconData(Icon icon)
 {
     var data = IconDataDelegate(icon);
     if (data != null)
     {
         return data;
     }
     using (var ms = new MemoryStream())
     {
         icon.Save(ms);
         return ms.ToArray();
     }
 }
Ejemplo n.º 28
0
		[Test] // bug #410608
		public void Save_256 ()
		{
			if (RunningOnUnix)
				Assert.Ignore ("Depends on bug #323511");

			using (Icon icon = new Icon (TestBitmap.getInFile ("bitmaps/323511.ico"))) {
				// FIXME: use this instead after bug #415809 is fixed
				//SaveAndCompare ("256", icon, true);

				MemoryStream ms = new MemoryStream ();
				icon.Save (ms);
				ms.Position = 0;

				using (Icon loaded = new Icon (ms)) {
					Assert.AreEqual (icon.Height, loaded.Height, "Loaded.Height");
					Assert.AreEqual (icon.Width, loaded.Width, "Loaded.Width");
				}
			}
		}
Ejemplo n.º 29
0
        public static void SaveIcon(Icon SourceIcon, string IconFilename)
        {
            FileStream NewIconStream = new FileStream(IconFilename, FileMode.Create);

            SourceIcon.Save(NewIconStream);

            NewIconStream.Close();
        }
Ejemplo n.º 30
0
 private void SaveIcon(Icon icon)
 {
     if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
     {
         FileStream fs = File.Create(saveFileDialog1.FileName);
         icon.Save(fs);
         fs.Close();
     }
 }
Ejemplo n.º 31
0
        //internal static Bitmap CreateDisabledBitmap(Bitmap bmp)
        //{
        //    if(bmp==null)
        //        return null;

        //    Bitmap bmpTarget=null;
        //    try
        //    {
        //        int nWidth = bmp.Width;
        //        int nHeight = bmp.Height;
        //        bmpTarget = new Bitmap(bmp);
        //        for (int iX = 0; iX < nWidth; iX++)
        //        {
        //            for (int iY = 0; iY < nHeight; iY++)
        //            {
        //                Color cr = bmp.GetPixel(iX, iY);
        //                if(cr.IsEmpty || cr==Color.Transparent)
        //                {
        //                    bmpTarget.SetPixel(iX, iY, Color.Transparent);
        //                }
        //                else
        //                {
        //                    byte nA = cr.A;
        //                    byte nB = (byte) ((cr.B + 255) / 2);
        //                    byte nG = (byte) ((cr.G + 255) / 2);
        //                    byte nR = (byte) ((cr.R + 255) / 2);
        //                    nR = nG = nB = (byte) (nR * 0.299 + nG * 0.587 + nB * 0.114);
        //                    bmpTarget.SetPixel(iX, iY, Color.FromArgb(nA, nR, nG, nB));
        //                }
        //            }
        //        }
        //    }
        //    catch
        //    {
        //        return null;
        //    }

        //    return bmpTarget;
        //}
        internal static Icon CreateDisabledIcon(Icon ico)
        {
            try
            {
                System.IO.MemoryStream memStream = new System.IO.MemoryStream();
                ico.Save(memStream);
                byte[] array = memStream.ToArray();
                int nIconCount = array[4];
                for (int iIcon = 0; iIcon < nIconCount; iIcon++)
                {
                    int nBaseOffset = 6 + iIcon * 16;
                    int nWidth = array[nBaseOffset + 0];
                    int nHeight = array[nBaseOffset + 1];
                    int nOffset = GetDWORD(ref array, nBaseOffset + 12);
                    //data at position
                    int nStructSize = GetDWORD(ref array, nOffset);
                    int nPlanes = GetWORD(ref array, nOffset + 12);
                    int nBitCount = GetWORD(ref array, nOffset + 14);
                    //process 32-bit Icons (bitcount=32)

                    //process 24-bit icons (bitcount=24)

                    //process 8-bit (256 color) icons (bitcount=8)
                    if (nPlanes != 1) continue;

                    int nSize = GetDWORD(ref array, nOffset + 20);
                    int nStep = 0;

                    switch (nBitCount)
                    {
                        case 32: nStep = 4; nSize = nWidth * nHeight * 4; break;
                        case 24: nStep = 3; nSize = nWidth * nHeight * 3; break;
                        case 8: nStep = 4; nSize = 1024; break;           //256 colors x 4 bytes
                        default: continue;
                    }

                    int iDataStart = nOffset + nStructSize;
                    for (int iPtr = iDataStart; iPtr < iDataStart + nSize; iPtr += nStep)
                    {
                        byte nB = (byte)((array[iPtr] + 255) / 2);
                        byte nG = (byte)((array[iPtr + 1] + 255) / 2);
                        byte nR = (byte)((array[iPtr + 2] + 255) / 2);
                        if (!(nB == 127 && nG == 127 && nR == 127))
                        {
                            byte nNewRGB = (byte)(nR * 0.299 + nG * 0.587 + nB * 0.114);
                            array[iPtr] = nNewRGB;
                            array[iPtr + 1] = nNewRGB;
                            array[iPtr + 2] = nNewRGB;
                        }
                    }
                }
                return new Icon(new System.IO.MemoryStream(array));
            }
            catch (Exception)
            {
                return null;
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        ///     Converts an Icon to a GDI+ Bitmap preserving the transparent area.
        /// </summary>
        /// <param name="icon">An System.Drawing.Icon to be converted.</param>
        /// <returns>A System.Drawing.Bitmap Object.</returns>
        public static Bitmap ToBitmap(Icon icon)
        {
            if (icon == null)
                throw new ArgumentNullException(nameof(icon));

            // Quick workaround: Create an .ico file in memory, then load it as a Bitmap.

            using (var ms = new MemoryStream())
            {
                icon.Save(ms);
                using (var bmp = (Bitmap) Image.FromStream(ms))
                {
                    return new Bitmap(bmp);
                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Gets an icon of a specific size from a set of icons.
        /// </summary>
        /// <param name="icon">The icon.</param>
        /// <param name="size">The size required.</param>
        /// <returns>The icon that is cloest to the size provided.</returns>
        protected static Icon GetIconSpecificSize(Icon icon, Size size)
        {
            //  Create a memory stream.
            using (var memoryStream = new MemoryStream())
            {
                //  Save the icon to the stream, then seek to the origin.
                icon.Save(memoryStream);
                memoryStream.Position = 0;

                //  Load the icon from the stream, but specify the size.
                return new Icon(memoryStream, size);
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Converts an Icon to a Bitmap
        /// </summary>
        /// <param name="icon">The Icon to be converted</param>
        /// <returns>A Bitmap that contains the converted Icon</returns>
        internal static unsafe Bitmap ConvertToBitmap(Icon icon)
        {
            Bitmap bitmap = null;

            // get the screen bpp
            int bitDepth = 0;

            IntPtr dc = NativeMethods.GetDC(IntPtr.Zero);
            bitDepth = NativeMethods.GetDeviceCaps(dc, 12 /*BITSPIXEL*/);
            bitDepth *= NativeMethods.GetDeviceCaps(dc, 14 /*PLANES*/);
            NativeMethods.ReleaseDC(IntPtr.Zero, dc);

            // if the screen bpp is not 32bpp return the
            // null bitmap so that IconToBitmap can get
            // windows to convert the icon (as it only
            // ignores the alpha channel if the display
            // is in 32bpp mode - why??)
            if (bitDepth != 32)
            {
                return bitmap;
            }

            // get the default icon sizes
            int defaultWidth = NativeMethods.GetSystemMetrics(11 /*SM_CXICON*/);
            int defaultHeight = NativeMethods.GetSystemMetrics(12 /*SM_CYICON*/);

            // convert the icon into a byte array

            MemoryStream ms = new MemoryStream();
            icon.Save(ms);

            byte[] iconData = ms.ToArray();

            ms.Close();
            ms = null;

            // prevent the garbage collector from relocating the iconData
            fixed (byte* data = iconData)
            {
                // "read" the data
                ICONFILE* iconfile = (ICONFILE*)data;

                // make sure we have valid data
                if (iconfile->reserved != 0 || iconfile->resourceType != 1 || iconfile->iconCount == 0)
                {
                    throw new ArgumentException("The argument picture must be a picture that can be used as a Icon");
                }

                // set the current entry to the start of the entry section
                ICONENTRY* currentEntry = &iconfile->entries;

                // the entry that contains the icon whose properties closest
                // match the default icon size and bitdepth
                ICONENTRY* targetEntry = null;
                int bpp = 0;

                // record the size of an ICONENTRY
                int iconEntrySize = Marshal.SizeOf(typeof(ICONENTRY));

                // make sure we have enough data to read each entry
                if ((iconEntrySize * iconfile->iconCount) >= iconData.Length)
                {
                    throw new ArgumentException("The argument picture must be a picture that can be used as a Icon");
                }

                // go through each entry
                for (int i = 0; i < iconfile->iconCount; i++)
                {
                    // get the icons bpp
                    int iconBitDepth = currentEntry->numPlanes * currentEntry->bitsPerPixel;

                    // make sure it is at least 16bpp
                    iconBitDepth = Math.Max(iconBitDepth, 16);

                    // set the target entry if we haven't already
                    if (targetEntry == null)
                    {
                        targetEntry = currentEntry;
                        bpp = iconBitDepth;
                    }
                    else
                    {
                        // work out the difference between default sizes
                        int targetTotalDiff = Math.Abs(targetEntry->width - defaultWidth) + Math.Abs(targetEntry->height - defaultHeight);
                        int currentTotalDiff = Math.Abs(currentEntry->width - defaultWidth) + Math.Abs(currentEntry->height - defaultHeight);

                        // check if the current match is closer than the previous match
                        if (currentTotalDiff < targetTotalDiff)
                        {
                            targetEntry = currentEntry;
                            bpp = iconBitDepth;
                        }
                            // if the size differences are the same, compare bit depths
                        else if ((currentTotalDiff == targetTotalDiff) && ((iconBitDepth <= bitDepth) && (iconBitDepth > bpp)) || (bpp > bitDepth) && (iconBitDepth < bpp))
                        {
                            targetEntry = currentEntry;
                            bpp = iconBitDepth;
                        }
                    }

                    // move to the next entry
                    currentEntry++;
                }

                // make sure the target entry is valid
                if ((targetEntry->dataOffset < 0) || ((targetEntry->dataOffset + targetEntry->dataSize) > iconData.Length))
                {
                    throw new ArgumentException("The argument picture must be a picture that can be used as a Icon");
                }

                // make sure the target is 32bpp
                if (targetEntry->bitsPerPixel == 32)
                {
                    int offset = targetEntry->dataOffset;
                    int dataSize = targetEntry->dataSize;

                    bitmap = new Bitmap(targetEntry->width, targetEntry->height, PixelFormat.Format32bppArgb);

                    int FILE_HEADER_BYTES = 40;
                    int PALETTE_SIZE = targetEntry->bitsPerPixel * 4;
                    int AND_MAP_SIZE = (targetEntry->width / 8) * (targetEntry->height / 8);
                    int XOR_MAP_SIZE = dataSize - FILE_HEADER_BYTES - PALETTE_SIZE;
                    int ROW_SIZE = targetEntry->width * (targetEntry->bitsPerPixel / 8);

                    byte[] bitmapBytes = new byte[dataSize];

                    GCHandle gcHandle = GCHandle.Alloc(bitmapBytes, GCHandleType.Pinned);
                    // nb. we only copy the actual PNG data (no header)
                    Array.Copy(iconData, offset, bitmapBytes, 0, dataSize);

                    // copy the byte array contents back to a handle to the alpha bitmap (use lockbits)
                    Rectangle copyArea = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    BitmapData alphaBits = bitmap.LockBits(copyArea, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

                    int dataStart = FILE_HEADER_BYTES + PALETTE_SIZE;

                    // copymemory to bitmap data (Scan0)
                    IntPtr firstCopyElement = Marshal.UnsafeAddrOfPinnedArrayElement(bitmapBytes, dataStart);
                    NativeMethods.CopyMemory(alphaBits.Scan0, firstCopyElement, XOR_MAP_SIZE - ROW_SIZE);
                    gcHandle.Free();

                    // complete operation
                    bitmap.UnlockBits(alphaBits);
                    NativeMethods.GdiFlush();

                    // flip bits (not sure why this is needed at the moment..)
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
                }
            }

            return bitmap;
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Split an Icon consists of multiple icons into an array of Icon each consist of single icons.
        /// </summary>
        /// <param name="icon">The System.Drawing.Icon to be split.</param>
        /// <returns>An array of System.Drawing.Icon each consist of single icons.</returns>
        public static Icon[] SplitIcon(Icon icon)
        {
            if (icon == null)
            {
                throw new ArgumentNullException("icon");
            }

            // Get multiple .ico file image.
            byte[] srcBuf = null;
            using (MemoryStream stream = new MemoryStream())
            {
                icon.Save(stream);
                srcBuf = stream.ToArray();
            }

            List<Icon> splitIcons = new List<Icon>();
            {
                int count = BitConverter.ToInt16(srcBuf, 4); // ICONDIR.idCount

                for (int i = 0; i < count; i++)
                {
                    using (MemoryStream destStream = new MemoryStream())
                    using (BinaryWriter writer = new BinaryWriter(destStream))
                    {
                        // Copy ICONDIR and ICONDIRENTRY.
                        writer.Write(srcBuf, 0, sICONDIR - 2);
                        writer.Write((short)1);    // ICONDIR.idCount == 1;

                        writer.Write(srcBuf, sICONDIR + sICONDIRENTRY * i, sICONDIRENTRY - 4);
                        writer.Write(sICONDIR + sICONDIRENTRY);    // ICONDIRENTRY.dwImageOffset = sizeof(ICONDIR) + sizeof(ICONDIRENTRY)

                        // Copy picture and mask data.
                        int imgSize = BitConverter.ToInt32(srcBuf, sICONDIR + sICONDIRENTRY * i + 8);       // ICONDIRENTRY.dwBytesInRes
                        int imgOffset = BitConverter.ToInt32(srcBuf, sICONDIR + sICONDIRENTRY * i + 12);    // ICONDIRENTRY.dwImageOffset
                        writer.Write(srcBuf, imgOffset, imgSize);

                        // Create new icon.
                        destStream.Seek(0, SeekOrigin.Begin);
                        splitIcons.Add(new Icon(destStream));
                    }
                }
            }

            return splitIcons.ToArray();
        }
Ejemplo n.º 36
0
 private byte[] getIconBytesFromIcon(Icon icon)
 {
     try
     {
         using (MemoryStream ms = new MemoryStream())
         {
             icon.Save(ms);
             return ms.ToArray();
         }
     }
     catch (Exception)
     {
         return null;
     }
 }
Ejemplo n.º 37
-1
		public virtual void Init()
		{
			originalIcon = new Icon(GetType(), "TestIcon.ico");
			file = "./yellow.ico";
			using (FileStream stream = File.Create(file))
			{
				originalIcon.Save(stream);
			}
		}