Inheritance: System.Windows.Media.Imaging.BitmapDecoder
Exemplo n.º 1
1
        /// <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;
        }
Exemplo n.º 2
1
        public void avilaImages()
        {
            try
            {

                Stream imageStreamSource = new FileStream("base.bmp", FileMode.Open, FileAccess.Read, FileShare.Read);

                BmpBitmapDecoder baseImage = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                BitmapSource baseImageSource = baseImage.Frames[0];

                //List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
                //colors.Add(System.Windows.Media.Colors.Red);
                //colors.Add(System.Windows.Media.Colors.Blue);
                //colors.Add(System.Windows.Media.Colors.Green);
                BitmapPalette palette = new BitmapPalette(baseImageSource, 8);

                WriteableBitmap bitmapImages = new WriteableBitmap(imageSizeX, imageSizeY, (double)600, (double)560, PixelFormats.Gray8, palette);
                WriteableBitmap bitmapImagesW = new WriteableBitmap(imageSizeX, imageSizeY, (double)600, (double)560, PixelFormats.Gray8, palette);

                string photoSaveLocation = Directory.GetCurrentDirectory();
                photoSaveLocation = photoSaveLocation + "\\images\\";

                imageDeleteLocation = photoSaveLocation;
                if (Directory.Exists(photoSaveLocation))
                {
                    Directory.Delete(photoSaveLocation, true);
                }
                Directory.CreateDirectory(photoSaveLocation);
                if (Directory.Exists(imageCopyLocation))
                {
                    Directory.Delete(imageCopyLocation, true);
                }
                Directory.CreateDirectory(imageCopyLocation);

                const int stride = imageSizeX;
                byte[] pixels = new byte[imageSizeX * imageSizeY];
                byte[] pixelsW = new byte[imageSizeX * imageSizeY];
                int currentImage = 0;
                if (layerSize < .001f)
                {
                    textBlock3.Text = "Layer size is too small";
                }
                else if (layerSize > .009f)
                {
                    textBlock3.Text = "Layer size is too large";
                }
                else
                {
                    numImages = imageSizeZ / layerSize;

                    int centerImage = (int)numImages / 2;
                    int sphereOffsetY = baseImageSizeY / 2;

                    int x, y, r2;

                    int pixelsX = (int)numImages;

                    byte[] circlePixels = new byte[pixelsX * pixelsX];

                    int offset = (int)(numImages) / 2;
                    int radius = (int)(sphereSizeZ / layerSize);
                    //int offsetY = radius;

                    byte sphereOneColor = sphereOneColorGlobal;

                    r2 = (int)radius * (int)radius;

                    circlePixels[(int)(offset + (offset + radius) * pixelsX)] = sphereOneColor;
                    circlePixels[(int)(offset + (offset - radius) * pixelsX)] = sphereOneColor;
                    circlePixels[(int)(offset + radius + (offset) * pixelsX)] = sphereOneColor;
                    circlePixels[(int)(offset - radius + (offset) * pixelsX)] = sphereOneColor;

                    y = radius;
                    x = 1;
                    y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                    while (x < y)
                    {
                        circlePixels[(int)(offset + x + (offset + y) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset + x + (offset - y) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset - x + (offset + y) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset - x + (offset - y) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset + y + (offset + x) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset + y + (offset - x) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset - y + (offset + x) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset - y + (offset - x) * pixelsX)] = sphereOneColor;
                        x += 1;
                        y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                    }
                    if (x == y)
                    {
                        circlePixels[(int)(offset + x + (offset + y) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset + x + (offset - y) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset - x + (offset + y) * pixelsX)] = sphereOneColor;
                        circlePixels[(int)(offset - x + (offset - y) * pixelsX)] = sphereOneColor;
                    }

                    WriteableBitmap view3D = new WriteableBitmap((int)pixelsX, (int)pixelsX, (double)600, (double)600, PixelFormats.Gray8, palette);
                    view3D.WritePixels(new Int32Rect(0, 0, pixelsX, pixelsX), circlePixels, pixelsX, 0);

                    BitmapEncoder view3DEnc = new BmpBitmapEncoder();
                    view3DEnc.Frames.Add(BitmapFrame.Create(view3D));

                    using (FileStream fs = new FileStream(photoSaveLocation + "view3D.bmp", FileMode.Create, FileAccess.Write))
                    {
                        view3DEnc.Save(fs);
                    }

                    for (int i = 0; i < numImages; i++)
                    {
                        for (int locationIndex = 0, colorIndex = 0; colorIndex < pixels.Length; locationIndex++, colorIndex += 1)
                        {
                            int columnLocation = locationIndex % imageSizeX;
                            int rowLocation = (int)(locationIndex / imageSizeX);

                            if (locationIndex >= (baseImageSizeY) * imageSizeX && locationIndex <= (baseImageSizeY + gapSize) * imageSizeX || locationIndex >= (baseImageSizeY * 2 + gapSize) * imageSizeX && locationIndex <= (baseImageSizeY * 2 + gapSize + gapSize) * imageSizeX)
                            {
                                pixels[colorIndex] = 0;
                            }
                            else
                            {
                                if (locationIndex < baseImageSizeY * imageSizeX)
                                {
                                    pixels[colorIndex] = backgroundColor;
                                }
                                else if (locationIndex < (baseImageSizeY * 2 + gapSize) * imageSizeX )
                                {
                                    pixels[colorIndex] = backgroundColor - colorOffsetLower1;
                                }
                                else if (locationIndex < (baseImageSizeY * 3 + gapSize + gapSize) * imageSizeX)
                                {
                                    pixels[colorIndex] = backgroundColor + colorOffsetUpper1;
                                }
                            }
                            pixelsW[colorIndex] = maxColor;
                        }

                        //bitmapImages.WritePixels(new Int32Rect(0, 0, imageSizeX, imageSizeY), pixels, stride, 0);
                        //Bitmap bmp;

                        //using (MemoryStream outStream = new MemoryStream())
                        //{
                        //    BitmapEncoder enc = new BmpBitmapEncoder();
                        //    enc.Frames.Add(BitmapFrame.Create((bitmapImages)));
                        //    enc.Save(outStream);
                        //    bmp = new System.Drawing.Bitmap(outStream);
                        //}

                        //Graphics graphicsProccesor = Graphics.FromImage(bmp);

                        //System.Drawing.Pen backgroudPen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(backgroundColor, backgroundColor, backgroundColor));

                        //System.Drawing.Pen sphere1Pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(sphereOneColor, sphereOneColor, sphereOneColor));
                        //System.Drawing.Pen sphere2Pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(sphereTwoColor, sphereTwoColor, sphereTwoColor));
                        //System.Drawing.Pen sphere3Pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(sphereThreeColor, sphereThreeColor, sphereThreeColor));

                        //graphicsProccesor.DrawEllipse(sphere1Pen, sphereOneOffset, (imageSizeY / 2), sphereSize, sphereSize);

                        //for (int x = 0; x < imageSizeX; x++)
                        //    for (int y = 0; y < imageSizeY; y++)
                        //    {
                        //        bmp.GetPixel(x, y).ToString();
                        //    }

                        for (int locationIndex = 0, colorIndex = 0; colorIndex < pixels.Length; locationIndex++, colorIndex += 1)
                        {

                            int columnLocation = locationIndex % imageSizeX;
                            int rowLocation = (int)(locationIndex / imageSizeX);

                            //pixels[colorIndex] = backgroundColor;
                            //pixelsW[colorIndex] = maxColor;

                            int sphereSize = 0;

                            int sphereOffset = sphereOneOffset;

                            //if (sphereSize > 0)
                            if (currentImage > centerImage - (sphereSizeZ / layerSize) && currentImage < centerImage + (sphereSizeZ / layerSize) && columnLocation == sphereOffset && rowLocation == sphereOffsetY)
                            {
                                sphereSize = (getRadius(currentImage, circlePixels, centerImage));

                                if (currentImage == centerImage)
                                {
                                    int test = 0;
                                }

                                r2 = sphereSize * sphereSize;
                                sphereOneColor = sphereOneColorGlobal;
                                byte sphereTwoColor = sphereTwoColorGlobal;
                                byte sphereThreeColor = sphereThreeColorGlobal;

                                pixels[(int)(sphereOffset + (sphereOffsetY + sphereSize) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset + (sphereOffsetY - sphereSize) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset + sphereSize + (sphereOffsetY) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset - sphereSize + (sphereOffsetY) * imageSizeX)] = sphereOneColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + y + (sphereOffsetY + x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + y + (sphereOffsetY - x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - y + (sphereOffsetY + x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - y + (sphereOffsetY - x) * imageSizeX)] = sphereOneColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                }

                                sphereOffset = sphereTwoOffset;
                                r2 = sphereSize * sphereSize;

                                pixels[(int)(sphereOffset + (sphereOffsetY + sphereSize) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset + (sphereOffsetY - sphereSize) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset + sphereSize + (sphereOffsetY) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset - sphereSize + (sphereOffsetY) * imageSizeX)] = sphereTwoColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + y + (sphereOffsetY + x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + y + (sphereOffsetY - x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - y + (sphereOffsetY + x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - y + (sphereOffsetY - x) * imageSizeX)] = sphereTwoColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                }

                                sphereOffset = sphereThreeOffset;
                                r2 = sphereSize * sphereSize;

                                pixels[(int)(sphereOffset + (sphereOffsetY + sphereSize) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset + (sphereOffsetY - sphereSize) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset + sphereSize + (sphereOffsetY) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset - sphereSize + (sphereOffsetY) * imageSizeX)] = sphereThreeColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + y + (sphereOffsetY + x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + y + (sphereOffsetY - x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - y + (sphereOffsetY + x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - y + (sphereOffsetY - x) * imageSizeX)] = sphereThreeColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + x + (sphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (sphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                }

                                //new circle sets 2 and 3

                                int localSphereOffsetY = (baseImageSizeY / 2) + baseImageSizeY + gapSize;
                                sphereOffset = sphereOneOffset;
                                sphereOneColor = sphereOneColorGlobal - colorOffsetLower1;
                                sphereTwoColor = sphereTwoColorGlobal - colorOffsetLower2;
                                sphereThreeColor = sphereThreeColorGlobal - colorOffsetLower3;

                                pixels[(int)(sphereOffset + (localSphereOffsetY + sphereSize) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset + (localSphereOffsetY - sphereSize) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset + sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset - sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereOneColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY + x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY - x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY + x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY - x) * imageSizeX)] = sphereOneColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                }

                                sphereOffset = sphereTwoOffset;
                                r2 = sphereSize * sphereSize;

                                pixels[(int)(sphereOffset + (localSphereOffsetY + sphereSize) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset + (localSphereOffsetY - sphereSize) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset + sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset - sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereTwoColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY + x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY - x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY + x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY - x) * imageSizeX)] = sphereTwoColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                }

                                sphereOffset = sphereThreeOffset;
                                r2 = sphereSize * sphereSize;

                                pixels[(int)(sphereOffset + (localSphereOffsetY + sphereSize) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset + (localSphereOffsetY - sphereSize) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset + sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset - sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereThreeColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY + x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY - x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY + x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY - x) * imageSizeX)] = sphereThreeColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                }

                                //circle set 3

                                localSphereOffsetY = (baseImageSizeY / 2) + baseImageSizeY + gapSize + baseImageSizeY + gapSize;
                                sphereOffset = sphereOneOffset;
                                sphereOneColor = sphereOneColorGlobal + colorOffsetUpper1;
                                sphereTwoColor = sphereTwoColorGlobal + colorOffsetUpper2;
                                sphereThreeColor = sphereThreeColorGlobal + colorOffsetUpper3;

                                pixels[(int)(sphereOffset + (localSphereOffsetY + sphereSize) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset + (localSphereOffsetY - sphereSize) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset + sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereOneColor;
                                pixels[(int)(sphereOffset - sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereOneColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY + x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY - x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY + x) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY - x) * imageSizeX)] = sphereOneColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereOneColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereOneColor;
                                }

                                sphereOffset = sphereTwoOffset;
                                r2 = sphereSize * sphereSize;

                                pixels[(int)(sphereOffset + (localSphereOffsetY + sphereSize) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset + (localSphereOffsetY - sphereSize) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset + sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereTwoColor;
                                pixels[(int)(sphereOffset - sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereTwoColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY + x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY - x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY + x) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY - x) * imageSizeX)] = sphereTwoColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereTwoColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereTwoColor;
                                }

                                sphereOffset = sphereThreeOffset;
                                r2 = sphereSize * sphereSize;

                                pixels[(int)(sphereOffset + (localSphereOffsetY + sphereSize) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset + (localSphereOffsetY - sphereSize) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset + sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereThreeColor;
                                pixels[(int)(sphereOffset - sphereSize + (localSphereOffsetY) * imageSizeX)] = sphereThreeColor;

                                y = sphereSize;
                                x = 1;
                                y = (int)(Math.Sqrt(r2 - 1) + 0.5);
                                while (x < y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY + x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + y + (localSphereOffsetY - x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY + x) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - y + (localSphereOffsetY - x) * imageSizeX)] = sphereThreeColor;
                                    x += 1;
                                    y = (int)(Math.Sqrt(r2 - x * x) + 0.5);
                                }
                                if (x == y)
                                {
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset + x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY + y) * imageSizeX)] = sphereThreeColor;
                                    pixels[(int)(sphereOffset - x + (localSphereOffsetY - y) * imageSizeX)] = sphereThreeColor;
                                }
                            }
                        }
                            //if (currentImage > centerImage - (sphereSizeZ / layerSize) && currentImage < centerImage + (sphereSizeZ / layerSize))
                            //{
                        for (int testY = 0; testY < imageSizeY; testY++)
                                {
                                    int hitColor = backgroundColor;
                                    int hitEndColor = backgroundColor;
                                    int sphereStart = 0;
                                    int sphereEnd = 0;
                                    int sphereMiddle = 0;
                                    for (int testX = testY * imageSizeX; testX < (testY * imageSizeX) + imageSizeX; testX++)
                                    {
                                        if (pixels[testX] != backgroundColor && pixels[testX] != backgroundColor - colorOffsetLower1 && pixels[testX] != backgroundColor + colorOffsetUpper1)
                                        {
                                            if (sphereStart == 0)
                                            {
                                                hitColor = pixels[testX];
                                                sphereStart = testX;
                                            }
                                            else if (sphereMiddle != 0)
                                            {
                                                hitEndColor = pixels[testX];
                                                sphereEnd = testX;
                                            }
                                        }
                                        if (pixels[testX] == backgroundColor || pixels[testX] == backgroundColor - colorOffsetLower1 || pixels[testX] == backgroundColor + colorOffsetUpper1)
                                        {
                                            if (sphereStart != 0)
                                            {
                                                if (sphereMiddle == 0)
                                                {
                                                    sphereMiddle = testX;
                                                }
                                                else if (sphereMiddle != 0)
                                                {
                                                    if (sphereEnd != 0)
                                                    {
                                                        if (hitEndColor == hitColor)
                                                        {
                                                            for (int colorY = sphereStart; colorY < sphereEnd; colorY++)
                                                            {
                                                                pixels[colorY] = (byte)hitColor;
                                                            }
                                                        }
                                                        hitColor = backgroundColor;
                                                        sphereStart = 0;
                                                        sphereEnd = 0;
                                                        sphereMiddle = 0;

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                        //    }
                        //}
                        //    sphereOffset = sphereTwoOffset;
                        //    if (currentImage == centerImage - (sphereSizeZ / layerSize) && columnLocation == sphereOffset - sphereSize && rowLocation == sphereOffsetY - sphereSize)
                        //    {
                        //        pixels[colorIndex] = sphereTwoColor;
                        //        pixelsW[colorIndex] = maxColor;
                        //    }
                        //    sphereOffset = sphereThreeOffset;
                        //    if (currentImage == centerImage - (sphereSizeZ / layerSize) && columnLocation == sphereOffset - sphereSize && rowLocation == sphereOffsetY - sphereSize)
                        //    {
                        //        pixels[colorIndex] = sphereThreeColor;
                        //        pixelsW[colorIndex] = maxColor;
                        //    }

                        //    if within +- .3in in Z
                        //    if (isSphere(sphereOneOffset, locationIndex, i)) //left circle
                        //    {
                        //        pixels[colorIndex] = sphereOneColor;
                        //        pixelsW[colorIndex] = maxColor;
                        //    }
                        //    else if (isSphere(sphereTwoOffset, locationIndex, i)) //middle circle
                        //    {
                        //        pixels[colorIndex] = sphereTwoColor;
                        //        pixelsW[colorIndex] = maxColor;
                        //    }
                        //    else if (isSphere(sphereThreeOffset, locationIndex, i)) //right circle
                        //    {
                        //        pixels[colorIndex] = sphereThreeColor;
                        //        pixelsW[colorIndex] = maxColor;
                        //    }
                        //    else
                        //    {
                        //        pixels[colorIndex] = backgroundColor;
                        //        pixelsW[colorIndex] = maxColor;
                        //    }
                        //}

                        ////Test loop
                        //for (int j = 0; j < pixels.Length; j++)
                        //{
                        //    pixels[j] = 0;
                        //    pixelsW[j] = maxColor;
                        //}

                        for (int pixelsCount = 0; pixelsCount < pixels.Length; pixelsCount++)
                        {
                            if (pixels[pixelsCount] != 0)
                            {
                                pixelsW[pixelsCount] = (byte)((byte)(255) - pixels[pixelsCount]);
                            }
                            else
                            {
                                pixelsW[pixelsCount] = 0;
                            }
                        }

                        bitmapImages.WritePixels(new Int32Rect(0, 0, imageSizeX, imageSizeY), pixels, stride, 0);

                        image1.Source = bitmapImages;

                        BitmapEncoder avilaImages = new BmpBitmapEncoder();
                        avilaImages.Frames.Add(BitmapFrame.Create(bitmapImages));

                        bitmapImagesW.WritePixels(new Int32Rect(0, 0, imageSizeX, imageSizeY), pixelsW, stride, 0);

                        BitmapEncoder avilaImagesW = new BmpBitmapEncoder();
                        avilaImagesW.Frames.Add(BitmapFrame.Create(bitmapImagesW));

                        try
                        {
                            int intNumImages = (int)numImages;
                            string currentImageName = currentImage.ToString().PadLeft(intNumImages.ToString().Length, '0') + ".bmp";
                            using (FileStream fs = new FileStream(photoSaveLocation + currentImageName, FileMode.Create, FileAccess.Write))
                            {
                                avilaImages.Save(fs);
                                textBlock4.Text = "Image base number " + currentImage + " created";
                            }
                            string currentImageNameW = currentImage.ToString().PadLeft(intNumImages.ToString().Length, '0') + "_w.bmp";
                            using (FileStream fs = new FileStream(photoSaveLocation + currentImageNameW, FileMode.Create, FileAccess.Write))
                            {
                                avilaImagesW.Save(fs);
                                textBlock4.Text = "Image base inverted number " + currentImage + " created";
                            }
                            currentImage++;
                        }
                        catch (IOException)
                        {
                            textBlock3.Text = "IO Exception caught, is //images// write locked?";
                        }
                    }
                }
                //end loop here
                //--------------------------------------
                imageStreamSource.Close();
                textBlock4.Text = currentImage + " images were created successfully";

            }
            catch (IOException)
            {
                textBlock3.Text = "IO Exception caught, does image base.bmp exist in runtime directory?";
            }

            //---------------------------------------------------------------------------------------------------------------------
            //---------------------------------------------------------------------------------------------------------------------
            //----------------------------------------This Code is from bmpCopyPasta-----------------------------------------------
            //-------The following code is from a script I made earlier to copy a series of images to be print ready---------------
            //-------it requires a series of images that end with _w and for every one of these there is an image without _w-------
            //---------------------------------------------------------------------------------------------------------------------
            //---------------------------------------------------------------------------------------------------------------------

            int numImagesCopy = 0;

            string[] oldPathAndNameRGB = new string[50];
            //string[] newPathAndNameRGB = new string[50];

            string[] oldPathAndNameW;
            //string[] newPathAndNameW = new string[50];

            string[] errorLocations = new string[50];

            string[] z2cFile = new string[3];

            string imagesDirectory = imageCopyLocation;

            string blankImage = imagesDirectory + "\\blank.bmp"; //Black Image/RGB
            string baseImageCopy = imagesDirectory + "\\base.bmp"; //White Image/W

            try
            {
                /*numImagesRGB = Directory.GetFiles(imagesDirectory, "*.bmp", SearchOption.TopDirectoryOnly).Length; //count the number of .jpg files in the directory found above
                oldPathAndNameRGB = Directory.GetFiles(imagesDirectory, "*.bmp", SearchOption.TopDirectoryOnly);*/

                numImagesCopy = Directory.GetFiles(imageDeleteLocation, "*_w.bmp", SearchOption.TopDirectoryOnly).Length; //count the number of .jpg files in the directory found above
                oldPathAndNameW = Directory.GetFiles(imageDeleteLocation, "*_w.bmp", SearchOption.TopDirectoryOnly);

                if (numImagesCopy != 0)
                {
                    oldPathAndNameRGB = new string[numImagesCopy];
                    errorLocations = new string[numImagesCopy];
                }
                for (int i = 0; i < numImagesCopy; i++)
                {
                    oldPathAndNameRGB[i] = oldPathAndNameW[i].Substring(0, oldPathAndNameW[i].Length - 6) + ".bmp";
                }

                //if (Directory.Exists(imagesDirectory))
                //{
                //    Directory.Delete(imagesDirectory, true);
                //}

                //System.IO.Directory.CreateDirectory(imagesDirectory);

                for (int i = 0; i < numImagesCopy; i++)
                {
                    if (File.Exists(oldPathAndNameRGB[i]) && File.Exists(oldPathAndNameW[i]))
                    {

                    }
                    else
                    {
                        for (int j = 0; j < errorLocations.Length; j++)
                        {
                            errorLocations[j] = "There was an issue with image number " + i;
                        }
                    }
                }

                if (errorLocations[0] == null)
                {

                    for (int i = 0; i < numImagesCopy; i++)
                    {
                        string imageName = "Layer" + i.ToString().PadLeft(/*numImagesRGB.ToString().Length*/ 4, '0'); //May need to just be 4 later

                        System.IO.File.Copy(oldPathAndNameRGB[i], imagesDirectory + imageName + "_c.bmp");
                        System.IO.File.Copy(oldPathAndNameRGB[i], imagesDirectory + imageName + "_m.bmp");
                        System.IO.File.Copy(oldPathAndNameRGB[i], imagesDirectory + imageName + "_y.bmp");

                        //System.IO.File.Copy(oldPathAndNameW[i], imagesDirectory + "\\images\\" + imageName + "_c.bmp");//transition code
                        //System.IO.File.Copy(oldPathAndNameW[i], imagesDirectory + "\\images\\" + imageName + "_m.bmp");//transition code
                        //System.IO.File.Copy(oldPathAndNameW[i], imagesDirectory + "\\images\\" + imageName + "_y.bmp");//transition code

                        //System.IO.File.Copy(blankImage, imagesDirectory + "\\images\\" + imageName + "_c.bmp");//davelike test code
                        //System.IO.File.Copy(blankImage, imagesDirectory + "\\images\\" + imageName + "_m.bmp");//davelike test code
                        //System.IO.File.Copy(blankImage, imagesDirectory + "\\images\\" + imageName + "_y.bmp");//davelike test code

                        textBlock4.Text = "CMY of layer: " + i + " is done";

                        System.IO.File.Copy(oldPathAndNameW[i], imagesDirectory + imageName + "_w.bmp");

                        //System.IO.File.Copy(oldPathAndNameRGB[i], imagesDirectory + "\\images\\" + imageName + "_w.bmp"); //davelike test code

                        //System.IO.File.Copy(baseImage, imagesDirectory + "\\images\\" + imageName + "_w.bmp"); //davelike test code

                        textBlock4.Text = "W of layer: " + i + " is done";

                        //System.IO.File.Copy(oldPathAndNameW[i], imagesDirectory + "\\images\\" + imageName + "_k.bmp"); //davelike test code

                        //System.Console.WriteLine("K of layer: " + i + " is done"); //davelike test code

                    }

                    System.Console.WriteLine("All Done Copying Images");

                    if (numImagesCopy != 0)
                    {
                        z2cFile[0] = "inches";
                        z2cFile[1] = ".007";
                        z2cFile[2] = numImagesCopy.ToString();

                        System.IO.File.WriteAllLines(imagesDirectory + "\\images.z2c", z2cFile);
                        textBlock4.Text = "All Done Creating .z2c file";
                    }
                }

                else
                {
                    for (int i = 0; i < errorLocations.Length; i++)
                    {
                        if (errorLocations[i] != null)
                        {
                            System.Console.WriteLine(errorLocations[i]);
                        }
                    }
                }
            }
            catch
            {
                textBlock4.Text = "Exception caught, the folder \\forPrint\\ may be write locked.";
            }

            System.Console.WriteLine("The number of images found was " + numImagesCopy + ". Press enter to finish");
            Console.ReadLine();
        }
        public void TestCacheModifySymbol()
        {
            using (ShimsContext.Create())
              {
            client.Geometry.MapPoint p = new client.Geometry.MapPoint(0.0, 0.0);
            clientfake.ShimGraphic g = new clientfake.ShimGraphic();
            client.FeatureService.Symbols.PictureMarkerSymbol pms = new client.FeatureService.Symbols.PictureMarkerSymbol();
            Uri myUri = new Uri("../../resources/zoom_in_tool_1.bmp", UriKind.RelativeOrAbsolute);

            BitmapDecoder decoder = new BmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];
            pms.Source = bitmapSource;
            clientfake.ShimUniqueValueRenderer r = new clientfake.ShimUniqueValueRenderer();
            Dictionary<String, Object> attributes = new Dictionary<String, Object>();
            attributes["uniquedesignation"] = "Wolfpack 1 C";
            attributes["owningunit"] = "2nd Stryker Brigade";
            attributes["type"] = "M1128";
            g.AttributesGet = () => { return attributes; };
            g.GeometryGet = () => { return p; };
            Dictionary<String, String> fields = new Dictionary<String, String>();
            fields["UID"] = "uniquedesignation";
            fields["HF"] = "owningunit";
            fields["LABELS"] = "uniquedesignation";
            fields["DESCFLDS"] = "type";
            fields["DESCFIELD"] = "type";
            int count = cache.RetrieveFeatureCache("EQUIPMENT").Count;
            cache.AddFeature("EQUIPMENT", g, "Type: {type}", "{uniquedesignation}", fields, r);
            fields["LABELS"] = "uniquedesignation,owningunit";
            g.SymbolGet = () => { return pms; };
            cache.UpdateFeature("EQUIPMENT", "Wolfpack 1 C", "Type: {type}", "{uniquedesignation} owned by {owningunit}", g, fields);
            Dictionary<String, Dictionary<String, Object>> fcache = cache.RetrieveFeatureCache("EQUIPMENT");
            Dictionary<String, Object> f = fcache["Wolfpack 1 C"];
            ImageSource imsrc = f["ICON"] as ImageSource;
            Assert.AreEqual(pms.Source, imsrc);
              }
        }
Exemplo n.º 4
0
        private static ImageSource RetriveImage(string imagePath)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(imagePath);

            switch (imagePath.Substring(imagePath.Length - 3))
            {
            case "jpg":
                var jpgDecoder = new System.Windows.Media.Imaging.JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(jpgDecoder.Frames[0]);

            case "bmp":
                var bmpDecoder = new System.Windows.Media.Imaging.BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(bmpDecoder.Frames[0]);

            case "png":
                var pngDecoder = new System.Windows.Media.Imaging.PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(pngDecoder.Frames[0]);

            case "ico":
                var icoDecoder = new System.Windows.Media.Imaging.IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(icoDecoder.Frames[0]);

            default:
                return(null);
            }
        }
