예제 #1
0
        public static BitmapSource ImageSourceReturn(string uri)
        {
            try
            {
                Uri myUri = new Uri(uri);
                switch (myUri.Segments.Last().Substring(myUri.Segments.Last().Count() - 3, 3))
                {
                case "jpg":
                {
                    JpegBitmapDecoder dec = new JpegBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource      bs  = dec.Frames[0];

                    return(bs);
                }

                case "peg":
                {
                    JpegBitmapDecoder dec = new JpegBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource      bs  = dec.Frames[0];

                    return(bs);
                }

                case "bmp":
                {
                    BmpBitmapDecoder dec = new BmpBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                case "png":
                {
                    PngBitmapDecoder dec = new PngBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                case "gif":
                {
                    GifBitmapDecoder dec = new GifBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                case "iff":
                {
                    TiffBitmapDecoder dec = new TiffBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource      bs  = dec.Frames[0];

                    return(bs);
                }

                case "wmp":
                {
                    WmpBitmapDecoder dec = new WmpBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                case "JPG":
                {
                    JpegBitmapDecoder dec = new JpegBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource      bs  = dec.Frames[0];

                    return(bs);
                }

                case "PEG":
                {
                    JpegBitmapDecoder dec = new JpegBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    int          f        = dec.Frames.Count;
                    BitmapSource bs       = new BitmapImage(myUri);

                    return(bs);
                }

                case "BMP":
                {
                    BmpBitmapDecoder dec = new BmpBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                case "PNG":
                {
                    PngBitmapDecoder dec = new PngBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                case "GIF":
                {
                    GifBitmapDecoder dec = new GifBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                case "IFF":
                {
                    TiffBitmapDecoder dec = new TiffBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource      bs  = dec.Frames[0];

                    return(bs);
                }

                case "WMP":
                {
                    WmpBitmapDecoder dec = new WmpBitmapDecoder(myUri, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapSource     bs  = dec.Frames[0];

                    return(bs);
                }

                default:
                {
                    return(null);
                }
                }
            }
            catch (Exception e)
            {
                return(null);
            }
        }
예제 #2
0
    public unsafe static BitmapSource Read(ref BITMAP_READ_DETAILS info, byte *pixels, uint bcrFlags)
    {
        // we do this parsing here since BitmapCore has no references to PresentationCore
        if (info.compression == BitmapCompressionMode.BI_PNG)
        {
            var stream = new PointerStream(pixels, info.imgDataSize);
            var png    = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            return(png.Frames[0]);
        }
        else if (info.compression == BitmapCompressionMode.BI_JPEG)
        {
            var stream = new PointerStream(pixels, info.imgDataSize);
            var jpg    = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            return(jpg.Frames[0]);
        }

        PixelFormat           wpfFmt  = PixelFormats.Bgra32;
        BitmapCorePixelFormat coreFmt = BitmapCorePixelFormat.Bgra32;

        bool forceBgra32 = (bcrFlags & BitmapCore.BC_READ_FORCE_BGRA32) > 0;

        if (!forceBgra32 && info.imgSourceFmt != null)
        {
            var origFmt = info.imgSourceFmt;
            var pxarr   = Formats.Where(m => m.coreFmt == origFmt).ToArray();
            if (pxarr.Length > 0)
            {
                var px = pxarr.First();
                wpfFmt  = px.wpfFmt;
                coreFmt = px.coreFmt;
            }
        }

        BitmapPalette palette = null;

        if (info.imgColorTable.Length > 0)
        {
            var clrs = info.imgColorTable.Select(c => Color.FromRgb(c.rgbRed, c.rgbGreen, c.rgbBlue));
            if (info.imgColorTable.Length > 256) // wpf throws on oversized palettes
            {
                clrs = clrs.Take(256);
            }
            palette = new BitmapPalette(clrs.ToList());
        }

        var bitmap = new WriteableBitmap(
            info.imgWidth,
            info.imgHeight,
            info.dpiX,
            info.dpiY,
            wpfFmt,
            palette);

        var buf = (byte *)bitmap.BackBuffer;

        bitmap.Lock();

        BitmapCore.ReadPixels(ref info, coreFmt, pixels, buf, bcrFlags);

        bitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, info.imgWidth, info.imgHeight));
        bitmap.Unlock();
        bitmap.Freeze(); // dispose back buffer

        return(bitmap);
    }
    /// <summary>
    /// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
    /// The theory can be found at http://www.libpng.org/pub/png/book/chapter08.html
    /// </summary>
    /// <param name="data">File data to load</param>
    /// <param name="paletteLength">Palette length in the original image. The palette format of .net is not adjustable in size, so it'll be the max size. This value can be used to adjust that.</param>
    /// <returns>The loaded image</returns>
    public static Bitmap LoadBitmap(Byte[] data, out Int32 paletteLength)
    {
        Bitmap loadedImage;

        if (data.Length > PNG_IDENTIFIER.Length && data.Take(PNG_IDENTIFIER.Length).SequenceEqual(PNG_IDENTIFIER))
        {
            Byte[] transparencyData = null;
            // Check if it contains a palette.
            // I'm sure it can be looked up in the header somehow, but meh.
            Int32 plteOffset = FindChunk(data, "PLTE");
            if (plteOffset != -1)
            {
                // Check if it contains a palette transparency chunk.
                Int32 trnsOffset = FindChunk(data, "tRNS");
                if (trnsOffset != -1)
                {
                    // Get chunk
                    Int32 trnsLength = GetChunkDataLength(data, trnsOffset);
                    transparencyData = new Byte[trnsLength];
                    Array.Copy(data, trnsOffset + 8, transparencyData, 0, trnsLength);
                    // filter out the palette alpha chunk, make new data array
                    Byte[] data2 = new Byte[data.Length - (trnsLength + 12)];
                    Array.Copy(data, 0, data2, 0, trnsOffset);
                    Int32 trnsEnd = trnsOffset + trnsLength + 12;
                    Array.Copy(data, trnsEnd, data2, trnsOffset, data.Length - trnsEnd);
                    data = data2;
                }
            }
            // Open a Stream and decode a PNG image
            using (MemoryStream imageStreamSource = new MemoryStream(data))
            {
                PngBitmapDecoder decoder      = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                BitmapSource     bitmapSource = decoder.Frames[0];
                Int32            width        = bitmapSource.PixelWidth;
                Int32            height       = bitmapSource.PixelHeight;
                Int32            stride       = ImageUtils.GetMinimumStride(width, bitmapSource.Format.BitsPerPixel);
                Byte[]           pixel        = new Byte[height * stride];
                bitmapSource.CopyPixels(pixel, stride, 0);
                WriteableBitmap myBitmap = new WriteableBitmap(width, height, 96, 96, bitmapSource.Format, bitmapSource.Palette);
                myBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixel, stride, 0);
                // Convert WPF BitmapSource to GDI+ Bitmap
                Bitmap newBitmap = BitmapFromSource(myBitmap);
                System.Drawing.Color[] colpal = newBitmap.Palette.Entries;
                Boolean hasTransparency       = false;
                if (colpal.Length != 0 && transparencyData != null)
                {
                    for (Int32 i = 0; i < colpal.Length; i++)
                    {
                        if (i >= transparencyData.Length)
                        {
                            break;
                        }
                        System.Drawing.Color col = colpal[i];
                        colpal[i] = System.Drawing.Color.FromArgb(transparencyData[i], col.R, col.G, col.B);
                        if (!hasTransparency)
                        {
                            hasTransparency = transparencyData[i] == 0;
                        }
                    }
                }
                paletteLength = colpal.Length;
                if (hasTransparency)
                {
                    Byte[] imageData = ImageUtils.GetImageData(newBitmap, out stride);
                    return(ImageUtils.BuildImage(imageData, newBitmap.Width, newBitmap.Height, stride, newBitmap.PixelFormat, colpal, System.Drawing.Color.Empty));
                }
                return(newBitmap);
            }
        }
        using (MemoryStream ms = new MemoryStream(data))
        {
            loadedImage = new Bitmap(ms);
            ms.Close();
            paletteLength = loadedImage.Palette.Entries.Length;
        }
        return(ImageUtils.CloneImage(loadedImage));
    }
예제 #4
0
        /// <summary>
        /// Creates a WPF bitmap source from an GDI image.
        /// </summary>
        public static BitmapSource CreateBitmapSource(Image image)
        {
            MemoryStream stream = new MemoryStream();
            //int width = image.Width;
            //int height = image.Height;
            //double dpiX = image.HorizontalResolution;
            //double dpiY = image.VerticalResolution;
            //System.Windows.Media.PixelFormat pixelformat = PixelFormats.Default;
            BitmapSource bitmapSource = null;

            try
            {
                string guid = image.RawFormat.Guid.ToString("B").ToUpper();
                switch (guid)
                {
                case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}":      // memoryBMP
                case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}":      // bmp
                    image.Save(stream, ImageFormat.Bmp);
                    stream.Position = 0;
                    BmpBitmapDecoder bmpDecoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    bitmapSource = bmpDecoder.Frames[0];
                    break;

                case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}":      // png
                    image.Save(stream, ImageFormat.Png);
                    stream.Position = 0;
                    PngBitmapDecoder pngDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    bitmapSource = pngDecoder.Frames[0];
                    break;

                case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}":      // jpeg
                    image.Save(stream, ImageFormat.Jpeg);
                    JpegBitmapDecoder jpegDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    stream.Position = 0;
                    bitmapSource    = jpegDecoder.Frames[0];
                    break;

                case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}":      // gif
                    image.Save(stream, ImageFormat.Gif);
                    GifBitmapDecoder gifDecoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    stream.Position = 0;
                    bitmapSource    = gifDecoder.Frames[0];
                    break;

                case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}":      // tiff
                    image.Save(stream, ImageFormat.Tiff);
                    TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    stream.Position = 0;
                    bitmapSource    = tiffDecoder.Frames[0];
                    break;

                case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}":      // icon
                    image.Save(stream, ImageFormat.Icon);
                    IconBitmapDecoder iconDecoder = new IconBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    stream.Position = 0;
                    bitmapSource    = iconDecoder.Frames[0];
                    break;

                case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}":      // emf
                case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}":      // wmf
                case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}":      // exif
                case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}":      // photoCD
                case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}":      // flashPIX

                default:
                    throw new InvalidOperationException("Unsupported image format.");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ImageHelper.CreateBitmapSource failed:" + ex.Message);
            }
            finally
            {
                //if (stream != null)
                //  stream.Close();
            }
            return(bitmapSource);
        }
