예제 #1
0
        public byte[] QuantizeImage(Stream stream)
        {
            var image = Image.Load <Rgba32>(stream);
            //var output = QuantizeImage(image, 10, 70);
            var output = QuantizeImage(image, 10, 60);

            using (var mem = new MemoryStream())
            {
                pngEncoder.Encode(output, mem);
                return(mem.ToArray());
            }
        }
예제 #2
0
        /// <summary>
        /// Encode the input data as per provided image format.
        /// </summary>
        /// <param name="data">An array of data to be encoded.</param>
        /// <param name="width">Image width.</param>
        /// <param name="height">Image height.</param>
        /// <param name="format">Graphics format used by the render texture.</param>
        /// <param name="imageFormat">Format for encoding the data.</param>
        /// <param name="additionalParam">Additional flags to be passed for the encoding.</param>
        /// <returns></returns>
        /// <exception cref="NotSupportedException"></exception>
        public static Array EncodeArray(Array data, int width, int height, GraphicsFormat format, ImageFormat imageFormat, int additionalParam = 0)
        {
            using (s_Encode.Auto())
            {
                switch (imageFormat)
                {
                case ImageFormat.Raw:
                    return(data);

#if UNITY_2019_3_OR_NEWER
                case ImageFormat.Png:
#if USIM_USE_BUILTIN_PNG_ENCODER
                    return(ImageConversion.EncodeArrayToPNG(data, format, (uint)width, (uint)height, 0));
#else
                    int bitDepth = 8;
                    PngEncoder.ColorType colorType = PngEncoder.GetTypeAndDepth(GraphicsUtilities.GetBlockSize(format), GraphicsUtilities.GetComponentCount(format), ref bitDepth);
                    return(PngEncoder.Encode(ArrayUtilities.Cast <byte>(data), width, height, colorType, bitDepth, (PngEncoder.PngParam)additionalParam));
#endif
                case ImageFormat.Exr:
                    return(ImageConversion.EncodeArrayToEXR(data, format, (uint)width, (uint)height, 0, /*EXRFlags*/ (Texture2D.EXRFlags)additionalParam));

                case ImageFormat.Tga:
                    return(ImageConversion.EncodeArrayToTGA(data, format, (uint)width, (uint)height, 0));
#endif
                case ImageFormat.Jpg:
#if USIM_USE_BUILTIN_JPG_ENCODER && UNITY_2019_3_OR_NEWER
                    return(ImageConversion.EncodeArrayToJPG(data, format, (uint)width, (uint)height, 0, /*quality*/ additionalParam > 0 ? (int)additionalParam : 75));
#else
                    return(JpegEncoder.Encode(ArrayUtilities.Cast <byte>(data), width, height, GraphicsUtilities.GetBlockSize(format), format, /*quality*/ additionalParam > 0 ? (int)additionalParam : 75));
#endif
                default:
                    throw new NotSupportedException("ImageFormat is not supported");
                }
            }
        }
예제 #3
0
        public static void SaveImage(this UIElement uiElement)
        {
            var dialog = new SaveFileDialog
            {
                DefaultExt = ".png",
                Filter     = "PNG | *.png | JPG | *.jpg",
            };
            var save = dialog.ShowDialog();

            if (save.HasValue && save.Value)
            {
                var saveStream = dialog.OpenFile();

                var bitmap = new WriteableBitmap(uiElement, new TranslateTransform());
                var image  = bitmap.ToImage();
                if (dialog.SafeFileName.EndsWith(".png"))
                {
                    var encoder = new PngEncoder();
                    encoder.Encode(image, saveStream);
                }
                else if (dialog.SafeFileName.EndsWith(".jpg"))
                {
                    var encoder = new JpegEncoder();
                    encoder.Encode(image, saveStream);
                }

                saveStream.Close();
            }
        }
예제 #4
0
파일: Utils.cs 프로젝트: ScottIsAFool/InTwo
        public static async Task <bool> SaveTile(UIElement tile, int height, int width, string file)
        {
            try
            {
                var asyncService = SimpleIoc.Default.GetInstance <IAsyncStorageService>();

                if (await asyncService.FileExistsAsync(file))
                {
                    await asyncService.DeleteFileAsync(file);
                }

                var tileBitmap = new WriteableBitmap(width, height);
                tileBitmap.Render(tile, null);
                tileBitmap.Invalidate();

                using (var fileStream = await asyncService.CreateFileAsync(file))
                {
                    var encoder = new PngEncoder();
                    var image   = tileBitmap.ToImage();
                    encoder.Encode(image, fileStream);
                }

                return(true);
            }
            catch
            {
            }
            return(false);
        }
예제 #5
0
        /// <summary>
        /// Saves the image to the given stream with the png format.
        /// </summary>
        /// <typeparam name="TPixel">The pixel format.</typeparam>
        /// <param name="source">The image this method extends.</param>
        /// <param name="stream">The stream to save the image to.</param>
        /// <param name="encoder">The options for the encoder.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the stream is null.</exception>
        /// <returns>
        /// The <see cref="Image{TPixel}"/>.
        /// </returns>
        public static Image <TPixel> SaveAsPng <TPixel>(this Image <TPixel> source, Stream stream, PngEncoder encoder)
            where TPixel : struct, IPixel <TPixel>
        {
            encoder = encoder ?? new PngEncoder();
            encoder.Encode(source, stream);

            return(source);
        }
        /// <summary>
        /// Saves the image to the given stream with the png format.
        /// </summary>
        /// <typeparam name="TColor">The pixel format.</typeparam>
        /// <param name="source">The image this method extends.</param>
        /// <param name="stream">The stream to save the image to.</param>
        /// <param name="options">The options for the encoder.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the stream is null.</exception>
        /// <returns>
        /// The <see cref="Image{TColor}"/>.
        /// </returns>
        public static Image <TColor> SaveAsPng <TColor>(this Image <TColor> source, Stream stream, IPngEncoderOptions options)
            where TColor : struct, IPixel <TColor>
        {
            PngEncoder encoder = new PngEncoder();

            encoder.Encode(source, stream, options);

            return(source);
        }
예제 #7
0
        public bool Save(string path, int quality, int compression)
        {
            CheckTexture();
            SensorCamera.Render();
            if (Distorted)
            {
                LensDistortion.Distort(SensorCamera.targetTexture, DistortedTexture);
            }
            var readback = AsyncGPUReadback.Request(Distorted ? DistortedTexture : SensorCamera.targetTexture, 0, TextureFormat.RGBA32);

            readback.WaitForCompletion();

            if (readback.hasError)
            {
                Debug.Log("Failed to read GPU texture");
                return(false);
            }

            Debug.Assert(readback.done);
            var data = readback.GetData <byte>();

            var bytes = new byte[16 * 1024 * 1024];
            int length;

            var ext = System.IO.Path.GetExtension(path).ToLower();

            if (ext == ".png")
            {
                length = PngEncoder.Encode(data, Width, Height, 4, compression, bytes);
            }
            else if (ext == ".jpeg" || ext == ".jpg")
            {
                length = JpegEncoder.Encode(data, Width, Height, 4, quality, bytes);
            }
            else
            {
                return(false);
            }

            if (length > 0)
            {
                try
                {
                    using (var file = System.IO.File.Create(path))
                    {
                        file.Write(bytes, 0, length);
                    }
                    return(true);
                }
                catch
                {
                }
            }

            return(false);
        }