Exemplo n.º 5
0
 private void GetBitmapSourceFromBmp(string fileRoute)
 {
     Stream imageStream = new FileStream(fileRoute, FileMode.Open, FileAccess.Read, FileShare.Read);
     var decoder = new BmpBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     BmSource = decoder.Frames[0];
     BitsPerPix = BmSource.Format.BitsPerPixel;
 }
Exemplo n.º 6
0
        private System.Windows.Media.ImageSource BmpImageSource(string embeddedPath)
        {
            Stream stream  = this.GetType().Assembly.GetManifestResourceStream(embeddedPath);
            var    decoder = new System.Windows.Media.Imaging.BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            return(decoder.Frames[0]);
        }
Exemplo n.º 7
0
        public static BitmapSource ToImage(byte[] arg, TypeImagen tipo) {
            BitmapSource temporigen = null;
            if(arg != null){
                System.IO.MemoryStream ms = new System.IO.MemoryStream(arg);

                switch (tipo)
                {
                    case TypeImagen.BMP:

                        BmpBitmapDecoder bmpdeco = new BmpBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        temporigen = bmpdeco.Frames[0];
                        break;
                    case TypeImagen.JPG:
                        
                        JpegBitmapDecoder jpgdeco = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        temporigen = jpgdeco.Frames[0];
                        break;
                }
            }
            return temporigen;
        }