예제 #5
0
        /// <summary>
        /// Creates an MS tag for a given URL.
        /// </summary>
        /// <param name="credential">The API credential.</param>
        /// <param name="category">The tag category.</param>
        /// <param name="link">The link to encode in the tag.</param>
        /// <returns>The tag image.</returns>
        private BitmapSource CreateTag(UserCredential credential, string category, Uri link)
        {
            // Hash the URL for use in the title, because if the URL is too long, the tag service gets angry.
            string hash = GetMD5Hash(link.OriginalString);

            // Define the range for which the tag is valid.
            DateTime tagStartDate = DateTime.UtcNow.AddDays(-1);
            DateTime tagEndDate   = DateTime.UtcNow.AddDays(90);

            MIBPContractClient client = new MIBPContractClient();
            Tag tag = null;

            try
            {
                // See if this tag already exists.
                tag = client.GetTagByTagName(credential, category, hash);

                if (tag.UTCEndDate > tagEndDate)
                {
                    // If the tag is expired, change the end date so that it will work again.
                    tag.UTCStartDate = tagStartDate;
                    tag.UTCEndDate   = tagEndDate;

                    try
                    {
                        client.UpdateTag(credential, category, hash, tag);
                    }
                    catch
                    {
                        return(null);
                    }
                }
            }
            catch
            {
                // The tag wasn't found, so create a new one.
                tag = new URITag
                {
                    MedFiUrl     = link.OriginalString,
                    Title        = hash,
                    UTCStartDate = tagStartDate,
                    UTCEndDate   = tagEndDate,
                };

                try
                {
                    client.CreateTag(credential, category, tag);
                }
                catch
                {
                    return(null);
                }
            }

            try
            {
                byte[]       barcode = client.GetBarcode(credential, category, hash, ImageTypes.png, .8f, DecorationType.HCCBRP_DECORATION_NONE, false);
                BitmapSource bmp     = new PngBitmapDecoder(new MemoryStream(barcode), BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0];
                return(bmp);
            }
            catch
            {
                return(null);
            }
        }
예제 #6
0
        public GameInfo(BlorbFile blorb)
        {
            var metadata = blorb.LoadMetadata();

            XNamespace xmlns                 = "http://babel.ifarchive.org/protocol/iFiction/";
            var        storyElement          = metadata.Element(xmlns + "story");
            var        biblioElement         = storyElement.Element(xmlns + "bibliographic");
            var        titleElement          = biblioElement.Element(xmlns + "title");
            var        headlineElement       = biblioElement.Element(xmlns + "headline");
            var        authorElement         = biblioElement.Element(xmlns + "author");
            var        firstPublishedElement = biblioElement.Element(xmlns + "firstpublished");
            var        descriptionElement    = biblioElement.Element(xmlns + "description");

            title          = titleElement != null ? (string)titleElement : string.Empty;
            headline       = headlineElement != null ? (string)headlineElement : string.Empty;
            author         = authorElement != null ? (string)authorElement : string.Empty;
            firstPublished = firstPublishedElement != null ? (string)firstPublishedElement : string.Empty;

            if (descriptionElement != null)
            {
                var descriptionBuilder = new StringBuilder();
                foreach (var descendent in descriptionElement.DescendantNodes())
                {
                    switch (descendent.NodeType)
                    {
                    case XmlNodeType.Text:
                        var tokens = ((XText)descendent).Value.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        descriptionBuilder.Append(string.Join(" ", tokens));

                        break;

                    case XmlNodeType.Element:
                        if (((XElement)descendent).Name == xmlns + "br")
                        {
                            descriptionBuilder.AppendLine();
                            descriptionBuilder.AppendLine();
                        }
                        break;
                    }
                }
                description = descriptionBuilder.ToString();
            }
            else
            {
                description = string.Empty;
            }

            var coverElement = storyElement.Element(xmlns + "cover");

            if (coverElement != null)
            {
                var coverFormatElement = coverElement.Element(xmlns + "format");
                var coverHeightElement = coverElement.Element(xmlns + "height");
                var coverWidthElement  = coverElement.Element(xmlns + "width");

                coverFormat = coverFormatElement != null ? (string)coverFormatElement : string.Empty;
                coverHeight = coverHeightElement != null ? (int)coverHeightElement : -1;
                coverWidth  = coverWidthElement != null ? (int)coverWidthElement : -1;
            }

            var zcodeElement = storyElement.Element(xmlns + "zcode");

            if (zcodeElement != null)
            {
                var coverPictureElement = zcodeElement.Element(xmlns + "coverpicture");
                if (coverPictureElement != null)
                {
                    coverId = coverPictureElement != null ? (int)coverPictureElement : -1;
                }
            }

            if (coverId >= 0)
            {
                var pictureKind = blorb.GetPictureKind(coverId);
                if (pictureKind != PictureKind.Unknown)
                {
                    using (var pictureStream = blorb.LoadPictureStream(coverId))
                    {
                        BitmapDecoder decoder;
                        if (pictureKind == PictureKind.Jpeg)
                        {
                            decoder = new JpegBitmapDecoder(pictureStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                        }
                        else // PictureKind.Png
                        {
                            decoder = new PngBitmapDecoder(pictureStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                        }

                        cover = decoder.Frames[0];
                    }
                }
            }
        }
예제 #7
0
        public Image GetPreviewAsImage()
        {
            if ((PreviewData == null) || (PreviewData.Length <= 0))
            {
                using (Bitmap newBitmap = new Bitmap(128, 128))
                {
                    return(newBitmap.Clone() as Bitmap);
                }
            }

            // read past the Revit metadata to the start of the PNG image
            int startingOffset = GetPngStartingOffset();

            if (startingOffset == 0)
            {
                using (Bitmap newBitmap = new Bitmap(128, 128))
                {
                    return(newBitmap.Clone() as Bitmap);
                }
            }

            try
            {
                byte[] pngDataBuffer = new byte[PreviewData.GetUpperBound(0) - startingOffset + 1];
                // read the PNG image data into a byte array
                using (MemoryStream ms = new MemoryStream(PreviewData))
                {
                    ms.Position = startingOffset;
                    ms.Read(pngDataBuffer, 0, pngDataBuffer.Length);
                }

                byte[] decoderData = null;

                // if the image data is valid
                if (pngDataBuffer != null)
                {
                    // use a memory stream to decode the PNG image data
                    // and copy the decoded data into a byte array
                    using (MemoryStream ms = new MemoryStream(pngDataBuffer))
                    {
                        PngBitmapDecoder decoder = new PngBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        decoderData = BitSourceToArray(decoder.Frames[0]);
                    }
                }

                // if the decoded data is valie
                if ((decoderData != null) && (decoderData.Length > 0))
                {
                    // use another memory stream to create a Bitmap
                    // and then an Image from that Bitmap
                    using (MemoryStream ms = new MemoryStream(decoderData))
                    {
                        using (Bitmap newBitmap = new Bitmap((ms)))
                        {
                            using (Image newImage = newBitmap)
                            {
                                return(newImage.Clone() as Image);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            using (Bitmap newBitmap = new Bitmap(128, 128))
            {
                return(newBitmap.Clone() as Bitmap);
            }
        }
        /// <summary>
        /// Couldn't get it to work with the proper colour-mode. But after modifying our code to use
        /// the version from http://www.bendewey.name/code/FilenameIconImageConverter.html everything
        /// was fixed.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ImageSource source = null;

            lock (this)
            {
                if (_internalCache == null)
                {
                    _internalCache = new Dictionary <string, ImageSource>();
                }

                string ext = Path.GetExtension(value == null ? "unknown.unknown" : value.ToString());

                int index = ext.IndexOf('?');

                if (index > -1)
                {
                    ext = ext.Substring(0, index);
                }

                if (_internalCache.ContainsKey(ext))
                {
                    return(_internalCache[ext]);
                }
                else
                {
                    string   resourcePath = Path.Combine(Path.GetTempPath(), "file" + ext);
                    FileInfo resource     = new FileInfo(resourcePath);
                    try
                    {
                        if (!resource.Exists)
                        {
                            using (StreamWriter strm = resource.CreateText())
                                strm.Close();
                        }

                        SHFILEINFO shinfo = new SHFILEINFO();

                        uint size = parameter == null ? Interop.SHGFI_SMALLICON : Interop.SHGFI_LARGEICON;

                        Interop.SHGetFileInfo(resource.FullName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Interop.SHGFI_ICON | size);

                        Icon fileIcon = Icon.FromHandle(shinfo.hIcon);
                        using (MemoryStream memStream = new MemoryStream())
                        {
                            Bitmap iconBitmap = fileIcon.ToBitmap();
                            iconBitmap.Save(memStream, ImageFormat.Png);
                            iconBitmap.Dispose();

                            memStream.Seek(0, SeekOrigin.Begin);
                            PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(memStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            source = bitmapDecoder.Frames[0];
                            source.Freeze();
                        }
                    }
                    finally
                    {
                        resource.Delete();
                    }

                    if (source != null)
                    {
                        _internalCache.Add(ext, source);
                    }
                }
            }

            return(source);
        }
예제 #9
0
        /// <summary>
        /// Add text comment to image file
        /// </summary>
        /// <param name="path">Image file path</param>
        /// <param name="desc">Text to add as comment</param>
        public static void AddImageDescription(string path, string desc)
        {
            string fileDirectory = Path.GetDirectoryName(path);
            string fileName      = Path.GetFileNameWithoutExtension(path);
            string fileExt       = Path.GetExtension(path);

            BitmapEncoder encoder      = null;
            string        tempLocation = fileDirectory + @"\" + "temp.jpg";
            bool          added        = false;
            string        filePath     = path;

            if (string.IsNullOrEmpty(fileExt))
            {
                filePath = FileHelper.FindFile(fileDirectory, fileName);
            }

            if (!string.IsNullOrEmpty(filePath))
            {
                if (File.Exists(filePath))
                {
                    path = filePath;
                    var imageFormat = GetImageFormat(Image.FromFile(path));

                    var mimeType = imageFormat.ToString();

                    while (!added)
                    {
                        try
                        {
                            BitmapDecoder decoder;
                            FileInfo      tempImage;
                            using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                var originalImage = File.Exists(path) ? new FileInfo(path) : null;
                                if (File.Exists(tempLocation))
                                {
                                    File.Delete(tempLocation);
                                }

                                originalImage.CopyTo(tempLocation, true);
                                tempImage = new FileInfo(tempLocation);
                                fileStream.Seek(0, SeekOrigin.Begin);

                                switch (mimeType) //find mime type of image based on extension
                                {
                                case "Jpeg":
                                    try
                                    {
                                        decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                                        encoder = new JpegBitmapEncoder();
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            fileStream.Seek(0, SeekOrigin.Begin);
                                            decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                                            encoder = new JpegBitmapEncoder();
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                fileStream.Seek(0, SeekOrigin.Begin);
                                                decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                                                encoder = new PngBitmapEncoder();
                                            }
                                            catch
                                            {
                                                try
                                                {
                                                    fileStream.Seek(0, SeekOrigin.Begin);
                                                    decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                                                    encoder = new PngBitmapEncoder();
                                                }
                                                catch
                                                {
                                                    decoder = null;
                                                }
                                            }
                                        }
                                    }
                                    break;

                                case "Png":
                                    try
                                    {
                                        decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                                        encoder = new PngBitmapEncoder();
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            fileStream.Seek(0, SeekOrigin.Begin);
                                            decoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                                            encoder = new PngBitmapEncoder();
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                fileStream.Seek(0, SeekOrigin.Begin);
                                                decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                                                encoder = new JpegBitmapEncoder();
                                            }
                                            catch
                                            {
                                                try
                                                {
                                                    fileStream.Seek(0, SeekOrigin.Begin);
                                                    decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                                                    encoder = new JpegBitmapEncoder();
                                                }
                                                catch
                                                {
                                                    decoder = null;
                                                }
                                            }
                                        }
                                    }
                                    break;

                                default:     // Not jpeg or png file - dont add the comments
                                    decoder = null;
                                    break;
                                }
                            }

                            if (decoder != null && desc != null)
                            {
                                var metadata = (BitmapMetadata)decoder.Frames[0].Metadata.Clone();

                                if (mimeType == "Jpeg")
                                {
                                    metadata.Comment = desc;
                                    metadata.SetQuery("/xmp/dc:description", desc);
                                }
                                else if (mimeType == "Png")
                                {
                                    metadata.SetQuery("/xmp/dc:description", desc);
                                }

                                var fileFrame = BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, metadata, decoder.Frames[0].ColorContexts);
                                encoder.Frames.Add(fileFrame);

                                using (Stream fileStreamOut = new FileStream(path, FileMode.Create))
                                {
                                    try
                                    {
                                        encoder?.Save(fileStreamOut);
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            //fileStreamOut.Close();
                                            tempImage.CopyTo(path, true);
                                        }
                                        catch
                                        {
                                            // ignored
                                        }
                                    }
                                }
                            }
                            added = true;
                            File.Delete(tempLocation);
                        }
                        catch (NotSupportedException)
                        {
                            added = true;
                        }
                        catch (FileFormatException)
                        {
                            added = true;
                        }
                        catch (IOException)
                        {
                            added = false;
                        }
                    }
                }
            }
        }