예제 #8
0
        /// <summary>
        /// Writes to specified image to the stream.
        /// </summary>
        /// <param name="image">The image to write to the stream. Cannot be null.</param>
        /// <param name="stream">The target stream. Cannot be null.</param>
        /// <exception cref="ArgumentNullException">
        ///     <para><paramref name="image"/> is null (Nothing in Visual Basic).</para>
        ///     <para>- or -</para>
        ///     <para><paramref name="stream"/> is null (Nothing in Visual Basic).</para>
        /// </exception>
        public static void WriteToStream(this ExtendedImage image, Stream stream)
        {
            Contract.Requires <ArgumentNullException>(image != null, "Image cannot be null.");
            Contract.Requires <ArgumentException>(image.IsFilled, "Image has not been loaded.");
            Contract.Requires <ArgumentNullException>(stream != null, "Stream cannot be null.");

            PngEncoder encoder = new PngEncoder();

            encoder.Encode(image, stream);
        }
예제 #9
0
 public void Decode_32bitTestImages(string path, int w, int h)
 {
     var d = new PngDecoder();
     var pixels = d.Decode(File.ReadAllBytes(path));
     Assert.AreEqual(w, pixels.GetLength(0));
     Assert.AreEqual(h, pixels.GetLength(1));
     Assert.IsNotNull(pixels);
     var e = new PngEncoder(new PngEncoderOptions());
     var encodedPixels = e.Encode(pixels);
     File.WriteAllBytes(Path.ChangeExtension(path, "out.png"), encodedPixels);
 }
예제 #10
0
        static Stream GetPngStream(WriteableBitmap bmp)
        {
#if TRIAL
            bmp = AddTrialTextToImage(bmp);
#endif
            PngEncoder enc = new PngEncoder();
            enc.IsWritingUncompressed = false;
            var ms = new MemoryStream();
            enc.Encode(bmp.ToImage(), ms);
            ms.Position = 0;
            return(ms);
        }
예제 #11
0
        public static byte[] ImageToByte(this Image <Rgba32> img, HttpRequest context, bool autoResize = true, IImageFormat format = null, bool autoDispose = false)
        {
            if (format == null)
            {
                format = ImageFormats.Png;
            }
            if ((context?.Query.ContainsKey("resize") ?? false) && autoResize)
            {
                string  userResizeAmount = context.Query["resize"];
                decimal resizeAmount     = decimal.Parse(userResizeAmount);
                if (resizeAmount != 1 && (img.Height * resizeAmount) < 50000 && (img.Width * resizeAmount) < 50000)
                {
                    img = img.Clone(c => c.Resize(new ResizeOptions()
                    {
                        Mode    = ResizeMode.Stretch,
                        Sampler = new NearestNeighborResampler(),
                        Size    = new Size((int)(img.Width * resizeAmount), (int)(img.Height * resizeAmount))
                    }));
                }
            }

            using (MemoryStream mem = new MemoryStream())
            {
                if (format == ImageFormats.Png)
                {
                    pngEncoder.Encode(img, mem);
                }
                else if (format == ImageFormats.Gif)
                {
                    gifEncoder.Encode(img, mem);
                }
                else
                {
                    img.Save(mem, format);
                }
                using (BinaryWriter writer = new BinaryWriter(mem))
                    writer.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new
                    {
                        notice    = "Generated by MapleStory.IO",
                        container = Startup.Hostname ?? "Debug",
                        gitHash   = Startup.SHA1,
                        url       = context == null ? "Debug" : context.Path.ToString(),
                        createdAt = DateTime.UtcNow
                    }));

                if (autoDispose)
                {
                    ThreadPool.QueueUserWorkItem((s) => img.Dispose());
                }
                return(mem.ToArray());
            }
        }
예제 #12
0
        public void Decode_32bitTestImages(string path, int w, int h)
        {
            var d      = new PngDecoder();
            var pixels = d.Decode(File.ReadAllBytes(path));

            Assert.AreEqual(w, pixels.GetLength(0));
            Assert.AreEqual(h, pixels.GetLength(1));
            Assert.IsNotNull(pixels);
            var e             = new PngEncoder(new PngEncoderOptions());
            var encodedPixels = e.Encode(pixels);

            File.WriteAllBytes(Path.ChangeExtension(path, "out.png"), encodedPixels);
        }
예제 #13
0
        private OxyImage GetGradientImage(OxyColor color1, OxyColor color2)
        {
            int n         = 256;
            var imageData = new OxyColor[1, n];

            for (int i = 0; i < n; i++)
            {
                imageData[0, i] = OxyColor.Interpolate(color1, color2, i / (n - 1.0));
            }

            var encoder = new PngEncoder(new PngEncoderOptions());

            return(new OxyImage(encoder.Encode(imageData)));
        }
        private async Task SaveTheImage(WriteableBitmap bitmap)
        {
            if (await _storageService.FileExistsAsync(LockScreenFile))
            {
                await _storageService.DeleteFileAsync(LockScreenFile);
            }

            using (var fileStream = await _storageService.CreateFileAsync(LockScreenFile))
            {
                var encoder = new PngEncoder();
                var image   = bitmap.ToImage();
                encoder.Encode(image, fileStream);
            }
        }
예제 #15
0
    public bool Save(string path, int quality, int compression)
    {
        renderCam.Render();

        Reader.Start();
        Reader.WaitForCompletion();

        var data = Reader.GetData();

        var bytes = new byte[16 * 1024 * 1024];
        int length;

        var ext = System.IO.Path.GetExtension(path).ToLower();

        if (ext == ".png")
        {
            length = PngEncoder.Encode(data, videoWidth, videoHeight, Reader.BytesPerPixel, compression, bytes);
        }
        else if (ext == ".jpeg" || ext == ".jpg")
        {
            length = JpegEncoder.Encode(data, videoWidth, videoHeight, Reader.BytesPerPixel, quality, bytes);
        }
        else
        {
            return(false);
        }

        if (length > 0)
        {
            try
            {
                using (var file = System.IO.File.Create(path))
                {
                    file.Write(bytes, 0, length);
                }
                return(true);
            }
            catch
            {
            }
        }
        return(false);
    }
예제 #16
0
        public void InfersColorTypeAndBitDepth <TPixel>(TestImageProvider <TPixel> provider, PngColorType pngColorType, PngBitDepth pngBitDepth)
            where TPixel : struct, IPixel <TPixel>
        {
            using (Stream stream = new MemoryStream())
            {
                var encoder = new PngEncoder();
                encoder.Encode(provider.GetImage(), stream);

                stream.Seek(0, SeekOrigin.Begin);

                var decoder = new PngDecoder();

                Image image = decoder.Decode(Configuration.Default, stream);

                PngMetadata metadata = image.Metadata.GetPngMetadata();
                Assert.Equal(pngColorType, metadata.ColorType);
                Assert.Equal(pngBitDepth, metadata.BitDepth);
            }
        }