Exemplo n.º 8
0
        public override ImageData Read(Stream stream, ImageMetaData info)
        {
            var meta = info as GrdMetaData;
            if (null == meta)
                throw new ArgumentException ("GrdFormat.Read should be supplied with GrdMetaData", "info");

            stream.Position = 12;
            using (var reader = new Reader (stream, meta.DataSize))
            {
                reader.Unpack();
                byte[] pixels = reader.Data;
                using (var bmp = new MemoryStream (reader.Data, false))
                {
                    var decoder = new BmpBitmapDecoder (bmp,
                        BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                    BitmapSource frame = decoder.Frames[0];
                    frame.Freeze();
                    return new ImageData (frame, info);
                }
            }
        }
Exemplo n.º 9
0
 public override ImageData Read(Stream file, ImageMetaData info)
 {
     var bmp_info = info as BmpMetaData;
     if (bmp_info != null && file.CanSeek
         && info.Width * info.Height * (uint)info.BPP/8 + bmp_info.HeaderLength == bmp_info.ImageLength)
     {
         if (0x20 == info.BPP)
         {
             return ReadBitmapBGRA (file, bmp_info);
         }
         else if (0x18 == info.BPP
                  && (bmp_info.ImageLength + info.Width * info.Height) == file.Length)
         {
             return ReadBitmapWithAlpha (file, bmp_info);
         }
     }
     var decoder = new BmpBitmapDecoder (file,
         BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
     BitmapSource frame = decoder.Frames.First();
     frame.Freeze();
     return new ImageData (frame, info);
 }
Exemplo n.º 10
0
        /// <summary>
        /// 从资源中恢复图像(png、ico、jpeg、bmp)
        /// </summary>
        /// <param name="nomImage"></param>
        /// <returns></returns>
        public static ImageSource ImageSource(string nomImage)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(nomImage);

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".png")) // Cas png
            {
                PngBitmapDecoder img = new System.Windows.Media.Imaging.PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".bmp")) // Cas bmp
            {
                BmpBitmapDecoder img = new System.Windows.Media.Imaging.BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".jpg")) // Cas jpg
            {
                JpegBitmapDecoder img = new System.Windows.Media.Imaging.JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".tiff")) // Cas tiff
            {
                TiffBitmapDecoder img = new System.Windows.Media.Imaging.TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().Contains(".ico")) // Cas  ico
            {
                IconBitmapDecoder img = new System.Windows.Media.Imaging.IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            return(null);
        }
        public 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);
                }

                var headers = client.ResponseHeaders;

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

                            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" || extension == ".jpeg")
                                decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            else if (extension == ".bmp")
                                decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            else
                            {
                                // We are not sure what extension we are looking at, lets see if there is a content-type available
                                if (headers["Content-Type"] != null)
                                {
                                    var type = headers["Content-Type"];

                                    if (type.IndexOf("gif", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                    else if (type.IndexOf("png", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                    else if (type.IndexOf("jpg", StringComparison.InvariantCultureIgnoreCase) > -1 || type.IndexOf("jpeg", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                    else if (type.IndexOf("bmp", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                }
                            }

                            if (decoder == null)
                            {
                                Logger.Error("Unable to determine type of image to decode. url = {0}", LogSource.BackgroundTask, url);
                                return;
                            }

                            _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);
            }
        }
Exemplo n.º 12
0
 private static Bitmap GetBitmapFromStream(Stream input, ImageFormat format)
 {
     BitmapDecoder decoder;
     if (format == ImageFormat.Bmp)
         decoder = new BmpBitmapDecoder(input, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     else if (format == ImageFormat.Png)
         decoder = new PngBitmapDecoder(input, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     else // Jpeg and other formats...
         decoder = new JpegBitmapDecoder(input, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     return GetBitmapFromFrames(decoder.Frames);
 }
Exemplo n.º 13
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)
        {
            GMapImage 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:
               {
                  Debug.WriteLine("WindowsPresentationImageProxy: unknown image format: " + type);
               }
               break;
            }

            if(m != null)
            {
               ret = new GMapImage();
               ret.Img = m;
               if(ret.Img.CanFreeze)
               {
                  ret.Img.Freeze();
               }
            }
             }
             return ret;
        }
Exemplo n.º 14
0
        private static BitmapFrame GetBitmapFrame(string sourceFile, Stream s)
        {
            BitmapDecoder d;

            string extension = Path.GetExtension(sourceFile);
            switch (extension.ToLower())
            {
                case ".jpg":
                case ".jpeg":
                    d = new JpegBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                    break;
                case ".gif":
                    d = new GifBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                    break;
                case ".png":
                    d = new PngBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                    break;
                case ".bmp":
                    d = new BmpBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                    break;
                case ".tif":
                case ".tiff":
                    d = new TiffBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                    break;
                default:
                    throw new InvalidDataException("Unsupported file extension " + extension);
            }

            BitmapFrame frame = d.Frames[0];

            return frame;
        }
Exemplo n.º 15
0
Arquivo: WSQ.cs Projeto: eliudiaz/wsq
        /// <summary>
        /// Encode image fingerprint to wsq file
        /// </summary>
        /// <param name="FileSource">File source (bmp,tiff)</param>
        /// <param name="FileDest">File wsq</param>
        /// <param name="comments">Comments in image</param>
        /// <param name="BitRate">Bit rate</param>
        public void EnconderFile(String FileSource, 
                                String FileDest, 
                                String[] comments, 
                                double BitRate)
        {
            try
            {
                switch (Path.GetExtension(FileSource).ToUpper())
                {
                    case ".BMP":
                    case ".TIF":
                        break;
                    default:
                        throw new ApplicationException("Error: FileSource extension no supported");

                }

                if (Path.GetExtension(FileDest).ToUpper().Replace(".", "") != "WSQ")
                {
                    throw new ApplicationException("Error: FileDest extension no supported");
                }

                Bitmap bm = null;
                System.Drawing.Image img = null;
                byte[] fileData;

                Wsqm.cBitmap bitmap;
                Wsqm.DataOutput data;
                BitmapSource bitmapSource;

                switch (Path.GetExtension(FileSource).ToUpper())
                {
                    case ".BMP":
                        img = System.Drawing.Image.FromFile(FileSource);
                        bm = new Bitmap(img);

                        Uri myUri = new Uri(FileSource, UriKind.RelativeOrAbsolute);
                        BmpBitmapDecoder decoder2 = new BmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        bitmapSource = decoder2.Frames[0];

                        fileData = GetBytesFromBitmapSource(bitmapSource);

                        bitmap = new Wsqm.cBitmap(fileData,
                                bm.Width,
                                bm.Height, 500, 8, 1);

                        data = new Wsqm.DataOutput();
                        data.RutaDestino = FileDest;

                        _EncoderWSQ.encode(data, bitmap, BitRate, comments);

                        img.Dispose();

                        break;
                    case ".TIF":
                        img = System.Drawing.Image.FromFile(FileSource);
                        bm = new Bitmap(img);

                        Stream imageStreamSource = new FileStream(FileSource, FileMode.Open, FileAccess.Read, FileShare.Read);
                        TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        bitmapSource = decoder.Frames[0];

                        fileData = GetBytesFromBitmapSource(bitmapSource);

                        bitmap = new Wsqm.cBitmap(fileData,
                                bm.Width,
                                bm.Height, 500, 8, 1);

                        data = new Wsqm.DataOutput();
                        data.RutaDestino = FileDest;
                        _EncoderWSQ.encode(data, bitmap, BitRate, comments);

                        img.Dispose();
                        imageStreamSource.Dispose();
                        break;

                }
            }
            catch (Exception e)
            {
                throw (e);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            Assembly caller = Assembly.GetEntryAssembly();
            var obj = caller.GetType(ClassName).GetProperty(ResourceName, BindingFlags.Static | BindingFlags.NonPublic);
            if (obj != null)
            {
                var val = obj.GetValue(obj, null);
                if (val != null)
                {
                    MemoryStream mstr = new MemoryStream();
                    BitmapDecoder decoder = null;

                    if (val is Icon)
                    {
                        ((Icon)val).Save(mstr);
                        decoder = new IconBitmapDecoder(mstr, BitmapCreateOptions.None, BitmapCacheOption.None);

                    }
                    else if (val is Bitmap)
                    {
                        Bitmap bmp = val as Bitmap;
                        if (ImageFormat == ImageFormat.Png)
                        {
                            bmp.Save(mstr, ImageFormat.Png);
                            decoder = new PngBitmapDecoder(mstr, BitmapCreateOptions.None, BitmapCacheOption.None);
                        }
                        else if (ImageFormat == ImageFormat.Tiff)
                        {
                            bmp.Save(mstr, ImageFormat.Tiff);
                            decoder = new TiffBitmapDecoder(mstr, BitmapCreateOptions.None, BitmapCacheOption.None);
                        }
                        else if (ImageFormat == ImageFormat.Gif)
                        {
                            bmp.Save(mstr, ImageFormat.Gif);
                            decoder = new GifBitmapDecoder(mstr, BitmapCreateOptions.None, BitmapCacheOption.None);
                        }
                        else if (ImageFormat == ImageFormat.Jpeg)
                        {
                            bmp.Save(mstr, ImageFormat.Jpeg);
                            decoder = new JpegBitmapDecoder(mstr, BitmapCreateOptions.None, BitmapCacheOption.None);
                        }
                        else if (ImageFormat == ImageFormat.Bmp)
                        {
                            bmp.Save(mstr, ImageFormat.Bmp);
                            decoder = new BmpBitmapDecoder(mstr, BitmapCreateOptions.None, BitmapCacheOption.None);
                        }
                    }

                    if (decoder != null)
                    {
                        return decoder.Frames[0];
                    }
                }

                return null;
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 17
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 = "";
        }
Exemplo n.º 18
0
        internal static BitmapDecoder CreateFromUriOrStream(
            Uri baseUri,
            Uri uri,
            Stream stream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            RequestCachePolicy uriCachePolicy,
            bool insertInDecoderCache
            )
        {
            Guid clsId = Guid.Empty;
            bool isOriginalWritable = false;
            SafeMILHandle decoderHandle = null;
            BitmapDecoder cachedDecoder = null;
            Uri finalUri = null;
            Stream uriStream = null;
            UnmanagedMemoryStream unmanagedMemoryStream = null;
            SafeFileHandle safeFilehandle = null;

            // check to ensure that images are allowed in partial trust
            DemandIfImageBlocked();

            if (uri != null)
            {
                finalUri = (baseUri != null) ?
                               System.Windows.Navigation.BaseUriHelper.GetResolvedUri(baseUri, uri) :
                               uri;

                if (insertInDecoderCache)
                {
                    if ((createOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
                    {
                        ImagingCache.RemoveFromDecoderCache(finalUri);
                    }

                    cachedDecoder = CheckCache(
                        finalUri,
                        out clsId
                        );
                }
            }

            // try to retrieve the cached decoder
            if (cachedDecoder != null)
            {
                decoderHandle = cachedDecoder.InternalDecoder;
            }
            else if ((finalUri != null) && (finalUri.IsAbsoluteUri) && (stream == null) &&
                     ((finalUri.Scheme == Uri.UriSchemeHttp) ||
                      (finalUri.Scheme == Uri.UriSchemeHttps)))
            {
                return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy);
            }
            else if ((stream != null) && (!stream.CanSeek))
            {
                return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy);
            }
            else
            {
                // Create an unmanaged decoder
                decoderHandle = BitmapDecoder.SetupDecoderFromUriOrStream(
                    finalUri,
                    stream,
                    cacheOption,
                    out clsId,
                    out isOriginalWritable,
                    out uriStream,
                    out unmanagedMemoryStream,
                    out safeFilehandle
                    );
            }

            BitmapDecoder decoder = null;

            // Find out the decoder type and wrap it appropriately and return that
            if (MILGuidData.GUID_ContainerFormatBmp == clsId)
            {
                decoder = new BmpBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatGif == clsId)
            {
                decoder = new GifBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatIco == clsId)
            {
                decoder = new IconBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatJpeg == clsId)
            {
                decoder = new JpegBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatPng == clsId)
            {
                decoder = new PngBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatTiff == clsId)
            {
                decoder = new TiffBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatWmp == clsId)
            {
                decoder = new WmpBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else
            {
                decoder = new UnknownBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }

            return decoder;
        }
Exemplo n.º 19
0
        private static BitmapSource Load(object obj, BitmapEncoding enc, 
            BitmapCreateOptions create, BitmapCacheOption cache, out BitmapMetadata data)
        {
            BitmapDecoder dec = null;

            if (obj is Stream)
            {
                Stream stream = obj as Stream;

                switch (enc)
                {
                    case BitmapEncoding.Bmp:
                        dec = new BmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Png:
                        dec = new PngBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Jpg:
                        dec = new JpegBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Tiff:
                        dec = new TiffBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Gif:
                        dec = new GifBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Wmp:
                        dec = new WmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Icon:
                        dec = new IconBitmapDecoder(stream, create, cache);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            else if (obj is Uri)
            {
                Uri stream = obj as Uri;

                switch (enc)
                {
                    case BitmapEncoding.Bmp:
                        dec = new BmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Png:
                        dec = new PngBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Jpg:
                        dec = new JpegBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Tiff:
                        dec = new TiffBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Gif:
                        dec = new GifBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Wmp:
                        dec = new WmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Icon:
                        dec = new IconBitmapDecoder(stream, create, cache);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            else
                throw new ArgumentException();

            data = dec.Metadata;
            return dec.Frames[0];
        }
Exemplo n.º 20
0
        private void DrawContent()
        {
            pnlContent.Children.Clear();

            if (Clipboard.ContainsText())
            {
                // we have some text in the clipboard.
                TextBox tb = new TextBox();
                tb.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                tb.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
                tb.Text = Clipboard.GetText();
                tb.IsReadOnly = true;
                tb.TextWrapping = TextWrapping.NoWrap;
                pnlContent.Children.Add(tb);
            }
            else if (Clipboard.ContainsFileDropList())
            {
                // we have a file drop list in the clipboard
                ListBox lb = new ListBox();
                lb.ItemsSource = Clipboard.GetFileDropList();
                pnlContent.Children.Add(lb);
            }
            else if (Clipboard.ContainsImage())
            {
                // Because of a known issue in WPF,
                // we have to use a workaround to get correct
                // image that can be displayed.
                // The image have to be saved to a stream and then 
                // read out to workaround the issue.
                MemoryStream ms = new MemoryStream();
                BmpBitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(Clipboard.GetImage()));
                enc.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);

                BmpBitmapDecoder dec = new BmpBitmapDecoder(ms,
                    BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                Image img = new Image();
                img.Stretch = Stretch.Uniform;
                img.Source = dec.Frames[0];
                pnlContent.Children.Add(img);
            }
            else
            {
                Label lb = new Label();
                lb.Content = "The type of the data in the clipboard is not supported by this sample.";
                pnlContent.Children.Add(lb);
            }
        }
Exemplo n.º 21
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {Title = "BMP Imaging Sample"};
            var mySv = new ScrollViewer();

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

            // Try creating a new image with a custom palette.
            var colors = new List<Color>
            {
                Colors.Red,
                Colors.Blue,
                Colors.Green
            };
            var myPalette = new BitmapPalette(colors);

            // Creates a new empty image with the pre-defined palette
            var image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed1,
                myPalette,
                pixels,
                stride);

            var stream = new FileStream("new.bmp", FileMode.Create);
            var encoder = new BmpBitmapEncoder();
            var myTextBlock = new TextBlock {Text = "Codec Author is: " + encoder.CodecInfo.Author};
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);


            // Open a Stream and decode a BMP image
            Stream imageStreamSource = new FileStream("tulipfarm.bmp", FileMode.Open, FileAccess.Read, FileShare.Read);
            var decoder = new BmpBitmapDecoder(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 BMP image
            var myUri = new Uri("tulipfarm.bmp", UriKind.RelativeOrAbsolute);
            var decoder2 = new BmpBitmapDecoder(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 BMP 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();
        }
 public ReadExifInfo(string fileName, FileInfo file)
 {
     try
     {
         using (foto = File.Open(fileName, FileMode.Open, FileAccess.Read))
         {
             JpegBitmapDecoder jpegdecoder;
             PngBitmapDecoder pngdecoder;
             BmpBitmapDecoder bmpdecoder;
             GifBitmapDecoder gifdecoder;
             IconBitmapDecoder icondecoder;
             TiffBitmapDecoder tiffdecoder;
             WmpBitmapDecoder wmpdecoder;
                 
             switch(file.Extension.ToLower())
             {
                 case ".jpg":
                     jpegdecoder = new JpegBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)jpegdecoder.Frames[0].Metadata.Clone();
                     break;
                 case ".jpeg":
                     jpegdecoder = new JpegBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)jpegdecoder.Frames[0].Metadata.Clone();
                     break;
                 case ".png":
                     pngdecoder = new PngBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)pngdecoder.Frames[0].Metadata.Clone();
                     break;
                 case ".bmp":
                     bmpdecoder = new BmpBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)bmpdecoder.Frames[0].Metadata.Clone();
                     break;
                 case ".gif":
                     gifdecoder = new GifBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)gifdecoder.Frames[0].Metadata.Clone();
                     break;
                 case ".ico":
                     icondecoder = new IconBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)icondecoder.Frames[0].Metadata.Clone();
                     break;
                 case ".tiff":
                     tiffdecoder = new TiffBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)tiffdecoder.Frames[0].Metadata.Clone();
                     break;
                 case ".wmp":
                     wmpdecoder = new WmpBitmapDecoder(foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                     bm = (BitmapMetadata)wmpdecoder.Frames[0].Metadata.Clone();
                     break;
             }
             creationTime = Convert.ToDateTime(bm.DateTaken);
         }
     }
     catch (Exception ex) { WPF.MessageBox.Show(fileName + "\n" + ex.Message, "Decoder Exception"); }
 }
Exemplo n.º 23
0
        /// <summary>
        /// <c>Bitmap</c> to <c>BitmapSource</c> conversion method in order to show the edited image at the main window.
        /// </summary>
        /// <remarks>Extension method.</remarks>
        public static BitmapFrame BitmapToBitmapSource(this Bitmap bitmap) {
            // Convert Bitmap to BitmapImage
            MemoryStream str = new MemoryStream();
            bitmap.Save(str, ImageFormat.Bmp);
            str.Seek(0, SeekOrigin.Begin);
            BmpBitmapDecoder bdc = new BmpBitmapDecoder(str, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

            return bdc.Frames[0];
        }
Exemplo n.º 24
0
        /// <summary>
        /// Decomposes a level bitmap to a tile sheet and a <see cref="LevelSheet"/>.
        /// </summary>
        /// <param name="fileName">Bitmap of the level to decompose.</param>
        /// <param name="tileWidth">Tile width, must be a multiple of <see cref="fileName"/> width.</param>
        /// <param name="tileHeight">Tile height, must be a multiple of <see cref="fileName"/> height.</param>
        /// <param name="targetJson">File to write the <see cref="LevelSheet"/> to.</param>
        /// <param name="targetPng">File to write the level tiles to.</param>
        /// <param name="sheetWidth">Width in pixels of the tile sheet, must be a multiple of 2.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static void Decompose(string fileName, int tileWidth, int tileHeight, string targetJson, string targetPng, int sheetWidth)
        {
            if (fileName == null) throw new ArgumentNullException("fileName");
            if (!File.Exists(fileName))
                throw new ArgumentOutOfRangeException("fileName", "Input file name does not exist");

            if (tileWidth <= 0) throw new ArgumentOutOfRangeException("tileWidth");
            if (tileHeight <= 0) throw new ArgumentOutOfRangeException("tileHeight");
            var image = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute));
            WriteableBitmap bitmap = BitmapFactory.ConvertToPbgra32Format(image);
            int pixelWidth = bitmap.PixelWidth;
            int pixelHeight = bitmap.PixelHeight;
            if (pixelWidth % tileWidth != 0)
                throw new ArgumentOutOfRangeException("tileWidth", "Tile width must be a multiple of image width");
            if (pixelHeight % tileHeight != 0)
                throw new ArgumentOutOfRangeException("tileHeight", "Tile height must be a multiple of image height");

            if (targetJson == null) throw new ArgumentNullException("targetJson");
            if (targetPng == null) throw new ArgumentNullException("targetPng");

            if (sheetWidth <= 0)
                throw new ArgumentOutOfRangeException("sheetWidth", "Must a multiple of two");
            if (sheetWidth %2 !=0)
                throw new ArgumentOutOfRangeException("sheetWidth", "Must a multiple of two");
            int hTiles = pixelWidth / tileWidth;
            int vTiles = pixelHeight / tileHeight;
            WriteableBitmap target = BitmapFactory.New(tileWidth, tileHeight);
            var dictionary = new Dictionary<string, LevelData>();
            for (int y = 0; y < vTiles; y++)
            {
                for (int x = 0; x < hTiles; x++)
                {
                    target.Blit(new Rect(0, 0, tileWidth, tileHeight), bitmap,
                        new Rect(x * tileWidth, y * tileHeight, tileWidth, tileHeight));

                    var bmpBitmapEncoder = new BmpBitmapEncoder();
                    bmpBitmapEncoder.Frames.Add(BitmapFrame.Create(target));
                    byte[] buffer;
                    using (var memoryStream = new MemoryStream())
                    {
                        bmpBitmapEncoder.Save(memoryStream);
                        buffer = memoryStream.GetBuffer();
                    }

                    byte[] hash;
                    using (SHA1 sha1 = SHA1.Create())
                    {
                        hash = sha1.ComputeHash(buffer);
                    }
                    IEnumerable<string> @select = hash.Select(s => s.ToString("X"));
                    string key = String.Concat(@select);

                    bool containsKey = dictionary.ContainsKey(key);
                    if (!containsKey)
                    {
                        dictionary.Add(key, new LevelData(buffer));
                    }
                    dictionary[key].Tiles.Add(new Tuple<int, int>(x, y));
                }
            }

            // generate sheet
            int count = dictionary.Count;
            int tilesPerRow = sheetWidth / tileWidth;
            int rows = count / tilesPerRow + 1;

            int desiredHeight = rows * tileHeight;
            WriteableBitmap writeableBitmap = BitmapFactory.New(tilesPerRow * tileWidth, rows * tileHeight);
            int i = 0;
            foreach (var myClass in dictionary)
            {
                byte[] bytes = myClass.Value.Pixels;
                BmpBitmapDecoder decoder;
                using (var memoryStream = new MemoryStream(bytes))
                {
                    decoder = new BmpBitmapDecoder(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                }
                BitmapFrame bitmapFrame = decoder.Frames[0];
                WriteableBitmap source = BitmapFactory.ConvertToPbgra32Format(bitmapFrame);
                var destRect = new Rect(i * tileWidth, 0, tileWidth, tileHeight);
                destRect.X = i % tilesPerRow * tileWidth;
                destRect.Y = i / tilesPerRow * tileHeight;

                writeableBitmap.Blit(destRect, source, new Rect(0, 0, tileWidth, tileHeight));
                i++;
            }


            // save level
            int i1 = hTiles * vTiles;
            var level = new int[i1];
            int j = 0;
            foreach (var myClass in dictionary)
            {
                List<Tuple<int, int>> tuples = myClass.Value.Tiles;
                foreach (var tuple in tuples)
                {
                    int x = tuple.Item1;
                    int y = tuple.Item2;
                    int offset = y * hTiles + x;
                    level[offset] = j;
                }
                j++;
            }


            // Save bitmap
            string pngDirectory = EnsureDirectoryExists(targetPng);
            string pngFile = Path.GetFileName(targetPng);
            string pngPath = Path.Combine(pngDirectory, pngFile);
            using (Stream stream = File.OpenWrite(pngPath))
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(writeableBitmap));
                encoder.Save(stream);
            }

            // Save sheet
            var sheet = new LevelSheet(Path.GetFileName(targetPng), sheetWidth, desiredHeight, hTiles, vTiles,
                tileWidth, tileHeight, level);
            string json = JsonConvert.SerializeObject(sheet, Formatting.Indented);
            string jsonDirectory = EnsureDirectoryExists(targetJson);
            string jsonFile = Path.GetFileName(targetJson);
            string jsonPath = Path.Combine(jsonDirectory, jsonFile);
            File.WriteAllText(jsonPath, json);
        }
Exemplo n.º 25
-1
        private void Load_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialogue = new OpenFileDialog()
            {
                Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png|Tiff Image (.tiff)|*.tiff|Wmf Image (.wmf)|*.wmf"
            };

            if (openFileDialogue.ShowDialog() == true)
            {
                Stream imageStreamSource = new FileStream(openFileDialogue.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                BitmapDecoder decoder;
                #region Decoding
                string extension = System.IO.Path.GetExtension(openFileDialogue.FileName);
                switch (extension.ToLower())
                {
                    case ".jpeg":
                        decoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        break;
                    case ".png":
                        decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        break;
                    case ".gif":
                        decoder = new GifBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        break;
                    case ".tiff":
                        decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        break;
                    case ".wmf":
                        decoder = new WmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        break;
                    case ".bmp":
                        decoder = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        break;
                    default:
                        return;
                }
                #endregion
                BitmapSource LoadedBitmap = decoder.Frames[0];
                MyCanvas.Children.Clear();
                MyCanvas.Width = LoadedBitmap.Width;
                MyCanvas.Height = LoadedBitmap.Height;
                MyCanvas.Children.Add(
                            new Image() { Source = LoadedBitmap }
                        );

            }
        }
Exemplo n.º 26
-1
 public object ReadBmp(Stream stream)
 {
     var decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     return decoder.Frames[0].Clone();
 }