예제 #10
0
        private int handleWithFilter(int x, int y, int w, int h, HttpListenerContext listenerContext, link redLink, link greenLink, link blueLink, bool isBlackAndWhite)
        {
            Console.WriteLine("start");
            PngBitmapDecoder decoder   = new PngBitmapDecoder(listenerContext.Request.InputStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnDemand);
            BitmapSource     bmpSourse = decoder.Frames[0];
            int leftPoint  = (w >= 0) ? x : x + w;
            int upperPoint = (h >= 0) ? y : y + h;
            int absW       = Math.Abs(w);
            int absH       = Math.Abs(h);
            int xFrom      = Math.Max(leftPoint, 0);
            int yFrom      = Math.Max(upperPoint, 0);
            int xTo        = Math.Min(leftPoint + absW, (int)bmpSourse.PixelWidth);
            int yTo        = Math.Min(upperPoint + absH, (int)bmpSourse.PixelHeight);
            int oldStride  = (int)bmpSourse.PixelWidth;

            byte[] buf = new byte[4 * ((xTo - xFrom) + (yTo - yFrom) * oldStride)];
            try
            {
                bmpSourse.CopyPixels(new System.Windows.Int32Rect(xFrom, yFrom, xTo - xFrom, yTo - yFrom), buf, 4 * (int)bmpSourse.PixelWidth, 0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.Read();
            }
            int width  = (xTo - xFrom);
            int height = (yTo - yFrom);
            int stride = width * 4;

            byte[] buf2 = new byte[4 * width * height];
            byte   oldB, oldG, oldR;

            for (int i = 0; i < height; i += 1)
            {
                for (int j = 0; j < (stride); j += 4)
                {
                    oldB = buf[4 * i * oldStride + j];
                    oldG = buf[4 * i * oldStride + j + 1];
                    oldR = buf[4 * i * oldStride + j + 2];

                    buf2[i * stride + j]     = blueLink(oldR, oldG, oldB);
                    buf2[i * stride + j + 1] = greenLink(oldR, oldG, oldB);
                    buf2[i * stride + j + 2] = redLink(oldR, oldG, oldB);
                    buf2[i * stride + j + 3] = buf[4 * i * oldStride + j + 3];
                }
            }



            BitmapSource     image   = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, buf2, stride);
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(image));
            MemoryStream inMemory = new MemoryStream();

            encoder.Save(inMemory);
            byte[] buffer = inMemory.GetBuffer();
            listenerContext.Response.OutputStream.Write(buffer, 0, buffer.Length);
            //FileStream fs= new FileStream("out.png", FileMode.OpenOrCreate);
            //fs.Write(buffer, 0, buffer.Length);
            //fs.Close();

            Console.WriteLine("end");
            return(200);
        }
예제 #11
0
        /**
         * Constructor
         */
        public MicRecordViewModel()
        {
            this.MenuRecognizerHoriz = new MenuRecognizer(4, 100);

/*
 * >>>>>>> origin/images
 *          this.menuListHoriz.Add(new MenuOption("Record", null, 4, this.menuRecognizerHoriz));
 *          this.menuListHoriz.Add(new MenuOption("Play", null, 4, this.menuRecognizerHoriz));
 *          this.menuListHoriz.Add(new MenuOption("Settings", null, 4, this.menuRecognizerHoriz));
 *          this.menuListHoriz.Add(new MenuOption("New Track", null, 4, this.menuRecognizerHoriz));
 */

            Stream           recordImgStream = new FileStream("Graphics/record.png", FileMode.Open, FileAccess.Read, FileShare.Read);
            PngBitmapDecoder decoder         = new PngBitmapDecoder(recordImgStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource     bitmapSource    = decoder.Frames[0];

            Image recordImage = new Image();

            recordImage.Source  = bitmapSource;
            recordImage.Stretch = Stretch.None;

            this.menuListHoriz.Add(new MenuOption("Graphics/record.png", null, 4, this.menuRecognizerHoriz));
            this.menuListHoriz.Add(new MenuOption("Graphics/play.png", null, 4, this.menuRecognizerHoriz));
            this.menuListHoriz.Add(new MenuOption("Graphics/settings.png", null, 4, this.menuRecognizerHoriz));
            this.menuListHoriz.Add(new MenuOption("Graphics/new.png", null, 4, this.menuRecognizerHoriz));

            recordImgStream.Close();

            MenuRecognizerHoriz.MenuItemSelected += OnHorizMenuItemSelected;

            /*
             * this.MenuRecognizerVert = new MenuRecognizer(3, 100, false);
             * this.menuListVert.Add(new MenuOption("Record", null, 3, this.menuRecognizerVert));
             * this.menuListVert.Add(new MenuOption("Stop Recording", null, 3, this.menuRecognizerVert));
             * this.menuListVert.Add(new MenuOption("New Track", null, 3, this.menuRecognizerVert));
             *
             * MenuRecognizerVert.MenuItemSelected += OnVertMenuItemSelected;
             * this.gestureController.Add(this.MenuRecognizerVert);
             */

            this.gestureController.Add(this.MenuRecognizerHoriz);

            Messenger.Default.Register <ShuttingDownMessage>(this, (message) => OnShuttingDown(message));

            this.uiDispatcher       = Application.Current.Dispatcher;
            metronomeTimer          = new System.Windows.Threading.DispatcherTimer();
            metronomeTimer.Tick    += new EventHandler(metronomeTimer_Tick);
            metronomeTimer.Interval = TimeSpan.FromMilliseconds(dotDuration);
            metronomeTimer.Start();

            int    i          = 0;
            string folderName = "First Cut Project";

            while (Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), folderName)))
            {
                i++;
                folderName = "First Cut Project (" + i.ToString() + ")";
            }

            this.projectDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), folderName);
            Directory.CreateDirectory(this.projectDirectory);
        }