예제 #17
0
    public bool SaveAsync(string imgFileName, string timeFileName, int quality, int compression)
    {
        renderCam.Render();
        DateTime renderTime = DateTime.Now;

        Reader.Start();
        Reader.Update(true);

        var data = Reader.GetData();

        var bytes = new byte[16 * 1024 * 1024];
        int length;

        var ext = System.IO.Path.GetExtension(imgFileName).ToLower();

        if (ext == ".png")
        {
            length = PngEncoder.Encode(data, videoWidth, videoHeight, Reader.BytesPerPixel, compression, bytes);
        }
        else if (ext == ".jpeg" || ext == ".jpg")
        {
            length = JpegEncoder.Encode(data, videoWidth, videoHeight, Reader.BytesPerPixel, quality, bytes);
        }
        else
        {
            return(false);
        }

        if (length > 0)
        {
            try
            {
                SaveAsync(bytes, length, imgFileName, timeFileName, renderTime);
                return(true);
            }
            catch
            {
            }
        }
        return(false);
    }
        private Task <Stream> GetImageStreamInternal(SignatureImageFormat format, Size scale, Rect signatureBounds, Size imageSize, float strokeWidth, Color strokeColor, Color backgroundColor)
        {
            var image = GetImageInternal(scale, signatureBounds, imageSize, strokeWidth, strokeColor, backgroundColor);

            if (image != null)
            {
                if (format == SignatureImageFormat.Jpeg)
                {
                    var stream = new MemoryStream();
                    image.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 0, 100);
                    return(Task.FromResult <Stream> (stream));
                }
                else if (format == SignatureImageFormat.Png)
                {
                    var stream  = new MemoryStream();
                    var encoder = new PngEncoder();
                    encoder.Encode(image.ToImage(), stream);
                    return(Task.FromResult <Stream> (stream));
                }
            }
            return(Task.FromResult <Stream> (null));
        }
예제 #19
0
        /// <summary>
        /// Encodes the given writeable bitmap using a <seealso cref="PngEncoder"/>.
        /// </summary>
        /// <param name="writeableBitmap">The bitmap to encode.</param>
        /// <returns>A base 64 representation of the bitmap encoded.</returns>
        private static string EncodeImage(WriteableBitmap writeableBitmap)
        {
            string projectThumbnail = null;

            MemoryStream ms = null;

            try
            {
                ms = PngEncoder.Encode(writeableBitmap) as MemoryStream;
            }
            catch (Exception ex)
            {
                // TODO: log exception
            }

            if (ms != null)
            {
                BinaryReader binaryReader = new BinaryReader(ms);
                byte[]       currentBytes = binaryReader.ReadBytes(1000);
                int          bytesRead    = currentBytes.Length;
                List <byte>  byteList     = currentBytes.ToList();

                while (bytesRead == 1000)
                {
                    currentBytes = binaryReader.ReadBytes(1000);
                    bytesRead    = currentBytes.Length;
                    byteList.AddRange(currentBytes);
                }

                binaryReader.Close();
                ms.Close();

                projectThumbnail = Convert.ToBase64String(byteList.ToArray());
            }

            return(projectThumbnail);
        }
예제 #20
0
        /// <summary>
        /// Converts the image to a png stream, which can be assigned to
        /// a silverlight image control as image source and applies the specified
        /// filter before converting the image.
        /// </summary>
        /// <param name="image">The image, which should be converted. Cannot be null
        /// (Nothing in Visual Basic).</param>
        /// <param name="filter">The filter, which should be applied before converting the
        /// image or null, if no filter should be applied to. Cannot be null.</param>
        /// <returns>The resulting stream.</returns>
        /// <exception cref="ArgumentNullException">
        ///     <para><paramref name="image"/> is null (Nothing in Visual Basic).</para>
        ///     <para>- or -</para>
        ///     <para><paramref name="filter"/> is null (Nothing in Visual Basic).</para>
        /// </exception>
        public static Stream ToStream(this ExtendedImage image, IImageFilter filter)
        {
            Contract.Requires <ArgumentNullException>(image != null, "Image cannot be null.");
            Contract.Requires <ArgumentException>(image.IsFilled, "Image has not been loaded.");

            MemoryStream memoryStream = new MemoryStream();

            try
            {
                ExtendedImage temp = image;

                if (filter != null)
                {
                    temp = image.Clone();

                    filter.Apply(temp, image, temp.Bounds);
                }

                PngEncoder encoder = new PngEncoder();
                encoder.IsWritingUncompressed = true;
                encoder.Encode(temp, memoryStream);

                memoryStream.Seek(0, SeekOrigin.Begin);
            }
            catch
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                    memoryStream = null;
                }
                throw;
            }

            return(memoryStream);
        }
예제 #21
0
        /// <summary>
        /// Used to render the contents to a tile
        /// </summary>
        /// <returns>a <see cref="StandardTileData"/> with the contents of this control</returns>
        public StandardTileData ToTile()
        {
            // Need to call these, otherwise the contents aren't rendered correctly.
            this.Measure(new Size(173, 173));
            this.Arrange(new Rect(0, 0, 173, 173));

            // The png encoder is the work of the ImageTools API. http://imagetools.codeplex.com/
            ExtendedImage tileImaged = this.ToImage();

            Encoders.AddEncoder <PngEncoder>();

            var p = new PngEncoder();

            const string tempFileName = "/Shared/ShellContent/tileImage.png";

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists(tempFileName))
                {
                    myIsolatedStorage.DeleteFile(tempFileName);
                }

                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempFileName);
                p.Encode(tileImaged, fileStream);
                fileStream.Close();
            }

            var newTile = new StandardTileData
            {
                Title           = Title,
                BackgroundImage =
                    new Uri("isostore:" + tempFileName, UriKind.RelativeOrAbsolute)
            };

            return(newTile);
        }