예제 #12
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            mainWindow       = new Window();
            mainWindow.Title = "PNG Imaging Sample";
            ScrollViewer mySV = new ScrollViewer();

            //<Snippet4>
            int width  = 128;
            int height = 128;
            int stride = width;

            byte[] pixels = new byte[height * stride];

            // Define the image palette
            BitmapPalette myPalette = BitmapPalettes.Halftone256;

            // Creates a new empty image with the pre-defined palette

            //<SnippetPngEncoder>
            //<Snippet2>
            BitmapSource image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed8,
                myPalette,
                pixels,
                stride);
            //</Snippet2>

            //<Snippet3>
            FileStream       stream      = new FileStream("new.png", FileMode.Create);
            PngBitmapEncoder encoder     = new PngBitmapEncoder();
            TextBlock        myTextBlock = new TextBlock();

            myTextBlock.Text  = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);
            //</Snippet3>
            //</SnippetPngEncoder>

            //</Snippet4>

            //<Snippet1>

            // Open a Stream and decode a PNG image
            Stream           imageStreamSource = new FileStream("smiley.png", FileMode.Open, FileAccess.Read, FileShare.Read);
            PngBitmapDecoder decoder           = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource     bitmapSource      = decoder.Frames[0];

            // Draw the Image
            Image myImage = new Image();

            myImage.Source  = bitmapSource;
            myImage.Stretch = Stretch.None;
            myImage.Margin  = new Thickness(20);
            //</Snippet1>

            //<Snippet5>

            // Open a Uri and decode a PNG image
            Uri myUri = new Uri("smiley.png", UriKind.RelativeOrAbsolute);
            PngBitmapDecoder decoder2      = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource     bitmapSource2 = decoder2.Frames[0];

            // Draw the Image
            Image myImage2 = new Image();

            myImage2.Source  = bitmapSource2;
            myImage2.Stretch = Stretch.None;
            myImage2.Margin  = new Thickness(20);
            //</Snippet5>

            // Define a StackPanel to host the decoded PNG images
            StackPanel myStackPanel = new StackPanel();

            myStackPanel.Orientation         = Orientation.Vertical;
            myStackPanel.VerticalAlignment   = VerticalAlignment.Stretch;
            myStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch;

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            mySV.Content       = myStackPanel;
            mainWindow.Content = mySV;
            mainWindow.Show();
        }
예제 #13
0
        public static void GetEpisodeImages(Show show)
        {
            foreach (var episode in show.Seasons.SelectMany(season => season.Episodes))
            {
                episode.IsLoading = true;
            }

            Task.Factory.StartNew(() =>
            {
                foreach (var season in show.Seasons.OrderByDescending(w => w.SeasonNumber))
                {
                    foreach (var episode in season.Episodes.OrderByDescending(w => w.EpisodeNumber))
                    {
                        var e = episode;

                        if (episode.ImageUrl != null)
                        {
                            var extension = Path.GetExtension(e.ImageUrl);
                            var file      = $"{show.ShowId}_{season.SeasonNumber}_{e.EpisodeNumber}{extension}";
                            var folder    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                         ConfigurationManager.AppSettings["IMAGE_CACHE"]);

                            if (!Directory.Exists(folder))
                            {
                                Directory.CreateDirectory(folder);
                            }

                            var filename = Path.Combine(folder, file);

                            if (!File.Exists(filename))
                            {
                                using (var web = new WebClient())
                                {
                                    web.DownloadFile(e.ImageUrl, filename);
                                }
                            }

                            Execute.BeginOnUIThread(() =>
                            {
                                try
                                {
                                    if (extension?.ToUpper() == ".PNG")
                                    {
                                        Stream imageStreamSource = new FileStream(filename, FileMode.Open,
                                                                                  FileAccess.Read, FileShare.Read);
                                        var decoder = new PngBitmapDecoder(imageStreamSource,
                                                                           BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                                        e.ImageSource = decoder.Frames[0];
                                    }
                                    else
                                    {
                                        try
                                        {
                                            e.ImageSource = new BitmapImage(new Uri(filename));
                                        }
                                        catch
                                        {
                                            //File most likely corrupted
                                            File.Delete(filename);
                                        }
                                    }
                                }
                                catch
                                {
                                    //supress
                                }
                            });
                        }

                        Execute.BeginOnUIThread(() => e.IsLoading = false);
                    }
                }
            });
        }