예제 #22
0
        public unsafe void int_10()
        {
            const int vga_vmemsize = 0x200000;

            switch (ah.UInt16)
            {
            case 0x0f:
                ah = 0x50;  // width in char
                al = 0x3;   // video mode
                bh = 0;     // page
                break;

            case 0x4f:     // VESA Calls
                switch (al.UInt16)
                {
                case 0x01:         // Get SVGA Mode Information
                {
                    if (cx != 0x101)
                    {
                        throw new NotImplementedException();
                    }

                    al = 0x4f;
                    ah = 0;         // success

                    {
                        var page_size = 640 * 480;
                        page_size = page_size & (~15);

                        ushort mode_attr = 0x9b;

                        var span = Memory.GetFixSize(es, di, Marshal.SizeOf <mode_info>());
                        span.Clear();

                        ref var mi = ref Memory.Ref <mode_info>(es[di]);

                        mi.BytesPerScanLine = 640;
                        mi.NumberOfPlanes   = 1;
                        mi.BitsPerPixel     = 8;
                        mi.MemoryModel      = 4;
                        mi.WinAAttributes   = 7;

                        if (vga_vmemsize < page_size)
                        {
                            throw new NotImplementedException();
                        }
                        else
                        {
                            mi.ModeAttributes     = mode_attr;
                            mi.NumberOfImagePages = (byte)((vga_vmemsize / page_size) - 1);
                        }

                        mi.WinGranularity = 64;
                        mi.WinSize        = 64;
                        mi.WinASegment    = 0xa000;
                        mi.XResolution    = 640;
                        mi.YResolution    = 480;

                        if (added_callback_setwindow == false)
                        {
                            RawProgramMain.AddInternalDynamicMethod(callback_setwindow, 16, 0xf0001320);
                            added_callback_setwindow = true;
                        }

                        mi.WinFuncPtr    = 0xf0001320;
                        mi.NumberOfBanks = 1;
                        mi.Reserved_page = 1;
                        mi.XCharSize     = 8;
                        mi.YCharSize     = 16;
                        mi.PhysBasePtr   = 0;
                    }

                    break;
                }

                case 0x02:         // Set videomode
                {
                    if (bx != 0x101)
                    {
                        throw new NotImplementedException();
                    }

                    al = 0x4f;
                    ah = 0;         // success

                    // /* mode  ,type     ,sw  ,sh  ,tw ,th ,cw,ch ,pt,pstart  ,plength,htot,vtot,hde,vde special flags */
                    //{ 0x101  ,M_LIN8   ,640 ,480 ,80 ,30 ,8 ,16 ,1 ,0xa0000 ,0x10000,100 ,525 ,80 ,480 ,0    },

                    break;
                }

                case 0x05:
                {
                    if (bh != 0)
                    {
                        throw new NotImplementedException();
                    }

                    // ah = SetCPUWindow(bl, dl); (window, address)

                    if (bl != 0)
                    {
                        ah = 1;
                    }
                    else
                    {
                        if (dl.Int32 * 0x10000 < vga_vmemsize)
                        {
                            ah = 0;
                            // out(0x3d4, 0x6a)
                            // out(0x3d5, dl)
                            // std::cerr << static_cast<uint>(dl) << std::endl;


                            var curr_bank = ((Memory)Memory)
                                            .mem_phys_raw(0xa0000, 0x10000)
                                            .Slice(0, 0x10000);


                            var offset = 3 * curr_bank_num * 0x10000;
                            for (var i = 0; i < 0x10000; i++)
                            {
                                if (img_data.Length <= offset + 3 * i + 2)
                                {
                                    break;
                                }

                                var c = curr_bank[i];

#if false
                                img_data[offset + 3 * i + 0] = c;
                                img_data[offset + 3 * i + 1] = c;
                                img_data[offset + 3 * i + 2] = c;
#else
                                img_data[offset + 3 * i + 2] = pal[c].rgb[2];
                                img_data[offset + 3 * i + 1] = pal[c].rgb[1];
                                img_data[offset + 3 * i + 0] = pal[c].rgb[0];
#endif
                            }

                            //if (dl == 0)
                            {
                                //var width = 640;
                                //var height = 480;

                                var ms         = new MemoryStream();
                                var nimg       = Image.LoadPixelData <Rgb24>(img_data, buf_width, buf_height);
                                var pngEncoder = new PngEncoder();
                                pngEncoder.CompressionLevel = 1;
                                pngEncoder.Encode(nimg, ms);
                                PngBytes = ms.ToArray();

                                var forgot = MainHub.SendClientUpdateImage(RawProgramMain.ServiceProvider);

                                fileNum++;
                                if (!string.IsNullOrEmpty(RawProgramMain.Configuration.Dos.PngOutput))
                                {
                                    var pngOutput = RawProgramMain.Configuration.Dos.PngOutput;
                                    var filePath  = Path.Combine(pngOutput, $"img-{fileNum:D4}.png");
                                    File.WriteAllBytes(filePath, PngBytes);
                                }

                                var time = DateTime.Now.TimeOfDay;
                                time = new TimeSpan(0, time.Hours, time.Minutes, time.Seconds, time.Milliseconds / 10 * 10);
                                NonBlockingConsole.WriteLine($"    Screen. Time: {time:hh\\:mm\\:ss\\.ff}, Number: {fileNum}.");
                            }


                            var need_cpy = (curr_bank_num * 0x10000 < all_banks.Length);

                            if (need_cpy)
                            {
                                curr_bank.CopyTo(all_banks.AsSpan(curr_bank_num * 0x10000));
                            }

                            curr_bank_num = dl.UInt16;

                            if (need_cpy)
                            {
                                all_banks.AsSpan().Slice(curr_bank_num * 0x10000, 0x10000).CopyTo(curr_bank);
                            }
                        }
                        else
                        {
                            ah = 1;
                        }
                    }

                    al = 0x4f;
                    break;
                }

                default:
                    throw new NotImplementedException();
                }

                break;
예제 #23
0
        //Aktion
        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            //Bild vom Internet in den Isolated Storage speichern
            try
            {
                //Dateiname anhand der DownloadID erstellen
                if (DownloadID == 0)
                {
                    //Dateiname erstellen
                    FileName = "txt.txt";
                    //Alte Datei löschen
                    if (file.FileExists("TempStyles/txt.txt"))
                    {
                        file.DeleteFile("TempStyles/txt.txt");
                    }
                }
                else
                {
                    //Dateiname erstellen
                    FileName = "1.png";
                    //Alte Datei löschen
                    if (file.FileExists("TempStyles/1.png"))
                    {
                        file.DeleteFile("TempStyles/1.png");
                    }
                }


                //Prüfen ob Downloadordner existiert
                if (file.DirectoryExists("TempStyles"))
                {
                }
                else
                {
                    file.CreateDirectory("TempStyles");
                }

                //Prüfen ob Datei bereits vorhanden
                if (file.FileExists("TempStyles/" + FileName))
                {
                    file.DeleteFile("TempStyles/" + FileName);
                }

                //Datei in Isolated Storage laden
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("TempStyles/" + FileName, System.IO.FileMode.Create, file))
                {
                    byte[] buffer = new byte[1024];
                    while (e.Result.Read(buffer, 0, buffer.Length) > 0)
                    {
                        stream.Write(buffer, 0, buffer.Length);
                    }
                }

                //Nach dem Das Bild heruntergeladen wurde, Bild laden und in Storage schreiben
                if (DownloadID == 1)
                {
                    //Writeable Bitmap erstellen
                    var    tempImage = new WriteableBitmap(1, 1);
                    byte[] data1;
                    {
                        using (IsolatedStorageFileStream isfs = file.OpenFile("TempStyles/1.png", FileMode.Open, FileAccess.Read))
                        {
                            data1 = new byte[isfs.Length];
                            isfs.Read(data1, 0, data1.Length);
                            isfs.Close();
                        }
                    }
                    MemoryStream ms = new MemoryStream(data1);

                    //Bild in WriteableBitmap
                    tempImage.SetSource(ms);
                    ImagesOnline1.Source = tempImage;

                    //Bild Spiegeln
                    tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                    //Altes Bild löschen
                    if (file.FileExists("TempStyles/2.png"))
                    {
                        file.DeleteFile("TempStyles/2.png");
                    }
                    //Bild speichern
                    Decoders.AddDecoder <PngDecoder>();
                    var img     = tempImage.ToImage();
                    var encoder = new PngEncoder();
                    using (var stream = new IsolatedStorageFileStream("TempStyles/2.png", FileMode.Create, file))
                    {
                        encoder.Encode(img, stream);
                        stream.Close();
                    }
                    //Bild ausgeben
                    ImagesOnline2.Source = tempImage;


                    //Bild Spiegeln
                    tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Horizontal);
                    //Altes Bild löschen
                    if (file.FileExists("TempStyles/3.png"))
                    {
                        file.DeleteFile("TempStyles/3.png");
                    }
                    //Bild speichern
                    Decoders.AddDecoder <PngDecoder>();
                    img     = tempImage.ToImage();
                    encoder = new PngEncoder();
                    using (var stream = new IsolatedStorageFileStream("TempStyles/3.png", FileMode.Create, file))
                    {
                        encoder.Encode(img, stream);
                        stream.Close();
                    }
                    //Bild ausgeben
                    ImagesOnline3.Source = tempImage;


                    //Bild Spiegeln
                    tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                    //Altes Bild löschen
                    if (file.FileExists("TempStyles/4.png"))
                    {
                        file.DeleteFile("TempStyles/4.png");
                    }
                    //Bild speichern
                    Decoders.AddDecoder <PngDecoder>();
                    img     = tempImage.ToImage();
                    encoder = new PngEncoder();
                    using (var stream = new IsolatedStorageFileStream("TempStyles/4.png", FileMode.Create, file))
                    {
                        encoder.Encode(img, stream);
                        stream.Close();
                    }
                    //Bild ausgeben
                    ImagesOnline4.Source = tempImage;
                }
            }
            catch
            {
            }
            //DownloadID erhöhen um nächstes Bild aus aus dem Netz herunterzuladen
            DownloadID++;
        }
예제 #24
0
        /// <summary>
        /// Determines if the images at the specified paths are equal.
        /// </summary>
        /// <param name="expected">Path to the expected image.</param>
        /// <param name="actual">Path to the actual image.</param>
        /// <param name="message">The message.</param>
        /// <param name="output">The output difference file.</param>
        public static void AreEqual(string expected, string actual, string message, string output)
        {
            var expectedImage = LoadImage(expected);
            var actualImage   = LoadImage(actual);

            if (expectedImage == null)
            {
                EnsureFolder(expected);
                File.Copy(actual, expected);
                Assert.Fail("File not found: {0}", expected);
            }

            if (expectedImage.GetLength(0) != actualImage.GetLength(0))
            {
                Assert.Fail("Expected height: {0}\nActual height:{1}\n{2}", expectedImage.GetLength(0), actualImage.GetLength(0), message);
            }

            if (expectedImage.GetLength(1) != actualImage.GetLength(1))
            {
                Assert.Fail("Expected width: {0}\nActual width:{1}\n{2}", expectedImage.GetLength(1), actualImage.GetLength(1), message);
            }

            var w               = expectedImage.GetLength(0);
            var h               = expectedImage.GetLength(1);
            var differences     = 0;
            var differenceImage = new OxyColor[w, h];

            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    if (!expectedImage[j, i].Equals(actualImage[j, i]))
                    {
                        differences++;
                        differenceImage[j, i] = OxyColors.Red;
                    }
                    else
                    {
                        differenceImage[j, i] = actualImage[j, i].ChangeIntensity(100);
                    }
                }
            }

            if (differences > 0)
            {
                if (output != null)
                {
                    for (int i = 0; i < h; i++)
                    {
                        for (int j = 0; j < w; j++)
                        {
                            if (!expectedImage[j, i].Equals(actualImage[j, i]))
                            {
                            }
                        }
                    }

                    EnsureFolder(output);
                    var encoder = new PngEncoder(new PngEncoderOptions());
                    File.WriteAllBytes(output, encoder.Encode(differenceImage));
                }

                Assert.Fail("Pixel differences: {0}\n{1}", differences, message);
            }
        }
예제 #25
0
        private static object PseudoLocalizeObject(object obj)
        {
#if !SILVERLIGHT
            // "Translate" bitmaps by inverting every pixel
            var bitmap = obj as Bitmap;
            if (null != bitmap)
            {
                for (var y = 0; y < bitmap.Height; y++)
                {
                    for (var x = 0; x < bitmap.Width; x++)
                    {
                        var color        = bitmap.GetPixel(x, y);
                        var inverseColor = Color.FromArgb(color.A, (byte)~color.R, (byte)~color.G, (byte)~color.B);
                        bitmap.SetPixel(x, y, inverseColor);
                    }
                }
            }
#endif

            // "Translate" encoded images by decoding, inverting every pixel, and re-encoding
            var byteArray = obj as byte[];
            if (null != byteArray)
            {
                try
                {
                    using (var stream = new MemoryStream(byteArray))
                    {
                        var bitmapImage = new BitmapImage();
#if SILVERLIGHT
                        bitmapImage.SetSource(stream);
#else
                        bitmapImage.BeginInit();
                        bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                        bitmapImage.StreamSource = stream;
                        bitmapImage.EndInit();
#endif
                        var writeableBitmap = new WriteableBitmap(bitmapImage);
                        var width           = writeableBitmap.PixelWidth;
                        var height          = writeableBitmap.PixelHeight;
#if SILVERLIGHT
                        var pixels = writeableBitmap.Pixels;
#else
                        var pixels = new int[width * height];
                        var stride = width * 4;
                        writeableBitmap.CopyPixels(pixels, stride, 0);
#endif
                        for (var i = 0; i < pixels.Length; i++)
                        {
                            uint pixel = (uint)pixels[i];
                            pixels[i] = (int)((~pixel & 0x00ffffff) | (pixel & 0xff000000));
                        }
#if SILVERLIGHT
                        obj = PngEncoder.Encode(width, height, pixels).ToArray();
#else
                        writeableBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, stride, 0);
                        var pngBitmapEncoder = new PngBitmapEncoder();
                        pngBitmapEncoder.Frames.Add(BitmapFrame.Create(writeableBitmap));
                        using (var memoryStream = new MemoryStream())
                        {
                            pngBitmapEncoder.Save(memoryStream);
                            obj = memoryStream.GetBuffer();
                        }
#endif
                    }
                }
                catch
                {
                    // byte[] may not have been an encoded image; leave obj alone
                }
            }

            // Return the object
            return(obj);
        }