예제 #14
0
        public void Open(System.IO.Stream Source)
        {
            File CursorFile = new File();

            CursorFile.Read(Source);
            if (CursorFile.Type != FileType.CURSOR)
            {
                throw new InvalidOperationException();
            }
            foreach (Frame CursorFrame in CursorFile.Frames)
            {
                System.Windows.Media.Imaging.BitmapFrame frame = null;
                if (CursorFrame.type == FrameType.BITMAP)
                {
                    if (CursorFrame.iconImage.icHeader.biBitCount == 32)
                    {
                        byte[] pixels = CursorFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, CursorFrame.Width, CursorFrame.Height, CursorFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(CursorFrame.Width, CursorFrame.Height, 96, 96, PixelFormats.Bgra32, null, pixels, CursorFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else if (CursorFrame.iconImage.icHeader.biBitCount == 24)
                    {
                        byte[] pixels = CursorFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, CursorFrame.Width, CursorFrame.Height, CursorFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(CursorFrame.Width, CursorFrame.Height, 96, 96, PixelFormats.Bgra32, null, pixels, CursorFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else if (CursorFrame.iconImage.icHeader.biBitCount == 8)
                    {
                        byte[] pixels = CursorFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, CursorFrame.Width, CursorFrame.Height, CursorFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(CursorFrame.Width, CursorFrame.Height, 96, 96, PixelFormats.Indexed8, GetPalette(CursorFrame.iconImage.icColors, true), pixels, CursorFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else if (CursorFrame.iconImage.icHeader.biBitCount == 4)
                    {
                        byte[] pixels = CursorFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, CursorFrame.Width, CursorFrame.Height, CursorFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(CursorFrame.Width, CursorFrame.Height, 96, 96, PixelFormats.Indexed4, GetPalette(CursorFrame.iconImage.icColors, true), pixels, CursorFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else
                    {
                        try
                        {
                            byte[] pixels = CursorFrame.iconImage.icXOR;
                            pixels = Utilities.FlipYBuffer(pixels, CursorFrame.Width, CursorFrame.Height, CursorFrame.iconImage.XorStride);
                            BitmapSource bp = BitmapSource.Create(CursorFrame.Width, CursorFrame.Height, 96, 96, PixelFormats.Indexed1, GetPalette(CursorFrame.iconImage.icColors, true), pixels, CursorFrame.iconImage.XorStride);
                            frame = BitmapFrame.Create(bp);
                        }
                        catch { continue; }
                    }

                    if (CursorFrame.iconImage.icAND?.Length > 0)
                    {
                        RGBQUAD[] palette = new RGBQUAD[2] {
                            RGBQUAD.FromRGBA(0, 0, 0, 0), RGBQUAD.FromRGBA(255, 255, 255, 255)
                        };
                        byte[] pixels = CursorFrame.iconImage.icAND;
                        pixels = Utilities.FlipYBuffer(pixels, CursorFrame.Width, CursorFrame.Height, CursorFrame.iconImage.AndStride);
                        BitmapSource AND = BitmapSource.Create(CursorFrame.Width, CursorFrame.Height,
                                                               96, 96, PixelFormats.Indexed1, GetPalette(palette, true), pixels, CursorFrame.iconImage.AndStride);

                        EditableBitmapImage editableXOR = new EditableBitmapImage(frame);
                        EditableBitmapImage editableAND = new EditableBitmapImage(AND);
                        for (int x = 0; x < editableXOR.PixelWidth; x++)
                        {
                            for (int y = 0; y < editableXOR.PixelHeight; y++)
                            {
                                Color px = editableAND.GetPixel(x, y);
                                if (px == Colors.White)
                                {
                                    Color c = editableXOR.GetPixel(x, y);
                                    c.A = 0;
                                    editableXOR.SetPixel(x, y, c);
                                }
                            }
                        }
                        if (frame.Format.BitsPerPixel == 32)
                        {
                            // Do nothing
                        }
                        else if (frame.Format.BitsPerPixel == 24)
                        {
                            frame = BitmapFrame.Create(editableXOR);
                        }
                        else if (frame.Format.BitsPerPixel == 8)
                        {
                            BitmapSource s = Helpers.Get8BitImage(editableXOR);
                            frame = BitmapFrame.Create(s);
                        }
                        else if (frame.Format.BitsPerPixel == 4)
                        {
                            BitmapSource s = Helpers.Get4BitImage(editableXOR);
                            frame = BitmapFrame.Create(s);
                        }
                    }
                }
                else
                {
                    try
                    {
                        PngBitmapDecoder decoder = new PngBitmapDecoder(new System.IO.MemoryStream(CursorFrame.pngBuffer), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        frame = decoder.Frames[0];
                    }
                    catch
                    {
                        frame = BitmapFrame.Create(CreateEmptyBitmap(CursorFrame.Width));
                    }
                }
                _Frames.Add(frame);
                SetHotspot(frame, CursorFrame.iconDir.wPlanes, CursorFrame.iconDir.wBitCount);
            }
        }
        private void FillWebResourcesIcons(IList <CompletionSet> completionSets, ITrackingSpan applicableTo, IEnumerable <WebResource> webResources, string name)
        {
            if (webResources == null || !webResources.Any())
            {
                return;
            }

            List <CrmCompletion> list = new List <CrmCompletion>();

            foreach (var resource in webResources.OrderBy(s => s.Name))
            {
                StringBuilder str = new StringBuilder(resource.Name);

                List <string> compareValues = new List <string>()
                {
                    resource.Name
                };

                if (!string.IsNullOrEmpty(resource.DisplayName))
                {
                    compareValues.Add(resource.DisplayName);

                    str.AppendFormat(" - {0}", resource.DisplayName);
                }

                ImageSource image = _defaultGlyph;

                if (!string.IsNullOrEmpty(resource.Content))
                {
                    if (_cachedImages.ContainsKey(resource.Content))
                    {
                        _cachedImages.TryGetValue(resource.Content, out image);

                        if (image != null)
                        {
                            str.AppendFormat(" - {0}x{1}", Convert.ToInt32(image.Width), Convert.ToInt32(image.Height));
                        }
                        else
                        {
                            image = _defaultGlyph;
                        }
                    }

                    try
                    {
                        var array = Convert.FromBase64String(resource.Content);

                        if (array != null && array.Length > 0)
                        {
                            MemoryStream ms = new MemoryStream(array);

                            if (resource.WebResourceType?.Value == (int)WebResource.Schema.OptionSets.webresourcetype.PNG_format_5)
                            {
                                PngBitmapDecoder decoder = new PngBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                                if (decoder.Frames.Count > 0)
                                {
                                    var bitmapSource = decoder.Frames[0];

                                    image = bitmapSource;
                                }
                            }
                            else
                            {
                                BitmapImage biImg = new BitmapImage();

                                biImg.DecodePixelHeight = biImg.DecodePixelWidth = 16;

                                biImg.BeginInit();
                                biImg.StreamSource = ms;
                                biImg.EndInit();

                                image = biImg;
                            }

                            if (image != null)
                            {
                                _cachedImages.TryAdd(resource.Content, image);

                                str.AppendFormat(" - {0}x{1}", Convert.ToInt32(image.Width), Convert.ToInt32(image.Height));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        DTEHelper.WriteExceptionToLog(ex);

                        image = _defaultGlyph;
                    }
                }

                string insertText = string.Format("$webresource:{0}", resource.Name);

                list.Add(CreateCompletion(str.ToString(), insertText, resource.Description, image, compareValues));
            }

            completionSets.Add(new CrmCompletionSet(SourceNameMonikerWebResourcesIcon, name, applicableTo, list, Enumerable.Empty <CrmCompletion>()));
        }
예제 #16
0
        internal void Load()
        {
            try
            {
                // If we have a loading function, use that to get the url we want to load
                if (loading != null)
                {
                    this.url = loading();
                }

                // We explicitly use the WebClient here because we need access to the system-wide browser cache and cookies collection
                var client = new WebClient {
                    CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable)
                };

                var stream = new MemoryStream();

                using (var istream = client.OpenRead(url))
                {
                    // Read stream into our own byte buffer on the background thread
                    istream.CopyTo(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                }

                Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action) delegate
                {
                    try
                    {
                        // Create imagesource on the foreground thread
                        string extension = Path.GetExtension(url).ToLower();
                        BitmapDecoder decoder;

                        if (extension == ".gif")
                        {
                            decoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        }
                        else if (extension == ".png")
                        {
                            decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        }
                        else if (extension == ".jpg")
                        {
                            decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        }
                        else if (extension == ".bmp")
                        {
                            decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        }
                        else
                        {
                            throw new ApplicationException(String.Format("Unsupported extension in AsyncHttpImage. Exception = {0}", extension));
                        }

                        AsyncSource = decoder.Frames[0];
                        AsyncSource.Freeze();

                        if (PropertyChanged != null)
                        {
                            PropertyChanged(this, new PropertyChangedEventArgs("AsyncSource"));
                        }

                        if (loaded != null)
                        {
                            loaded();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("An error has occured while trying to download an AsyncHttpImage. Url = {0} Exception = {1}", LogSource.BackgroundTask, url, ex);
                    }
                    finally
                    {
                        stream.Dispose();
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.Error("An error has occured while trying to download an AsyncHttpImage. Url = {0} Exception = {1}", LogSource.BackgroundTask, url, ex);
            }
        }
예제 #17
0
        // Decodes an image in memory to show it on the screen
        private BitmapSource memDecode(byte[] bytes)
        {
            BitmapFrame     frame;
            WriteableBitmap output;

            try
            {
                using (MemoryStream stream = new MemoryStream(bytes))
                {
                    switch (termExt)
                    {
                    case "gif":
                        GifBitmapDecoder gifDecoder = new GifBitmapDecoder(stream,
                                                                           BitmapCreateOptions.IgnoreColorProfile |
                                                                           BitmapCreateOptions.PreservePixelFormat,
                                                                           BitmapCacheOption.OnLoad);
                        frame = gifDecoder.Frames.First();
                        break;

                    case "png":
                        PngBitmapDecoder pngDecoder = new PngBitmapDecoder(stream,
                                                                           BitmapCreateOptions.IgnoreColorProfile |
                                                                           BitmapCreateOptions.PreservePixelFormat,
                                                                           BitmapCacheOption.OnLoad);
                        frame = pngDecoder.Frames.First();
                        break;

                    case "tiff":
                        TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(stream,
                                                                              BitmapCreateOptions.IgnoreColorProfile |
                                                                              BitmapCreateOptions.PreservePixelFormat,
                                                                              BitmapCacheOption.OnLoad);
                        frame = tiffDecoder.Frames.First();
                        break;

                    case "jpg":
                        JpegBitmapDecoder jpgDecoder = new JpegBitmapDecoder(stream,
                                                                             BitmapCreateOptions.IgnoreColorProfile |
                                                                             BitmapCreateOptions.PreservePixelFormat,
                                                                             BitmapCacheOption.OnLoad);
                        frame = jpgDecoder.Frames.First();
                        break;

                    case "jp2":
                        var j2kImg = J2kImage.FromStream(stream);
                        output = j2kImg.As <WriteableBitmap>();
                        frame  = BitmapFrame.Create(output);
                        break;

                    default:
                        BmpBitmapDecoder bmpDecoder = new BmpBitmapDecoder(stream,
                                                                           BitmapCreateOptions.IgnoreColorProfile |
                                                                           BitmapCreateOptions.PreservePixelFormat,
                                                                           BitmapCacheOption.OnLoad);
                        frame = bmpDecoder.Frames.First();
                        break;
                    }
                    if (bpp < 4)
                    {
                        frame = BitmapFrame.Create(new FormatConvertedBitmap(frame, PixelFormats.Rgb24, null, 0));
                    }
                    else
                    {
                        frame = BitmapFrame.Create(new FormatConvertedBitmap(frame, PixelFormats.Rgba64, null, 0));
                    }
                    frame.Freeze();
                    return(frame);
                }
            }
            catch
            {
                output = new WriteableBitmap(400, 400, 72, 72, PixelFormats.Bgr24, null);
                frame  = BitmapFrame.Create(output);
                return(frame);
            }
        }
예제 #18
0
        private void LoadImage(MemoryStream stream, ImageFormat format)
        {
            mipMaps = new List <MipMap>();
            switch (format)
            {
            case ImageFormat.DDS:
            {
                LoadImageDDS(stream, format);
                break;
            }

            case ImageFormat.TGA:
            {
                LoadImageTGA(stream, format);
                break;
            }

            case ImageFormat.BMP:
            {
                LoadImageBMP(stream, format);
                break;
            }

            case ImageFormat.PNG:
            case ImageFormat.JPEG:
            {
                BitmapSource frame = null;
                if (format == ImageFormat.PNG)
                {
                    frame = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0];
                }
                else if (format == ImageFormat.JPEG)
                {
                    frame = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0];
                }

                if (!checkPowerOfTwo(frame.PixelWidth) ||
                    !checkPowerOfTwo(frame.PixelHeight))
                {
                    throw new Exception("dimensions not power of two");
                }

                FormatConvertedBitmap srcBitmap = new FormatConvertedBitmap();
                srcBitmap.BeginInit();
                srcBitmap.Source            = frame;
                srcBitmap.DestinationFormat = PixelFormats.Bgra32;
                srcBitmap.EndInit();

                byte[] pixels = new byte[srcBitmap.PixelWidth * srcBitmap.PixelHeight * 4];
                frame.CopyPixels(pixels, srcBitmap.PixelWidth * 4, 0);

                pixelFormat = PixelFormat.ARGB;
                MipMap mipmap = new MipMap(pixels, srcBitmap.PixelWidth, srcBitmap.PixelHeight, PixelFormat.ARGB);
                mipMaps.Add(mipmap);
                break;
            }

            default:
                throw new Exception();
            }
        }
예제 #19
0
        public D2Window(Form mainWindow, D2HostPanel overlayControl, IntPtr diablo2Handle)
        {
            this.mainWindow    = mainWindow;
            this.handle        = diablo2Handle;
            this.targetControl = overlayControl;

            this.mainWindow.Move       += new EventHandler(OnParentMove);
            this.targetControl.KeyDown += new System.Windows.Forms.KeyEventHandler(targetControl_KeyDown);
            this.targetControl.KeyUp   += new System.Windows.Forms.KeyEventHandler(targetControl_KeyUp);

            this.targetControl.RegisterEvents();

            underlayForm = new Form();
            underlayForm.FormBorderStyle = FormBorderStyle.None;
            underlayForm.Text            = "D2 Container Window";
            underlayForm.Controls.Add(new Panel()
            {
                Width = Screen.PrimaryScreen.WorkingArea.Width, Height = Screen.PrimaryScreen.WorkingArea.Height
            });
            underlayForm.ShowInTaskbar = false;
            underlayForm.Show();

            Mouse.OverrideCursor = System.Windows.Input.Cursors.None;

            overlayForm            = new D2OverlayWindow();
            overlayForm.MouseMove += new System.Windows.Input.MouseEventHandler(overlayForm_MouseMove);
            overlayForm.Width      = 1600;
            overlayForm.Height     = 1200;
            overlayForm.Show();

            HwndSource hwndSource = PresentationSource.FromVisual(overlayForm) as HwndSource;

            System.Windows.Point formSize = hwndSource.CompositionTarget.TransformFromDevice.Transform(new System.Windows.Point(targetControl.Width, targetControl.Height));

            scaleX = formSize.X / 800;
            scaleY = formSize.Y / 600;

            this.overlayForm.Canvas.RenderTransform = new ScaleTransform(scaleX, scaleY);

            System.IO.Stream fileStream = this.GetType().Assembly.GetManifestResourceStream("D2PartyTime.Resources.D2Cursor.png");
            if (fileStream != null)
            {
                PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                ImageSource      imageSource   = bitmapDecoder.Frames[0];

                d2Cursor = new System.Windows.Controls.Image();
                d2Cursor.IsHitTestVisible = false;
                //d2Cursor.MouseMove += new System.Windows.Input.MouseEventHandler(d2Cursor_MouseMove);
                d2Cursor.Source  = imageSource;
                d2Cursor.Stretch = Stretch.Uniform;

                d2Cursor.Visibility = Visibility.Hidden;

                overlayForm.Canvas.Children.Add(d2Cursor);
            }

            RegisterThumbnail();
            Hide();

            OnParentMove(null, null);

            this.mainWindow.Activate();
        }
예제 #20
0
        public object ReadPng(Stream stream)
        {
            PngBitmapDecoder?decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            return(decoder.Frames[0].Clone());
        }
예제 #21
0
        //static readonly byte[] pngHeader = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
        //static readonly byte[] jpgHeader = { 0xFF, 0xD8, 0xFF };
        //static readonly byte[] gifHeader = { 0x47, 0x49, 0x46 };
        //static readonly byte[] bmpHeader = { 0x42, 0x4D };

        public override PureImage FromStream(System.IO.Stream stream)
        {
            WindowsPresentationImage ret = null;

            if (stream != null)
            {
                var type = stream.ReadByte();
                stream.Position = 0;

                ImageSource m = null;

                switch (type)
                {
                // PNG: 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A
                case 0x89:
                {
                    var bitmapDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                    m             = bitmapDecoder.Frames[0];
                    bitmapDecoder = null;
                }
                break;

                // JPG: 0xFF, 0xD8, 0xFF
                case 0xFF:
                {
                    var bitmapDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                    m             = bitmapDecoder.Frames[0];
                    bitmapDecoder = null;
                }
                break;

                // GIF: 0x47, 0x49, 0x46
                case 0x47:
                {
                    var bitmapDecoder = new GifBitmapDecoder(stream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                    m             = bitmapDecoder.Frames[0];
                    bitmapDecoder = null;
                }
                break;

                // BMP: 0x42, 0x4D
                case 0x42:
                {
                    var bitmapDecoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                    m             = bitmapDecoder.Frames[0];
                    bitmapDecoder = null;
                }
                break;

                // TIFF: 0x49, 0x49 || 0x4D, 0x4D
                case 0x49:
                case 0x4D:
                {
                    var bitmapDecoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                    m             = bitmapDecoder.Frames[0];
                    bitmapDecoder = null;
                }
                break;

                default:
                {
                }
                break;
                }

                if (m != null)
                {
                    ret     = new WindowsPresentationImage();
                    ret.Img = m;
                    if (ret.Img.CanFreeze)
                    {
                        ret.Img.Freeze();
                    }
                }
            }
            return(ret);
        }
예제 #22
0
        public override PureImage FromStream(System.IO.Stream stream)
        {
            WindowsPresentationImage ret = null;

            if (stream != null)
            {
                // try png decoder
                try
                {
                    PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                    ImageSource      m             = bitmapDecoder.Frames[0];

                    if (m != null)
                    {
                        ret     = new WindowsPresentationImage();
                        ret.Img = m;
                        if (ret.Img.CanFreeze)
                        {
                            ret.Img.Freeze();
                        }
                    }

                    m             = null;
                    bitmapDecoder = null;
                }
                catch
                {
                    // try jpeg decoder
                    try
                    {
                        stream.Seek(0, System.IO.SeekOrigin.Begin);

                        JpegBitmapDecoder bitmapDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                        ImageSource       m             = bitmapDecoder.Frames[0];

                        if (m != null)
                        {
                            ret     = new WindowsPresentationImage();
                            ret.Img = m;
                            if (ret.Img.CanFreeze)
                            {
                                ret.Img.Freeze();
                            }
                        }

                        m             = null;
                        bitmapDecoder = null;
                    }
                    catch
                    {
                        ret = null;
                    }
                }
                finally
                {
                    try
                    {
                        stream.Seek(0, System.IO.SeekOrigin.Begin);

                        if (ret == null)
                        {
                            stream.Dispose();
                        }
                    }
                    catch
                    {
                    }
                }
            }
            return(ret);
        }
예제 #23
0
        public Image GetImage()
        {
            if ((previewData == null) || (previewData.Length <= 0))
            {
                using (Bitmap bitmap = new Bitmap(128, 128))
                {
                    return(bitmap.Clone() as Bitmap);
                }
            }

            int startingOffset = GetPngStartingOffset();

            if (startingOffset == 0)
            {
                using (Bitmap bitmap = new Bitmap(128, 128))
                {
                    return(bitmap.Clone() as Bitmap);
                }
            }

            try
            {
                byte[] pngDataBuffer = new byte[previewData.GetUpperBound(0) - startingOffset + 1];
                using (MemoryStream memoryStream = new MemoryStream(previewData))
                {
                    memoryStream.Position = startingOffset;
                    memoryStream.Read(pngDataBuffer, 0, pngDataBuffer.Length);
                }

                byte[] decoderData = null;

                if (pngDataBuffer != null)
                {
                    using (MemoryStream memoryStream = new MemoryStream(pngDataBuffer))
                    {
                        PngBitmapDecoder pngBitmapDecoder = new PngBitmapDecoder(memoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        decoderData = BitmapSourceToArray(pngBitmapDecoder.Frames[0]);
                    }
                }

                if ((decoderData != null) && (decoderData.Length > 0))
                {
                    using (MemoryStream memoryStream = new MemoryStream(decoderData))
                    {
                        using (Bitmap bitmap = new Bitmap((memoryStream)))
                        {
                            using (Image image = bitmap)
                            {
                                return(image.Clone() as Image);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                string messsage = exception.Message;
            }

            using (Bitmap bitmap = new Bitmap(128, 128))
            {
                return(bitmap.Clone() as Bitmap);
            }
        }
예제 #24
0
        /// <summary>
        /// Method to apply meta data in the jpg file
        /// </summary>
        /// <param name="inputFileName">input file name</param>
        /// <param name="outputFileName">output file name</param>
        /// <param name="metaDataCollection">Metadata collection</param>
        /// <returns></returns>
        public MetadataResult ApplyMetaData(string inputFileName, string outputFileName, List <DocumentData> metaDataCollection)
        {
            MetadataResult retDataCol = new MetadataResult();

            if (metaDataCollection == null)
            {
                retDataCol.Status  = "Error";
                retDataCol.Message = "There has to be at least 1 metadata field that needs to be applied to the assest";
            }

            try
            {
                using (FileStream fileStream = File.Open(inputFileName, FileMode.Open))
                {
                    //Creating the bitmat decoder from the input file streaam
                    BitmapDecoder decoder = PngBitmapDecoder.Create(fileStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);

                    BitmapMetadata md = new BitmapMetadata("png");

                    //Creating the frame with the meta data
                    BitmapFrame frame = BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, md, decoder.Frames[0].ColorContexts);

                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    // BitmapMetadata md = new BitmapMetadata("png");
                    encoder.Frames.Add(frame);

                    int ctr = 0;

                    foreach (DocumentData documentData in metaDataCollection)
                    {
                        if (ctr == 0)
                        {
                            //Adding the meta data
                            // md.SetQuery(@"/Text/" + key, metaDataCollection[key]);
                            md.SetQuery("/iTXt/Keyword", documentData.Key.ToCharArray()); // need to convert using ToCharArray as internal representation is based on the LPSTR C type
                            md.SetQuery("/iTXt/TextEntry", documentData.Text);
                        }
                        else
                        {
                            md.SetQuery("/[" + ctr + "]iTXt/" + "Keyword", documentData.Key.ToCharArray()); // need to convert using ToCharArray as internal representation is based on the LPSTR C type
                            md.SetQuery("/[" + ctr + "]iTXt/" + "TextEntry", documentData.Text);
                        }
                        ctr++;
                    }

                    // encoder.Frames.Add(frame);

                    //after assigning the meta data saving to another file
                    using (FileStream of = File.Open(outputFileName, FileMode.Create, FileAccess.Write))
                    {
                        encoder.Save(of);
                        of.Close();
                    }
                }

                retDataCol.Status  = "Success";
                retDataCol.Message = "Metadata applied successfully.";
            }
            catch (Exception ex)
            {
                retDataCol.Status  = "Error";
                retDataCol.Message = ex.ToString();
                //Logger.LogError("JPEGImageDocument", "ApplyMetaData", inputFileName, outputFileName, ex);
            }

            return(retDataCol);
        }
예제 #25
0
파일: Images.cs 프로젝트: Puddler/Chess
        public Images()
        {
            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.WhitePawn.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.WhitePawn = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.WhiteRook.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.WhiteRook = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.WhiteBishop.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.WhiteBishop = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.WhiteKnight.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.WhiteKnight = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.WhiteQueen.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.WhiteQueen = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.WhiteKing.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.WhiteKing = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.BlackPawn.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.BlackPawn = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.BlackRook.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.BlackRook = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.BlackBishop.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.BlackBishop = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.BlackKnight.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.BlackKnight = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.BlackQueen.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.BlackQueen = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Images.BlackKing.png"))
            {
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.BlackKing = decoder.Frames[0];
            }

            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("Chess.Icon.ico"))
            {
                IconBitmapDecoder decoder = new IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                this.Icon = decoder.Frames[0];
            }
        }
예제 #26
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {
                Title = "PNG Imaging Sample"
            };
            var mySv = new ScrollViewer();

            var width  = 128;
            var height = 128;
            var stride = width;
            var pixels = new byte[width * stride];

            // Define the image palette
            var myPalette = BitmapPalettes.Halftone256;

            // Creates a new empty image with the pre-defined palette

            var image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed8,
                myPalette,
                pixels,
                stride);

            var stream      = new FileStream("new.png", FileMode.Create);
            var encoder     = new PngBitmapEncoder();
            var myTextBlock = new TextBlock {
                Text = "Codec Author is: " + encoder.CodecInfo.Author
            };

            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);


            // Open a Stream and decode a PNG image
            Stream imageStreamSource = new FileStream("smiley.png", FileMode.Open, FileAccess.Read, FileShare.Read);
            var    decoder           = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat,
                                                            BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];

            // Draw the Image
            var myImage = new Image
            {
                Source  = bitmapSource,
                Stretch = Stretch.None,
                Margin  = new Thickness(20)
            };


            // Open a Uri and decode a PNG image
            var myUri    = new Uri("smiley.png", UriKind.RelativeOrAbsolute);
            var decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat,
                                                BitmapCacheOption.Default);
            BitmapSource bitmapSource2 = decoder2.Frames[0];

            // Draw the Image
            var myImage2 = new Image
            {
                Source  = bitmapSource2,
                Stretch = Stretch.None,
                Margin  = new Thickness(20)
            };

            // Define a StackPanel to host the decoded PNG images
            var myStackPanel = new StackPanel
            {
                Orientation         = Orientation.Vertical,
                VerticalAlignment   = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch
            };

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            mySv.Content        = myStackPanel;
            _mainWindow.Content = mySv;
            _mainWindow.Show();
        }
예제 #27
0
        /// <summary>
        /// Search archive <paramref name="arc"/> for baseline image.
        /// </summary>
        internal void ReadBaseline(BellArchive arc, Entry entry)
        {
            var header = ReadHeader();

            if (!((header[0] & 1) == 1 && 'd' == this.Type ||
                  header[0] == 1 && 'a' == this.Type))
            {
                return;
            }
            var scheme = arc.Scheme;
            var dir    = (List <Entry>)arc.Dir;
            int i      = dir.IndexOf(entry);

            while (--i >= 0 && "image" == dir[i].Type)
            {
                using (var input = arc.OpenEntry(dir[i]))
                {
                    int type = input.ReadByte();
                    if ('d' == type)
                    {
                        continue;
                    }
                    if ('a' == type)
                    {
                        int id = input.ReadByte();
                        if (id != scheme.Value2)
                        {
                            break;
                        }
                        using (var bin = new BinaryStream(input, dir[i].Name))
                            using (var base_image = new AImageReader(bin, scheme))
                            {
                                var base_header = base_image.ReadHeader();
                                if (1 == base_header[0])
                                {
                                    continue;
                                }
                                // check if image width/height are the same
                                if (base_header[3] == header[3] && base_header[4] == header[4])
                                {
                                    base_image.Unpack();
                                    Baseline = base_image.Data;
                                }
                            }
                    }
                    else if ('b' == type || 'c' == type)
                    {
                        var size_buf = new byte[4];
                        input.Read(size_buf, 0, 4);
                        var decoder = new PngBitmapDecoder(input, BitmapCreateOptions.None,
                                                           BitmapCacheOption.OnLoad);
                        BitmapSource frame = decoder.Frames[0];
                        Info.Width  = (uint)frame.PixelWidth;
                        Info.Height = (uint)frame.PixelHeight;
                        if (frame.Format.BitsPerPixel != 32)
                        {
                            frame = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, null, 0);
                        }
                        int stride = frame.PixelWidth * 4;
                        var pixels = new byte[stride * frame.PixelHeight];
                        frame.CopyPixels(pixels, stride, 0);
                        Baseline = pixels;
                    }
                    break;
                }
            }
        }
예제 #28
0
        public void Load(string filename, FileTypes type)
        {
            Tags.Clear();
            Title       = "";
            Description = "";
            City        = "";
            Sublocation = "";
            Country     = "";
            DateTaken   = new DateTime(2000, 1, 1);
            FileName    = filename;
            GeoLat      = GeoLong = null;
            StarRating  = 0;
            Author      = "";

            if (type == FileTypes.FileTypeUnknown)
            {
                if (filename.EndsWith(".jpg", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeJpeg;
                }
                else if (filename.EndsWith(".jpeg", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeJpeg;
                }
                else if (filename.EndsWith(".gif", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeGIF;
                }
                else if (filename.EndsWith(".png", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypePNG;
                }
                else if (filename.EndsWith(".tif", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeTiff;
                }
                else if (filename.EndsWith(".tiff", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeTiff;
                }
                else if (filename.EndsWith(".bmp", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeBmp;
                }
            }

            try
            {
                Stream         pictureStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
                BitmapMetadata bitmapMetadata;

                switch (type)
                {
                case FileTypes.FileTypeJpeg:
                    JpegBitmapDecoder JpegDecoder = new JpegBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)JpegDecoder.Frames[0].Metadata;

                    /* InPlaceBitmapMetadataWriter writer = JpegDecoder.Frames[0].CreateInPlaceBitmapMetadataWriter();
                     * writer.Comment = writer.Title;
                     * writer.TrySave();*/

                    // Try getting keywords first from XMP
                    int xmpkeywordindex = 0;
                    do
                    {
                        try
                        {
                            string keyword = (string)bitmapMetadata.GetQuery(@"/xmp/dc:subject/{ushort=" + xmpkeywordindex.ToString() + "}");
                            if (string.IsNullOrEmpty(keyword))
                            {
                                break;
                            }

                            Tags.Add(keyword);
                        }
                        catch (Exception)
                        {
                            break;
                        }

                        xmpkeywordindex++;
                    } while (true);

                    // If XMP had no keywords, get it from IPTC Keywords
                    if (bitmapMetadata.Keywords != null && Tags.Count == 0)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title = (string)bitmapMetadata.GetQuery(@"/xmp/dc:title/{ushort=0}");
                    if (string.IsNullOrEmpty(Title))
                    {
                        Title = bitmapMetadata.Title;
                    }

                    Description = (string)bitmapMetadata.GetQuery(@"/xmp/dc:description/{ushort=0}");
                    if (string.IsNullOrEmpty(Description))
                    {
                        Description = bitmapMetadata.Comment;
                    }

                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    Author = (string)bitmapMetadata.GetQuery(@"/xmp/dc:creator/{ushort=0}");
                    if (string.IsNullOrEmpty(Author) && bitmapMetadata.Author.Count > 0)
                    {
                        Author = bitmapMetadata.Author[0];
                    }

                    City = (string)bitmapMetadata.GetQuery(@"/xmp/<xmpbag>photoshop:City");
                    if (string.IsNullOrEmpty(City))
                    {
                        City = (string)bitmapMetadata.GetQuery(@"/app13/irb/8bimiptc/iptc/city");
                    }

                    if (City == null)
                    {
                        City = "";
                    }

                    Sublocation = (string)bitmapMetadata.GetQuery(@"/xmp/<xmpbag>photoshop:Location");
                    if (string.IsNullOrEmpty(Sublocation))
                    {
                        Sublocation = (string)bitmapMetadata.GetQuery(@"/app13/irb/8bimiptc/iptc/sub-location");
                    }

                    if (Sublocation == null)
                    {
                        Sublocation = "";
                    }

                    Country = (string)bitmapMetadata.GetQuery(@"/xmp/<xmpbag>photoshop:Country");
                    if (string.IsNullOrEmpty(Country))
                    {
                        Country = (string)bitmapMetadata.GetQuery(@"/app13/irb/8bimiptc/iptc/country\/primary location name");
                    }

                    if (Country == null)
                    {
                        Country = "";
                    }

                    StarRating = bitmapMetadata.Rating;

                    byte[] Version = (byte[])bitmapMetadata.GetQuery(@"/app1/ifd/gps/");
                    if (Version != null)
                    {
                        ulong[] GeoLatInfo       = (ulong[])bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{ulong=2}");
                        string  GeoLatDirection  = (string)bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{char=1}");
                        ulong[] GeoLongInfo      = (ulong[])bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{ulong=4}");
                        string  GeoLongDirection = (string)bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{char=3}");

                        if (GeoLatInfo != null && GeoLatDirection != null)
                        {
                            GeoLat = ConvertCoordinate(GeoLatInfo);
                            if (GeoLatDirection == "S")
                            {
                                GeoLat = -GeoLat;
                            }
                        }

                        if (GeoLongInfo != null && GeoLongDirection != null)
                        {
                            GeoLong = ConvertCoordinate(GeoLongInfo);
                            if (GeoLongDirection == "W")
                            {
                                GeoLong = -GeoLong;
                            }
                        }
                    }

                    break;

                case FileTypes.FileTypeTiff:
                    TiffBitmapDecoder TiffDecoder = new TiffBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)TiffDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;

                case FileTypes.FileTypeGIF:
                    GifBitmapDecoder GifDecoder = new GifBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)GifDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;

                case FileTypes.FileTypePNG:
                    PngBitmapDecoder PngDecoder = new PngBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)PngDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;

                case FileTypes.FileTypeBmp:
                    BmpBitmapDecoder BmpDecoder = new BmpBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)BmpDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;
                }

                pictureStream.Close();
            }
            catch (Exception)
            {
            }

            if (Title == null)
            {
                Title = "";
            }
            if (Description == null)
            {
                Description = "";
            }
        }
예제 #29
0
        public void Load(string filename, FileTypes type)
        {
            Tags.Clear();
            Title       = "";
            Description = "";
            City        = "";
            Sublocation = "";
            Country     = "";
            DateTaken   = new DateTime(2000, 1, 1);
            FileName    = filename;
            GeoLat      = GeoLong = null;
            StarRating  = 0;

            if (type == FileTypes.FileTypeUnknown)
            {
                if (filename.EndsWith(".jpg", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeJpeg;
                }
                else if (filename.EndsWith(".jpeg", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeJpeg;
                }
                else if (filename.EndsWith(".gif", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeGIF;
                }
                else if (filename.EndsWith(".png", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypePNG;
                }
                else if (filename.EndsWith(".tif", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeTiff;
                }
                else if (filename.EndsWith(".tiff", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeTiff;
                }
                else if (filename.EndsWith(".bmp", System.StringComparison.CurrentCultureIgnoreCase))
                {
                    type = FileTypes.FileTypeBmp;
                }
            }

            try
            {
                Stream         pictureStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
                BitmapMetadata bitmapMetadata;

                switch (type)
                {
                case FileTypes.FileTypeJpeg:
                    JpegBitmapDecoder JpegDecoder = new JpegBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)JpegDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    //City = (string)bitmapMetadata.GetQuery(@"/xmp/<xmpbag>photoshop:City");
                    City = (string)bitmapMetadata.GetQuery(@"/app13/irb/8bimiptc/iptc/city");
                    if (City == null)
                    {
                        City = "";
                    }

                    Sublocation = (string)bitmapMetadata.GetQuery(@"/app13/irb/8bimiptc/iptc/sub-location");
                    if (Sublocation == null)
                    {
                        Sublocation = "";
                    }

                    //Country = (string)bitmapMetadata.GetQuery(@"/xmp/<xmpbag>photoshop:Country");
                    Country = (string)bitmapMetadata.GetQuery(@"/app13/irb/8bimiptc/iptc/country\/primary location name");
                    if (Country == null)
                    {
                        Country = "";
                    }

                    byte[] Version = (byte[])bitmapMetadata.GetQuery(@"/app1/ifd/gps/");
                    if (Version != null)
                    {
                        ulong[] GeoLatInfo       = (ulong[])bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{ulong=2}");
                        string  GeoLatDirection  = (string)bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{char=1}");
                        ulong[] GeoLongInfo      = (ulong[])bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{ulong=4}");
                        string  GeoLongDirection = (string)bitmapMetadata.GetQuery(@"/app1/ifd/gps/subifd:{char=3}");

                        if (GeoLatInfo != null && GeoLatDirection != null)
                        {
                            GeoLat = ConvertCoordinate(GeoLatInfo);
                            if (GeoLatDirection == "S")
                            {
                                GeoLat = -GeoLat;
                            }
                        }

                        if (GeoLongInfo != null && GeoLongDirection != null)
                        {
                            GeoLong = ConvertCoordinate(GeoLongInfo);
                            if (GeoLongDirection == "W")
                            {
                                GeoLong = -GeoLong;
                            }
                        }
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;

                case FileTypes.FileTypeTiff:
                    TiffBitmapDecoder TiffDecoder = new TiffBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)TiffDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;

                case FileTypes.FileTypeGIF:
                    GifBitmapDecoder GifDecoder = new GifBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)GifDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;

                case FileTypes.FileTypePNG:
                    PngBitmapDecoder PngDecoder = new PngBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)PngDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;

                case FileTypes.FileTypeBmp:
                    BmpBitmapDecoder BmpDecoder = new BmpBitmapDecoder(pictureStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    bitmapMetadata = (BitmapMetadata)BmpDecoder.Frames[0].Metadata;

                    if (bitmapMetadata.Keywords != null)
                    {
                        foreach (string tag in bitmapMetadata.Keywords)
                        {
                            Tags.Add(tag);
                        }
                    }

                    Title       = bitmapMetadata.Title;
                    Description = bitmapMetadata.Comment;
                    if (bitmapMetadata.DateTaken != null)
                    {
                        DateTaken = DateTime.Parse(bitmapMetadata.DateTaken);
                    }

                    StarRating = bitmapMetadata.Rating;

                    break;
                }

                pictureStream.Close();
            }
            catch (Exception)
            {
            }

            if (Title == null)
            {
                Title = "";
            }
            if (Description == null)
            {
                Description = "";
            }
        }
예제 #30
0
        public void UpdateBitmaps(string name)
        {
            if (Directory.Exists(tempPath + "Okiaros"))
            {
                foreach (string currFile in Directory.GetFiles(tempPath + "Okiaros"))
                {
                    File.Delete(currFile);
                }
            }
            else
            {
                Directory.CreateDirectory(tempPath + "Okiaros");
            }

            string[] pngs = new string[Bitmaps.Count];
            for (int i = 0; i < pngs.Length; i++)
            {
                pngs[i] = name + @"\texture-" + i.ToString("d3") + ".png";
            }

            for (int i = 0; i < Bitmaps.Count; i++)
            {
                FileStream cFS = new FileStream(pngs[i], System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                Bitmaps[i] = new Bitmap(cFS);
                cFS.Close();
            }

            var palettes  = new List <string>(0);
            var toQuant   = new List <Bitmap>(0);
            var filenames = new List <string>(0);

            for (int i = 0; i < paletteAddresses.Count; i++)
            {
                if (!palettes.Contains(paletteAddresses[i].ToString("X")))
                {
                    toQuant.Add(Bitmaps[i]);
                    palettes.Add(paletteAddresses[i].ToString("X"));
                    filenames.Add(paletteAddresses[i].ToString() + "@" + textureAddresses[i].ToString() + ",0,0," + Bitmaps[i].Width.ToString() + "," + Bitmaps[i].Height.ToString());
                }
                else
                {
                    for (int k = 0; k < paletteAddresses.Count; k++)
                    {
                        if (paletteAddresses[i].ToString() == paletteAddresses[k].ToString())
                        {
                            int wi = toQuant[k].Width;
                            int he = toQuant[k].Height;
                            if (Bitmaps[i].Height > he)
                            {
                                he = Bitmaps[i].Height;
                            }
                            wi = wi + Bitmaps[i].Width;
                            var merge   = new Bitmap(wi, he);
                            var mergeGr = Graphics.FromImage(merge);
                            mergeGr.DrawImage(toQuant[k], new Rectangle(0, 0, toQuant[k].Width, toQuant[k].Height));
                            mergeGr.DrawImage(Bitmaps[i], new Rectangle(toQuant[k].Width, 0, Bitmaps[i].Width, Bitmaps[i].Height));
                            filenames[k] = filenames[k] + "@" + textureAddresses[i].ToString() + "," + toQuant[k].Width.ToString() + ",0," + Bitmaps[i].Width.ToString() + "," + Bitmaps[i].Height.ToString();
                            toQuant[k]   = merge;
                            k            = paletteAddresses.Count;
                        }
                    }
                }
            }

            pngs = Directory.GetFiles(tempPath + "Okiaros", "*.png");
            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.FileName    = "pngquant.exe";
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.Arguments   = "pngquant.exe ";
            string[] toQuantFilenames = new string[toQuant.Count];

            for (int i = 0; i < toQuant.Count; i++)
            {
                toQuantFilenames[i]  = tempPath + @"Okiaros\" + filenames[i];
                startInfo.Arguments += "\"" + toQuantFilenames[i] + ".png" + "\" ";
                toQuant[i].Save(toQuantFilenames[i] + ".png");
            }

            Process.Start(startInfo);
            while (Process.GetProcessesByName("pngquant").Length > 0)
            {
            }

            for (int i = 0; i < toQuantFilenames.Length; i++)
            {
                File.Delete(toQuantFilenames[i] + ".png");
                toQuantFilenames[i] += "-fs8.png";
            }

            for (int g = 0; g < toQuantFilenames.Length; g++)
            {
                string   curr              = toQuantFilenames[g];
                string   filename_         = Path.GetFileName(curr).Split('-')[0];
                string[] bounds            = filename_.Split('@');
                int      newPaletteAddress = (int)(int.Parse(bounds[0]));
                var      stream            = new System.IO.FileStream(curr, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                var      bitm2Palette      = new Bitmap(stream);
                var      decoder           = new PngBitmapDecoder(stream,
                                                                  BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                var bitmapSource = decoder.Frames[0];
                var palette      = new List <System.Windows.Media.Color>(bitmapSource.Palette.Colors);
                while (palette.Count < 256)
                {
                    palette.Add(System.Windows.Media.Colors.Black);
                }

                /*if (checkBox1.Checked)
                 *              palette.Sort((System.Windows.Media.Color left, System.Windows.Media.Color right) => (BrightNess(left)).CompareTo(BrightNess(right)));*/

                for (int c = 0; c < 256; c++)
                {
                    int colorSlot = ((64 * ((c / 8) % 2) + ((c / 32) * 128) + (8 * ((c / 16) % 2)) + (c % 8)) * 4);
                    if (colorSlot < timBinary.Buffer.Length - 3)
                    {
                        timBinary.Buffer[newPaletteAddress + colorSlot]     = (byte)palette[c].R;
                        timBinary.Buffer[newPaletteAddress + colorSlot + 1] = (byte)palette[c].G;
                        timBinary.Buffer[newPaletteAddress + colorSlot + 2] = (byte)palette[c].B;
                        timBinary.Buffer[newPaletteAddress + colorSlot + 3] = (byte)((palette[c].A + 1) / 2);
                    }
                }

                for (int i = 1; i < bounds.Length; i++)
                {
                    string[]   splited      = bounds[i].Split(',');
                    int        pixAddress   = (int)(int.Parse(splited[0]));
                    Bitmap     CropBitmap   = bitm2Palette.Clone(new Rectangle(int.Parse(splited[1]), int.Parse(splited[2]), int.Parse(splited[3]), int.Parse(splited[4])), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    LockBitmap CropBitmapLK = new LockBitmap(CropBitmap);
                    CropBitmapLK.LockBits();
                    if (dmyCount > 0 && pixAddress >= DMY)
                    {
                        for (ushort x = 0; x < CropBitmap.Width; x++)
                        {
                            for (ushort y = 0; y < CropBitmap.Height; y++)
                            {
                                System.Windows.Media.Color currCol = CropBitmapLK.GetPixel(x, y);
                                int pos = pixAddress + (y * CropBitmap.Width) + x;
                                if (pos > timBinary.Buffer.Length - 1)
                                {
                                    pos = timBinary.Buffer.Length - 1;
                                }
                                timBinary.Buffer[pos] = (byte)palette.IndexOf(currCol); //433
                            }
                        }
                    }
                    else
                    {
                        int textW2 = (CropBitmap.Width * 2);
                        int textW4 = (CropBitmap.Width * 4);
                        for (int x = 0; x < CropBitmap.Width; x++)
                        {
                            ushort xMOD16  = (ushort)(x % 16);
                            ushort xMOD8   = (ushort)(x % 8);
                            ushort xOVER16 = (ushort)(x / 16);
                            for (int y = 0; y < CropBitmap.Height; y++)
                            {
                                System.Windows.Media.Color currCol = CropBitmapLK.GetPixel(x, y);
                                ushort yOVER4 = (ushort)(y / 4);
                                ushort yMOD2  = (ushort)(y % 2);
                                ushort yMOD4  = (ushort)(y % 4);
                                ushort yMOD8  = (ushort)(y % 8);
                                int    offset = 32 * (xOVER16) + (4 * (xMOD16)) - (30 * ((xMOD16) >> 3)) + ((System.Byte)(y & 1)) * textW2 + ((System.Byte)(y >> 2)) * textW4 + ((((System.Byte)(y & 3)) >> 1) + (((xMOD8) >> 2) * -1 + (1 - ((xMOD8) >> 2))) * 16 * (((System.Byte)(y & 3)) >> 1) + (((xMOD8) >> 2) * -1 + (1 - ((xMOD8) >> 2))) * 16 * (((System.Byte)(y & 7)) >> 2)) * (1 - (((System.Byte)(y & 7)) >> 2) * (((System.Byte)(y & 3)) >> 1)) + (((System.Byte)(y & 7)) >> 2) * (((System.Byte)(y & 3)) >> 1);
                                if (pixAddress + offset < timBinary.Buffer.Length)
                                {
                                    timBinary.Buffer[pixAddress + offset] = (byte)palette.IndexOf(currCol);
                                }
                            }
                        }
                    }
                }
                stream.Close();
                stream       = null;
                decoder      = null;
                bitmapSource = null;
                palette      = null;
                toQuant      = null;
                filenames    = null;
            }
        }