예제 #26
0
        public static void CreateLivetileImage(LivetileData data, LiveItems liveItem)
        {
            Canvas          panel = null;
            WriteableBitmap wb    = null;

            switch (liveItem)
            {
            case LiveItems.Calendar:
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    panel            = GetCalendarCanvas(data);
                    panel.Background = data.GetBackgroundBrush(LiveItems.Calendar);

                    System.Diagnostics.Debug.WriteLine("달력 전 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.calendar.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        wb = new WriteableBitmap(panel, null);
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }

                    System.Diagnostics.Debug.WriteLine("달력 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    wb = wb.Resize(159, 159, WriteableBitmapExtensions.Interpolation.NearestNeighbor);
                    System.Diagnostics.Debug.WriteLine("달력 줄임 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.calendar.small.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }
                    System.Diagnostics.Debug.WriteLine("작은 달력 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);

                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.calendar.back.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        panel.Children.Clear();
                        panel.Width  = 1;
                        panel.Height = 1;
                        wb           = new WriteableBitmap(panel, null);
                        //System.Diagnostics.Debug.WriteLine("###########달력 이미지 저장전 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                        //System.Diagnostics.Debug.WriteLine("###########달력 이미지 저장후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    }
                    System.Diagnostics.Debug.WriteLine("타일 뒷면 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                }
                break;

            case LiveItems.Weather:
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    SolidColorBrush backBrush = data.GetBackgroundBrush(LiveItems.Weather);
                    panel            = GetWeatherCanvas(data);
                    panel.Background = backBrush;

                    System.Diagnostics.Debug.WriteLine("날씨 전 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.weather.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        wb = new WriteableBitmap(panel, null);
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }
                    System.Diagnostics.Debug.WriteLine("날씨 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    wb = wb.Resize(159, 159, WriteableBitmapExtensions.Interpolation.NearestNeighbor);
                    System.Diagnostics.Debug.WriteLine("날씨 줄임 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.weather.small.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }
                    System.Diagnostics.Debug.WriteLine("작은 날씨 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);

                    //날씨 백타일 (주간 일보)
                    panel            = GetWeatherBackCanvas(data);
                    panel.Background = backBrush;

                    System.Diagnostics.Debug.WriteLine("주간 날씨 전 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.weather.back.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        wb = new WriteableBitmap(panel, null);
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }
                    System.Diagnostics.Debug.WriteLine("주간 날씨 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                }
                break;

            case LiveItems.Battery:
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    panel            = GetBatteryCanvas(data);
                    panel.Background = data.GetBackgroundBrush(LiveItems.Battery);

                    System.Diagnostics.Debug.WriteLine("배터리 전 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.battery.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        wb = new WriteableBitmap(panel, null);
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }
                    System.Diagnostics.Debug.WriteLine("배터리 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    wb = wb.Resize(159, 159, WriteableBitmapExtensions.Interpolation.NearestNeighbor);
                    System.Diagnostics.Debug.WriteLine("배터리 줄임 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.battery.small.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }
                    System.Diagnostics.Debug.WriteLine("작은 배터리 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);


                    using (IsolatedStorageFileStream targetStream = isoStore.OpenFile("Shared/ShellContent/livetile.battery.back.jpg", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        panel.Children.Clear();
                        panel.Width  = 1;
                        panel.Height = 1;
                        wb           = new WriteableBitmap(panel, null);
                        //wb.SaveJpeg(targetStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        pngEncoder.Encode(wb.ToImage(), targetStream);
                    }
                    System.Diagnostics.Debug.WriteLine("배터리 뒷면 저장 후 =>" + Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage);
                }
                break;
            }

            wb = null;
            GC.Collect();
        }
예제 #27
0
        //---------------------------------------------------------------------------------------------------------



        //Alle vorinstallierten Styles wiederherstellen
        //---------------------------------------------------------------------------------------------------------
        private void Restore_Click(object sender, RoutedEventArgs e)
        {
            //Abfrage ob wiederhergestellt werden soll
            if (MessageBox.Show(Lockscreen_Swap.AppResx.Z04_RestoreNote, Lockscreen_Swap.AppResx.Notification, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                //Styles wiederherstellen
                for (int i = 1; i <= 9; i++)
                {
                    //Prüfen ob Style vorhanden ist
                    if (!file.FileExists("Styles/000000" + i + ".txt"))
                    {
                        //Style kopieren
                        using (Stream input = Application.GetResourceStream(new Uri("Styles/" + i + ".txt", UriKind.Relative)).Stream)
                        {
                            // Create a stream for the new file in the local folder.
                            using (filestream = file.CreateFile("Styles/000000" + i + ".txt"))
                            {
                                // Initialize the buffer.
                                byte[] readBuffer = new byte[4096];
                                int    bytesRead  = -1;

                                // Copy the file from the installation folder to the local folder.
                                while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
                                {
                                    filestream.Write(readBuffer, 0, bytesRead);
                                }
                            }
                        }

                        //Bilder in Styles Images kppieren
                        var tempImage = new WriteableBitmap(1, 1);

                        //Bild kopieren
                        using (Stream input = Application.GetResourceStream(new Uri("Images/StylesImages/" + i + ".png", UriKind.Relative)).Stream)
                        {
                            // Create a stream for the new file in the local folder.
                            using (filestream = file.CreateFile("StylesImages/000000" + i + ".1.png"))
                            {
                                // Initialize the buffer.
                                byte[] readBuffer = new byte[4096];
                                int    bytesRead  = -1;

                                // Copy the file from the installation folder to the local folder.
                                while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
                                {
                                    filestream.Write(readBuffer, 0, bytesRead);
                                }
                            }
                        }
                        //Bild laden
                        byte[]       tempData;
                        MemoryStream tempMs;
                        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream isfs = isf.OpenFile("StylesImages/000000" + i + ".1.png", FileMode.Open, FileAccess.Read))
                            {
                                tempData = new byte[isfs.Length];
                                isfs.Read(tempData, 0, tempData.Length);
                                isfs.Close();
                            }
                        }
                        tempMs = new MemoryStream(tempData);
                        tempImage.SetSource(tempMs);

                        //Bild Spiegeln
                        tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Vertical);

                        //Bild speichern
                        Decoders.AddDecoder <PngDecoder>();
                        var img     = tempImage.ToImage();
                        var encoder = new PngEncoder();
                        using (var stream = new IsolatedStorageFileStream("StylesImages/000000" + i + ".2.png", FileMode.Create, file))
                        {
                            encoder.Encode(img, stream);
                            stream.Close();
                        }

                        //Bild Spiegeln
                        tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Horizontal);

                        //Bild speichern
                        Decoders.AddDecoder <PngDecoder>();
                        img     = tempImage.ToImage();
                        encoder = new PngEncoder();
                        using (var stream = new IsolatedStorageFileStream("StylesImages/000000" + i + ".3.png", FileMode.Create, file))
                        {
                            encoder.Encode(img, stream);
                            stream.Close();
                        }
                        //Bild Spiegeln
                        tempImage = tempImage.Flip(WriteableBitmapExtensions.FlipMode.Vertical);

                        //Bild speichern
                        Decoders.AddDecoder <PngDecoder>();
                        img     = tempImage.ToImage();
                        encoder = new PngEncoder();
                        using (var stream = new IsolatedStorageFileStream("StylesImages/000000" + i + ".4.png", FileMode.Create, file))
                        {
                            encoder.Encode(img, stream);
                            stream.Close();
                        }
                    }

                    //Style in InstalledStyles schreiben
                    InstalledStyles += "000000" + i + ".txt;";
                    InstalledStyles  = InstalledStyles.Trim(new char[] { '\r', '\n' });
                    //Installierte Styles speichern
                    filestream = file.CreateFile("Settings/InstalledStyles.txt");
                    sw         = new StreamWriter(filestream);
                    sw.WriteLine(InstalledStyles);
                    sw.Flush();
                    filestream.Close();
                }

                //Bilderliste neu erstellen
                ActionIfSelect = false;
                try
                {
                    LBInstalled.SelectedIndex = -1;
                }
                catch
                {
                }
                CreateImages();
                ActionIfSelect = true;
                SelectImages();

                //Online Styles neu erstellen
                if (Source != "")
                {
                    CreateOnlineImages();
                }
            }
        }
예제 #28
0
        static int Main(string[] args)
        {
            //DisplayCurrentDirectories();
            try {
                #region Read and Apply Config
                /* ___Program Settings___ */
                // read arguments from config file (and read backupConfig.txt if config.txt is not available, for debugging purposes)
                ParseConfigFile();
                //ParseArgs(args);      // for command line args

                /* ___Gobo Image List___ */
                var testReader = new StreamReader(Paths.GoboInfo);
                if (testReader != null)
                {
                    Console.WriteLine("Gobo-info file length:" + testReader.ReadToEnd().Length.ToString());
                }
                else
                {
                    Console.WriteLine("File failed to open: " + Paths.GoboInfo);
                }
                Console.WriteLine("");
                testReader.Close();

                var reader = new StreamReader(Paths.GoboInfo);
                // populate list of gobo objecsts
                while (!reader.EndOfStream)
                {
                    string line  = reader.ReadLine();
                    var    items = Regex.Match(line, @"([^;]+)\;([^;]+)");
                    gobos.Add(new GoboObj(items.Groups[1].Value, items.Groups[2].Value));
                }


                // handle image dimensions
                widthOrig  = 128;
                heightOrig = 128;
                widthNew   = widthOrig + (2 * borderSize);
                heightNew  = heightOrig + (2 * borderSize);

                DisplayArgs();
                #endregion


                // find and confirm the existence of each image
                foreach (var gobo in gobos)
                {
                    // verify and set full filepaths to source images
                    gobo.SetFilePath(Paths.ma2General);

                    // create on and off copies
                    try
                    {
                        // read original image
                        var inStream = new FileStream(gobo.FilePath, FileMode.Open, FileAccess.Read);
                        var imgOrig  = new PngDecoder().Decode <Rgba32>(Configuration.Default, inStream);
                        inStream.Close();

                        var imgOn  = new Image <Rgba32>(widthNew, heightNew);
                        var imgOff = new Image <Rgba32>(widthNew, heightNew);

                        // fill in top and bottom borders
                        for (int x = 0; x < widthNew; x++)
                        {
                            for (int i = 0; i < borderSize; i++)
                            {
                                imgOn[x, i]  = imgOn[x, heightNew - i - 1] = onPixel;
                                imgOff[x, i] = imgOff[x, heightNew - i - 1] = offPixel;
                            }
                        }

                        // fill in left and right borders
                        for (int y = 0; y < heightNew; y++)
                        {
                            for (int i = 0; i < borderSize; i++)
                            {
                                imgOn[i, y]  = imgOn[widthNew - i - 1, y] = onPixel;
                                imgOff[i, y] = imgOff[widthNew - i - 1, y] = offPixel;
                            }
                        }

                        // fill in body of image
                        for (int x = 0; x < imgOrig.Width; x++)
                        {
                            for (int y = 0; y < imgOrig.Height; y++)
                            {
                                // handle offsets
                                int newX = x + borderSize;
                                int newY = y + borderSize;

                                // copy to new images
                                imgOn[newX, newY] = imgOff[newX, newY] = imgOrig[x, y];
                            }
                        }

                        // check that output directory exists; create if it doesn't
                        if (!Exists(Paths.Output))
                        {
                            Console.WriteLine("Creating output directory: " + Paths.Output);
                            CreateDirectory(Paths.Output);
                        }

                        // write images to files
                        var encoder      = new PngEncoder();
                        var outStreamOn  = new FileStream(Paths.Output + gobo.OnName + ".png", FileMode.OpenOrCreate, FileAccess.Write);
                        var outStreamOff = new FileStream(Paths.Output + gobo.OffName + ".png", FileMode.OpenOrCreate, FileAccess.Write);
                        encoder.Encode(imgOn, outStreamOn);
                        encoder.Encode(imgOff, outStreamOff);
                        outStreamOn.Close();
                        outStreamOff.Close();

                        successCt++;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: " + e.Message);
                        errorCt++;
                    }
                    Console.WriteLine("");
                }
            }
            catch (Exception e)
            {
                using (var writer = new StreamWriter(Paths.DebugFile))
                {
                    writer.WriteLine(e.Message);
                    foreach (var data in e.Data)
                    {
                        writer.WriteLine(data.ToString());
                    }
                }
            }

            // pausing for status read at end if opted-in
            Console.WriteLine("Successful writes: " + successCt.ToString());
            if (pauseAtEnd)
            {
                Console.Read();
            }

            // return errors; if 0, all went as expected
            if (errorCt == 0)
            {
                return(successCt);
            }
            else
            {
                return(-errorCt);
            }
        }
예제 #29
0
        private void OnImageStreamRequested(object sender, SignaturePadView.ImageStreamRequestedEventArgs e)
        {
            var ctrl = Control;

            if (ctrl != null)
            {
                var image = ctrl.GetImage();
#if NETFX_CORE || WINDOWS_UWP
                // http://lunarfrog.com/blog/how-to-save-writeablebitmap-as-png-file
                InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                var encoder = BitmapEncoder.CreateAsync((e.ImageFormat == SignatureImageFormat.Png) ? BitmapEncoder.PngEncoderId : BitmapEncoder.JpegEncoderId, stream).AsTask().Result;
                // Get pixels of the WriteableBitmap object
                byte[] pixels = image.PixelBuffer.ToArray();
                // Save the image file with jpg extension
                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)image.PixelWidth, (uint)image.PixelHeight, 96, 96, pixels);
                encoder.FlushAsync().AsTask().Wait();
                e.ImageStreamTask = Task.Run <Stream>(() =>
                {
                    return(stream.AsStream());
                });
#elif WINDOWS_PHONE
                ExtendedImage img = null;
                if (e.ImageFormat == SignatureImageFormat.Png)
                {
                    img = image.ToImage();
                }
                var stream = new MemoryStream();
                e.ImageStreamTask = Task.Run <Stream>(() =>
                {
                    if (e.ImageFormat == SignatureImageFormat.Png)
                    {
                        var encoder = new PngEncoder();
                        encoder.Encode(img, stream);
                        return(stream);
                    }
                    if (e.ImageFormat == SignatureImageFormat.Jpg)
                    {
                        image.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 0, 100);
                        return(stream);
                    }
                    return(null);
                });
#elif __IOS__
                e.ImageStreamTask = Task.Run(() =>
                {
                    if (e.ImageFormat == SignatureImageFormat.Png)
                    {
                        return(image.AsPNG().AsStream());
                    }
                    if (e.ImageFormat == SignatureImageFormat.Jpg)
                    {
                        return(image.AsJPEG().AsStream());
                    }
                    return(null);
                });
#elif __ANDROID__
                var stream = new MemoryStream();
                var format = e.ImageFormat == SignatureImageFormat.Png ? Bitmap.CompressFormat.Png : Bitmap.CompressFormat.Jpeg;
                e.ImageStreamTask = image
                                    .CompressAsync(format, 100, stream)
                                    .ContinueWith(task =>
                {
                    image.Recycle();
                    image.Dispose();
                    image = null;
                    if (task.Result)
                    {
                        return((Stream)stream);
                    }
                    else
                    {
                        return(null);
                    }
                });
#endif
            }
        }
예제 #30
0
        void FetchComicReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            // Clean the webclient that was created when this request was created.
            WebClient webClient = sender as WebClient;

            if (webClient != null)
            {
                webClient = null;
            }

            if (RESTError(e))
            {
                Debug.WriteLine("Error fetching comic image! Error: " + e.Error.ToString());
                return;
            }

            ComicItem currentComicModel = (ComicItem)e.UserState;

            Debug.WriteLine("Fetched comic strip image.");

            Stream reply = null;

            try
            {
                reply = (Stream)e.Result;
            }
            catch (WebException webEx)
            {
                if (webEx.Status != WebExceptionStatus.Success)
                {
                    Debug.WriteLine("Web error occured. Cannot load image!");
                    return;
                }
            }

            MemoryStream comicStripBytes = new MemoryStream();

            reply.CopyTo(comicStripBytes);
            byte[] imgBytes = comicStripBytes.ToArray();
            if (isGifImage(imgBytes))
            {
                Debug.WriteLine("Image is a GIF");

                ExtendedImage gifStrip = new ExtendedImage();
                gifStrip.LoadingCompleted +=
                    (s, args) => {
                    Debug.WriteLine("GIF loaded. Encoding GIF image to PNG image...");

                    ExtendedImage gifImage = (ExtendedImage)s;
                    MemoryStream  pngBytes = new MemoryStream();

                    ImageTools.IO.Png.PngEncoder enc = new PngEncoder();
                    enc.Encode(gifImage, pngBytes);

                    this.Dispatcher.BeginInvoke(() => {
                        Debug.WriteLine("Encoding done. Setting PNG bytes to BitmapImage and showing.");
                        showNewComic(currentComicModel, pngBytes);
                    });
                };

                gifStrip.UriSource = new Uri(currentComicModel.imageUrl,
                                             UriKind.Absolute);
            }
            else
            {
                Debug.WriteLine("Image is not a GIF. Putting image bytes directly to BitmapImage.");
                showNewComic(currentComicModel, comicStripBytes);
            }

            App.comicListModel.ComicLoading = false;
        }
예제 #31
0
        private void OnImageStreamRequested(object sender, SignaturePadView.ImageStreamRequestedEventArgs e)
        {
            var ctrl = Control;

            if (ctrl != null)
            {
                var image = ctrl.GetImage();
#if WINDOWS_PHONE
                ExtendedImage img = null;
                if (e.ImageFormat == SignatureImageFormat.Png)
                {
                    img = image.ToImage();
                }
                var stream = new MemoryStream();
                e.ImageStreamTask = Task.Run <Stream>(() =>
                {
                    if (e.ImageFormat == SignatureImageFormat.Png)
                    {
                        var encoder = new PngEncoder();
                        encoder.Encode(img, stream);
                        return(stream);
                    }
                    if (e.ImageFormat == SignatureImageFormat.Jpg)
                    {
                        image.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 0, 100);
                        return(stream);
                    }
                    return(null);
                });
#elif __IOS__
                e.ImageStreamTask = Task.Run(() =>
                {
                    if (e.ImageFormat == SignatureImageFormat.Png)
                    {
                        return(image.AsPNG().AsStream());
                    }
                    if (e.ImageFormat == SignatureImageFormat.Jpg)
                    {
                        return(image.AsJPEG().AsStream());
                    }
                    return(null);
                });
#elif __ANDROID__
                var stream = new MemoryStream();
                var format = e.ImageFormat == SignatureImageFormat.Png ? Bitmap.CompressFormat.Png : Bitmap.CompressFormat.Jpeg;
                e.ImageStreamTask = image
                                    .CompressAsync(format, 100, stream)
                                    .ContinueWith(task =>
                {
                    image.Recycle();
                    image.Dispose();
                    image = null;
                    if (task.Result)
                    {
                        stream.Position = 0;
                        return((Stream)stream);
                    }
                    else
                    {
                        return(null);
                    }
                });
#endif
            }
        }
예제 #32
0
        /// <summary>
        /// Determines if the images at the specified paths are equal.
        /// </summary>
        /// <param name="expected">Path to the expected image.</param>
        /// <param name="actual">Path to the actual image.</param>
        /// <param name="message">The message.</param>
        /// <param name="output">The output difference file.</param>
        public static void AreEqual(string expected, string actual, string message, string output)
        {
            var expectedImage = LoadImage(expected);
            var actualImage = LoadImage(actual);

            if (expectedImage == null)
            {
                EnsureFolder(expected);
                File.Copy(actual, expected);
                Assert.Fail("File not found: {0}", expected);
            }

            if (expectedImage.GetLength(0) != actualImage.GetLength(0))
            {
                Assert.Fail("Expected height: {0}\nActual height:{1}\n{2}", expectedImage.GetLength(0), actualImage.GetLength(0), message);
            }

            if (expectedImage.GetLength(1) != actualImage.GetLength(1))
            {
                Assert.Fail("Expected width: {0}\nActual width:{1}\n{2}", expectedImage.GetLength(1), actualImage.GetLength(1), message);
            }

            var w = expectedImage.GetLength(0);
            var h = expectedImage.GetLength(1);
            var differences = 0;
            var differenceImage = new OxyColor[w, h];
            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    if (!expectedImage[j, i].Equals(actualImage[j, i]))
                    {
                        differences++;
                        differenceImage[j, i] = OxyColors.Red;
                    }
                    else
                    {
                        differenceImage[j, i] = actualImage[j, i].ChangeIntensity(100);
                    }
                }
            }

            if (differences > 0)
            {
                if (output != null)
                {
                    for (int i = 0; i < h; i++)
                    {
                        for (int j = 0; j < w; j++)
                        {
                            if (!expectedImage[j, i].Equals(actualImage[j, i]))
                            {
                            }
                        }
                    }

                    EnsureFolder(output);
                    var encoder = new PngEncoder(new PngEncoderOptions());
                    File.WriteAllBytes(output, encoder.Encode(differenceImage));
                }

                Assert.Fail("Pixel differences: {0}\n{1}", differences, message);
            }
        }