void IImageDecoder.Decode(ExtendedImage image, Stream stream)
        {
            Contract.Requires<ArgumentNullException>(image != null, "Image cannot be null.");
            Contract.Requires<ArgumentNullException>(stream != null, "Stream cannot be null.");

            throw new NotImplementedException();
        }
        /// <summary>
        /// Loads an image from an Url asynchronously
        /// </summary>
        /// <param name="location">The location of the image</param>
        /// <returns>A BitmapImage, that can be set as a source</returns>
        public static async Task<ExtendedImage> LoadImageFromUrlAsync(Uri location)
        {
            WebClient client = new WebClient();
            ExtendedImage image = new ExtendedImage();
            Stream source = await client.OpenReadTaskAsync(location);

            if (location.ToString().EndsWith("gif", StringComparison.InvariantCultureIgnoreCase))
            {
                image.SetSource(source);

                TaskCompletionSource<ExtendedImage> imageLoaded = new TaskCompletionSource<ExtendedImage>();

                EventHandler loadingCompleteHandler = new EventHandler((sender, e) =>
                {
                    imageLoaded.SetResult(image);
                });

                EventHandler<UnhandledExceptionEventArgs> loadingFailedHandler = new EventHandler<UnhandledExceptionEventArgs>((sender, e) =>
                {
                    imageLoaded.SetResult(image);
#if DEBUG
                    if (System.Diagnostics.Debugger.IsAttached)
                        System.Diagnostics.Debugger.Break();
#endif
                });



                image.LoadingCompleted += loadingCompleteHandler;
                image.LoadingFailed += loadingFailedHandler;

                image = await imageLoaded.Task;

                //Remove handlers, otherwise the object might be kept in the memory
                image.LoadingCompleted -= loadingCompleteHandler;
                image.LoadingFailed -= loadingFailedHandler;
            }
            else
            {
                BitmapImage bmp = new BitmapImage();
                bmp.SetSource(source);
                WriteableBitmap writeable = new WriteableBitmap(bmp);
                image = ImageExtensions.ToImage(writeable);
            }

            source.Close();
            return image;
        }
Exemple #3
0
        private void ApplicationBarIconButton_Click_3(object sender, EventArgs e)
        {
            for (int i = 0; i < app.t_num; i++)
            {
                if (photolist.Children.Contains(photo[i]))
                {
                    photolist.Children.Remove(photo[i]);
                }
                if (photolist.Children.Contains(animated_gif[i]))
                {
                    photolist.Children.Remove(animated_gif[i]);
                }
                photo[i].Source = null;
            }
            LayoutRoot.Children.Remove(daomeidan);
            photolist.Children.Remove(btnClickgif);
            dmd_name.Text   = "";
            content.Text    = str2;
            app.t_num       = 0;
            app.row         = -1;
            textBlock1.Text = textBlock2.Text = textBlock3.Text = textBlock4.Text = textBlock5.Text = "";


            if (remember != -1)
            {
                ExtendedImage image = new ExtendedImage();
                image.UriSource = new Uri(gif_arr[remember], UriKind.Relative);
                animated_gif[remember].Source = image;
            }
            remember = -1;
            ((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).IsEnabled = true;
            ((ApplicationBarIconButton)this.ApplicationBar.Buttons[1]).IsEnabled = true;

            ((HyperlinkButton)this.hyperlinkButton1).IsEnabled = true;

            content.Text = tishi_str1;
        }
        /// <summary>
        /// Encodes the data of the specified image and writes the result to
        /// the specified stream.
        /// </summary>
        /// <param name="image">The image, where the data should be get from.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image data should be written to. 
        /// Cannot be null (Nothing in Visual Basic).</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 void Encode(ExtendedImage image, Stream stream)
        {
            Guard.NotNull(image, "image");
            Guard.NotNull(stream, "stream");

            int rowWidth = image.PixelWidth;

            int amount = (image.PixelWidth * 3) % 4; 
            if (amount != 0)
            {
                rowWidth += 4 - amount;
            }

            BinaryWriter writer = new BinaryWriter(stream);

            BmpFileHeader fileHeader = new BmpFileHeader();
            fileHeader.Type = 19778;
            fileHeader.Offset = 54;
            fileHeader.FileSize = 54 + image.PixelHeight * rowWidth * 3;
            Write(writer, fileHeader);

            BmpInfoHeader infoHeader = new BmpInfoHeader();
            infoHeader.HeaderSize = 40;
            infoHeader.Height = image.PixelHeight;
            infoHeader.Width = image.PixelWidth;
            infoHeader.BitsPerPixel = 24;
            infoHeader.Planes = 1;
            infoHeader.Compression = BmpCompression.RGB;
            infoHeader.ImageSize = image.PixelHeight * rowWidth * 3;
            infoHeader.ClrUsed = 0;
            infoHeader.ClrImportant = 0;
            Write(writer, infoHeader);

            WriteImage(writer, image);

            writer.Flush();
        }
        /// <summary>
        /// Decodes the image from the specified stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</param>
        /// <exception cref="System.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 void Decode(ExtendedImage image, Stream stream)
        {
            Guard.NotNull(image, "image");
            Guard.NotNull(stream, "stream");


            FluxCoreJpegDecoder fluxCoreJpegDecoder = new FluxCoreJpegDecoder(stream);

            DecodedJpeg jpg = fluxCoreJpegDecoder.Decode();

            jpg.Image.ChangeColorSpace(ColorSpace.RGB);

            int pixelWidth  = jpg.Image.Width;
            int pixelHeight = jpg.Image.Height;

            byte[] pixels = new byte[pixelWidth * pixelHeight * 4];

            byte[][,] sourcePixels = jpg.Image.Raster;

            for (int y = 0; y < pixelHeight; y++)
            {
                for (int x = 0; x < pixelWidth; x++)
                {
                    int offset = (y * pixelWidth + x) * 4;

                    pixels[offset + 0] = sourcePixels[0][x, y];
                    pixels[offset + 1] = sourcePixels[1][x, y];
                    pixels[offset + 2] = sourcePixels[2][x, y];
                    pixels[offset + 3] = (byte)255;
                }
            }

            image.DensityX = jpg.Image.DensityX;
            image.DensityY = jpg.Image.DensityY;

            image.SetPixels(pixelWidth, pixelHeight, pixels);
        }
Exemple #6
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);
        }
Exemple #7
0
        /// <summary>
        /// Writes to specified image to the stream. The method loops through all encoders and
        /// uses the encoder which supports the extension of the specified file name.
        /// </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>
        /// <param name="fileName">Name of the file.</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, string fileName)
        {
            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.");
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(fileName), "File name cannot be null or empty.");

            string path = Path.GetExtension(fileName);

            if (path == null || string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("The file name is not valid and contains no extension.");
            }

            string pathExtension = path.Substring(1);

            Contract.Assume(!string.IsNullOrEmpty(pathExtension));

            IImageEncoder encoder = null;

            foreach (IImageEncoder availableEncoder in Encoders.GetAvailableEncoders())
            {
                if (availableEncoder != null && availableEncoder.IsSupportedFileExtension(pathExtension))
                {
                    encoder = availableEncoder;
                    break;
                }
            }

            if (encoder == null)
            {
                throw new UnsupportedImageFormatException("Specified file extension is not supported.");
            }

            encoder.Encode(image, stream);
        }
Exemple #8
0
 /// <summary>
 /// Utility method to ensure that all image and source references have been nulled out.
 /// </summary>
 public void Dispose()
 {
     if (_image != null)
     {
         _image.Source = null;
     }
     if (_framerefs != null)
     {
         _framerefs.Clear();
     }
     if (_frames != null)
     {
         _frames.Clear();
     }
     if (Source != null)
     {
         Source.UriSource = null;
         Source           = null;
     }
     if (_animationTimer != null)
     {
         _animationTimer.Stop();
     }
 }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.TryGetValue("imageUri", out imageFileName))
            {
                FilenameText.Text = imageFileName;

                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(imageFileName, System.IO.FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
                {
                    // Allocate an array large enough for the entire file
                    byte[] data = new byte[stream.Length];
                    // Read the entire file and then close it
                    stream.Read(data, 0, data.Length);
                    stream.Close();

                    ExtendedImage image = new ExtendedImage();
                    image.LoadingCompleted +=
                        (o, ea) => Dispatcher.BeginInvoke(() => { AnimatedImage.Source = image; });

                    image.SetSource(new MemoryStream(data));
                }
            }
        }
Exemple #10
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);
        }
Exemple #11
0
        //---------------------------------------------------------------------------------------------------------
        #endregion



        #region Tiles erstellen
        //Tiles erstellem
        //---------------------------------------------------------------------------------------------------------
        void CreateTiles()
        {
            //Erstes Tile erstellen
            WriteableBitmap FirstTile     = new WriteableBitmap(336, 336);
            WriteableBitmap FirstTileIcon = new WriteableBitmap(336, 336);

            // Wenn nicht transparent
            if (TileBackgroundColor != "*" & TileBackgroundColor != null)
            {
                //Hintergrundfarbe einfügen
                FirstTile.Clear(ConvertToSolidColorBrush(TileBackgroundColor, -1).Color);
            }
            //Tile Bild laden
            using (Stream input = Application.GetResourceStream(new Uri("TileMedium.png", UriKind.Relative)).Stream)
            {
                FirstTileIcon.SetSource(input);
            }
            //Bild zusammensetzen
            FirstTile.Blit(new Rect(0, 0, 336, 336), FirstTileIcon, new Rect(0, 0, 336, 336));


            // Bild erstellen
            Grid grid = new Grid
            {
                Width  = 336,
                Height = 336
            };
            Image img = new Image();

            img.Source = FirstTile;
            grid.Children.Add(img);
            // Writeable Bitmap aus Grid erstellen
            WriteableBitmap wbmp = new WriteableBitmap(grid, null);
            // Extended Image aus Writeable Bitmap erstellen
            ExtendedImage extendImage = wbmp.ToImage();

            // Bild speichern
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("Shared/ShellContent/First336.png"))
                {
                    store.DeleteFile("Shared/ShellContent/First336.png");
                }
                using (var stream = store.OpenFile("Shared/ShellContent/First336.png", System.IO.FileMode.OpenOrCreate))
                {
                    extendImage.WriteToStream(stream, "Shared/ShellContent/First336.png");
                }
            }

            //Bild ausgeben
            ImgFirstTile.Source = wbmp;



            //Erstes Tile groß erstellen
            WriteableBitmap FirstTileWidth     = new WriteableBitmap(691, 336);
            WriteableBitmap FirstTileIconWidth = new WriteableBitmap(691, 336);

            // Wenn nicht transparent
            if (TileBackgroundColor != "*" & TileBackgroundColor != null)
            {
                //Hintergrundfarbe einfügen
                FirstTileWidth.Clear(ConvertToSolidColorBrush(TileBackgroundColor, -1).Color);
            }
            //Tile Bild laden
            using (Stream input = Application.GetResourceStream(new Uri("TileLarge.png", UriKind.Relative)).Stream)
            {
                FirstTileIconWidth.SetSource(input);
            }
            //Bild zusammensetzen
            FirstTileWidth.Blit(new Rect(0, 0, 691, 336), FirstTileIconWidth, new Rect(0, 0, 691, 336));


            // Bild erstellen
            Grid gridWidth = new Grid
            {
                Width  = 691,
                Height = 336
            };
            Image imgWidth = new Image();

            imgWidth.Source = FirstTileWidth;
            gridWidth.Children.Add(imgWidth);
            // Writeable Bitmap aus Grid erstellen
            WriteableBitmap wbmpWidth = new WriteableBitmap(gridWidth, null);
            // Extended Image aus Writeable Bitmap erstellen
            ExtendedImage extendImageWidth = wbmpWidth.ToImage();

            // Bild speichern
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("Shared/ShellContent/First691.png"))
                {
                    store.DeleteFile("Shared/ShellContent/First691.png");
                }
                using (var stream = store.OpenFile("Shared/ShellContent/First691.png", System.IO.FileMode.OpenOrCreate))
                {
                    extendImageWidth.WriteToStream(stream, "Shared/ShellContent/First691.png");
                }
            }



            //Zweites Tile erstellen
            WriteableBitmap SecondTile     = new WriteableBitmap(336, 336);
            WriteableBitmap SecondTileIcon = new WriteableBitmap(336, 336);

            //Hintergrundfarbe einfügen
            if (SecondTileBackgroundColor != "*" & SecondTileBackgroundColor != null)
            {
                SecondTile.Clear(ConvertToSolidColorBrush(SecondTileBackgroundColor, -1).Color);
            }

            //Tile Bild laden
            using (Stream input = Application.GetResourceStream(new Uri("SecondTileMedium.png", UriKind.Relative)).Stream)
            {
                SecondTileIcon.SetSource(input);
            }
            //Bild zusammensetzen
            SecondTile.Blit(new Rect(0, 0, 336, 336), SecondTileIcon, new Rect(0, 0, 336, 336));

            // Bild erstellen
            Grid gridSecond = new Grid
            {
                Width  = 336,
                Height = 336
            };
            Image imgSecond = new Image();

            imgSecond.Source = SecondTile;
            gridSecond.Children.Add(imgSecond);
            // Writeable Bitmap aus Grid erstellen
            WriteableBitmap wbmpSecond = new WriteableBitmap(gridSecond, null);
            // Extended Image aus Writeable Bitmap erstellen
            ExtendedImage extendImageSecond = wbmpSecond.ToImage();

            // Bild speichern
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("Shared/ShellContent/Second336.png"))
                {
                    store.DeleteFile("Shared/ShellContent/Second336.png");
                }
                using (var stream = store.OpenFile("Shared/ShellContent/Second336.png", System.IO.FileMode.OpenOrCreate))
                {
                    extendImageSecond.WriteToStream(stream, "Shared/ShellContent/Second336.png");
                }
            }
            // Bild ausgeben
            ImgSecondTile.Source = wbmpSecond;



            //Zweites Tile erstellen
            WriteableBitmap SecondTileWidth     = new WriteableBitmap(691, 336);
            WriteableBitmap SecondTileIconWidth = new WriteableBitmap(691, 336);

            //Hintergrundfarbe einfügen
            if (SecondTileBackgroundColor != "*" & SecondTileBackgroundColor != null)
            {
                SecondTileWidth.Clear(ConvertToSolidColorBrush(SecondTileBackgroundColor, -1).Color);
            }

            //Tile Bild laden
            using (Stream input = Application.GetResourceStream(new Uri("SecondTileLarge.png", UriKind.Relative)).Stream)
            {
                SecondTileIconWidth.SetSource(input);
            }
            //Bild zusammensetzen
            SecondTileWidth.Blit(new Rect(0, 0, 691, 336), SecondTileIconWidth, new Rect(0, 0, 691, 336));
            // Second Tile groß erstellen
            Grid gridSecondWidth = new Grid
            {
                Width  = 691,
                Height = 336
            };
            Image imgSecondWidth = new Image();

            imgSecondWidth.Source = SecondTileWidth;
            gridSecondWidth.Children.Add(imgSecondWidth);
            // Writeable Bitmap aus Grid erstellen
            WriteableBitmap wbmpSecondWidth = new WriteableBitmap(gridSecondWidth, null);
            // Extended Image aus Writeable Bitmap erstellen
            ExtendedImage extendImageSecondWidth = wbmp.ToImage();

            // Bild speichern
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("Shared/ShellContent/Second691.png"))
                {
                    store.DeleteFile("Shared/ShellContent/Second691.png");
                }
                using (var stream = store.OpenFile("Shared/ShellContent/Second691.png", System.IO.FileMode.OpenOrCreate))
                {
                    extendImageSecondWidth.WriteToStream(stream, "Shared/ShellContent/Second691.png");
                }
            }


            //Erstes Tile neu erstellen
            ShellTile    Tile  = ShellTile.ActiveTiles.First();
            FlipTileData First = new FlipTileData();

            First.Title = MyMusicPlayer.Resources.AppResources.Z001_AppTitle;
            First.SmallBackgroundImage = new Uri("isostore:/Shared/ShellContent/First336.png", UriKind.Absolute);
            First.BackgroundImage      = new Uri("isostore:/Shared/ShellContent/First336.png", UriKind.Absolute);
            First.WideBackgroundImage  = new Uri("isostore:/Shared/ShellContent/First691.png", UriKind.Absolute);
            Tile.Update(First);


            //Second Tile neu erstellen
            if (oTile != null && oTile.NavigationUri.ToString().Contains("flip"))
            {
                FlipTileData oFliptile = new FlipTileData();
                oFliptile.Title = Title = "";
                oFliptile.SmallBackgroundImage = new Uri("isostore:/Shared/ShellContent/Second336.png", UriKind.Absolute);
                oFliptile.BackgroundImage      = new Uri("isostore:/Shared/ShellContent/Second336.png", UriKind.Absolute);
                oFliptile.WideBackgroundImage  = new Uri("isostore:/Shared/ShellContent/Second691.png", UriKind.Absolute);
                oTile.Update(oFliptile);
            }
        }
        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
            }
        }
        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)
                    {
                        return((Stream)stream);
                    }
                    else
                    {
                        return(null);
                    }
                });
#elif WINDOWS_UWP
                var stream = new InMemoryRandomAccessStream();
                e.ImageStreamTask = Task.Run <Stream>(() =>
                {
                    BitmapEncoder encoder = null;

                    if (e.ImageFormat == SignatureImageFormat.Png)
                    {
                        encoder = BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream).GetResults();
                        // Get pixels of the WriteableBitmap object
                        Stream pixelStream = image.PixelBuffer.AsStream();
                        byte[] pixels      = new byte[pixelStream.Length];
                        Task.Run(() => pixelStream.ReadAsync(pixels, 0, pixels.Length)).Wait();
                        // Save the image file with jpg extension
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96.0, 96.0, pixels);
                        Task.Run(() => encoder.FlushAsync()).Wait();
                        return(stream.AsStream());
                    }
                    else if (e.ImageFormat == SignatureImageFormat.Jpg)
                    {
                        encoder = BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream).GetResults();
                        // Get pixels of the WriteableBitmap object
                        Stream pixelStream = image.PixelBuffer.AsStream();
                        byte[] pixels      = new byte[pixelStream.Length];
                        Task.Run(() => pixelStream.ReadAsync(pixels, 0, pixels.Length)).Wait();
                        // Save the image file with jpg extension
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, 96.0, 96.0, pixels);
                        Task.Run(() => encoder.FlushAsync()).Wait();
                        return(stream.AsStream());
                    }
                    return(null);
                });
#endif
            }
        }
        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
            }
        }
        /// <summary>
        /// Decodes the image from the specified stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</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 void Decode(ExtendedImage image, Stream stream)
        {
            _image = image;

            _stream = stream;
            _stream.Seek(8, SeekOrigin.Current);

            bool isEndChunckReached = false;
            
            PngChunk currentChunk = null;

            byte[] palette = null;
            byte[] paletteAlpha = null;

            using (MemoryStream dataStream = new MemoryStream())
            {
                while ((currentChunk = ReadChunk()) != null)
                {
                    if (isEndChunckReached)
                    {
                        throw new ImageFormatException("Image does not end with end chunk.");
                    }

                    if (currentChunk.Type == PngChunkTypes.Header)
                    {
                        ReadHeaderChunk(currentChunk.Data);

                        ValidateHeader();
                    }
                    else if (currentChunk.Type == PngChunkTypes.Physical)
                    {
                        ReadPhysicalChunk(currentChunk.Data);
                    }
                    else if (currentChunk.Type == PngChunkTypes.Data)
                    {
                        dataStream.Write(currentChunk.Data, 0, currentChunk.Data.Length);
                    }
                    else if (currentChunk.Type == PngChunkTypes.Palette)
                    {
                        palette = currentChunk.Data;
                    }
                    else if (currentChunk.Type == PngChunkTypes.PaletteAlpha)
                    {
                        paletteAlpha = currentChunk.Data;
                    }
                    else if (currentChunk.Type == PngChunkTypes.Text)
                    {
                        ReadTextChunk(currentChunk.Data);
                    }
                    else if (currentChunk.Type == PngChunkTypes.End)
                    {
                        isEndChunckReached = true;
                    }
                }
                
                byte[] pixels = new byte[_header.Width * _header.Height * 4];

                PngColorTypeInformation colorTypeInformation = _colorTypes[_header.ColorType];

                if (colorTypeInformation != null)
                {
                    IColorReader colorReader = colorTypeInformation.CreateColorReader(palette, paletteAlpha);

                    ReadScanlines(dataStream, pixels, colorReader, colorTypeInformation);
                }

                image.SetPixels(_header.Width, _header.Height, pixels);
            }
        }
Exemple #16
0
 /// <summary>
 /// A simple constructor that initializes the object with the given values.
 /// </summary>
 /// <param name="id">The id of the mod.</param>
 /// <param name="downloadId">The DownloadId of the mod.</param>
 /// <param name="modName">The name of the mod.</param>
 /// <param name="fileName">The filename of the mod?</param>
 /// <param name="humanReadableVersion">The human readable form of the mod's version.</param>
 /// <param name="lastKnownVersion">The last known mod version.</param>
 /// <param name="isEndorsed">The Endorsement state of the mod.</param>
 /// <param name="machineVersion">The version of the mod.</param>
 /// <param name="author">The author of the mod.</param>
 /// <param name="categoryId">The category of the mod.</param>
 /// <param name="customCategoryId">The custom category of the mod.</param>
 /// <param name="description">The description of the mod.</param>
 /// <param name="installDate">The install date of the mod.</param>
 /// <param name="website">The website of the mod.</param>
 /// <param name="screenshot">The mod's screenshot.</param>
 /// <param name="updateWarningEnabled">Whether update warning is enabled for this mod.</param>
 /// <param name="updateChecksEnabled">Whether update checks are enabled for this mod.</param>
 public ModInfo(string id, string downloadId, string modName, string fileName, string humanReadableVersion, string lastKnownVersion, bool?isEndorsed, Version machineVersion, string author, int categoryId, int customCategoryId, string description, string installDate, Uri website, ExtendedImage screenshot, bool updateWarningEnabled, bool updateChecksEnabled)
 {
     SetAllInfo(true, id, downloadId, modName, fileName, humanReadableVersion, lastKnownVersion, isEndorsed, machineVersion, author, categoryId, customCategoryId, description, installDate, website, screenshot, updateWarningEnabled, updateChecksEnabled);
 }
Exemple #17
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;
        }
        /// <summary>
        /// Decodes the image from the specified stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</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 void Decode(ExtendedImage image, Stream stream)
        {
            _image  = image;

            _stream = stream;
            _stream.Seek(6, SeekOrigin.Current);

            ReadLogicalScreenDescriptor();

            if (_logicalScreenDescriptor.GlobalColorTableFlag == true)
            {
                _globalColorTable = new byte[_logicalScreenDescriptor.GlobalColorTableSize * 3];

                // Read the global color table from the stream
                stream.Read(_globalColorTable, 0, _globalColorTable.Length);
            }

            int nextFlag = stream.ReadByte();
            while (nextFlag != 0)
            {
                if (nextFlag == ImageLabel)
                {
                    ReadFrame();
                }
                else if (nextFlag == ExtensionIntroducer)
                {
                    int gcl = stream.ReadByte();
                    switch (gcl)
                    {
                        case GraphicControlLabel:
                            ReadGraphicalControlExtension();
                            break;
                        case CommentLabel:
                            ReadComments();
                            break;
                        case ApplicationExtensionLabel:
                            Skip(12);
                            break;
                        case PlainTextLabel:
                            Skip(13);
                            break;
                    }
                }
                else if (nextFlag == EndIntroducer)
                {
                    break;
                }
                nextFlag = stream.ReadByte();
            }
        }
Exemple #19
0
        public override void LoadFileDialog(FolderLocations folderLocation, int maxWidth, int maxHeight, int x, int y, int width, int height, string[] fileTypes, StreamLoadedCallbackMethod streamLoadedCallback)
        {
            if (streamLoadedCallback == null)
            {
                return;
            }

            // open native dlg
            var file = new OPENFILENAME();

            file.lStructSize = (uint)Marshal.SizeOf(typeof(OPENFILENAME));
            file.hwndOwner   = IntPtr.Zero;
            file.lpstrDefExt = IntPtr.Zero;
            file.lpstrFile   = Marshal.AllocHGlobal((int)MAX_PATH);
            unsafe { ((byte *)file.lpstrFile.ToPointer())[0] = 0; }
            file.nMaxFile        = MAX_PATH;
            file.lpstrFilter     = generateFilterValue(fileTypes);
            file.nFilterIndex    = 0;
            file.lpstrInitialDir = Marshal.StringToHGlobalUni(Application.dataPath);
            file.lpstrTitle      = Marshal.StringToHGlobalUni("Load file");
            file.Flags           = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
            GetOpenFileName(ref file);

            // get native dlg result
            string filename = null;

            if (file.lpstrFile != IntPtr.Zero)
            {
                filename = Marshal.PtrToStringUni(file.lpstrFile);
                Debug.Log("Loading file: " + filename);
            }

            Marshal.FreeHGlobal(file.lpstrFile);
            Marshal.FreeHGlobal(file.lpstrInitialDir);
            Marshal.FreeHGlobal(file.lpstrTitle);
            Marshal.FreeHGlobal(file.lpstrFilter);

            // open file
            if (!string.IsNullOrEmpty(filename))
            {
                if (maxWidth == 0 || maxHeight == 0 || folderLocation != FolderLocations.Pictures)
                {
                    streamLoadedCallback(new FileStream(filename, FileMode.Open, FileAccess.Read), true);
                }
                else
                {
                    var newStream = new MemoryStream();
                    try
                    {
                        using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
                        {
                            ImageTools.IO.IImageDecoder decoder = null;
                            switch (Path.GetExtension(filename).ToLower())
                            {
                            case ".jpg": decoder = new ImageTools.IO.Jpeg.JpegDecoder(); break;

                            case ".jpeg": decoder = new ImageTools.IO.Jpeg.JpegDecoder(); break;

                            case ".png": decoder = new ImageTools.IO.Png.PngDecoder(); break;

                            default:
                                Debug.LogError("Unsuported file ext type: " + Path.GetExtension(filename));
                                streamLoadedCallback(null, false);
                                return;
                            }
                            var image = new ExtendedImage();
                            decoder.Decode(image, stream);
                            var newSize  = Reign.MathUtilities.FitInViewIfLarger(image.PixelWidth, image.PixelHeight, maxWidth, maxHeight);
                            var newImage = ExtendedImage.Resize(image, (int)newSize.x, (int)newSize.y, new NearestNeighborResizer());

                            var encoder = new PngEncoder();
                            encoder.Encode(newImage, newStream);
                            newStream.Position = 0;
                        }
                    }
                    catch (Exception e)
                    {
                        newStream.Dispose();
                        newStream = null;
                        Debug.LogError(e.Message);
                    }
                    finally
                    {
                        streamLoadedCallback(newStream, true);
                    }
                }
            }
            else
            {
                streamLoadedCallback(null, false);
            }
        }
Exemple #20
0
        protected void RptShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ShopConfig shopConfig = SiteConfig.ShopConfig;

            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                goto Label_07BA;
            }
            int     productNum = 0;
            string  str        = "";
            string  str2       = "";
            decimal subTotal   = 0M;

            ((CheckBox)e.Item.FindControl("ChkProductId")).Checked = true;
            ShoppingCartInfo dataItem = e.Item.DataItem as ShoppingCartInfo;

            if (dataItem == null)
            {
                goto Label_07BA;
            }
            productNum = dataItem.Quantity;
            ((TextBox)e.Item.FindControl("TxtProductAmount")).Text = productNum.ToString();
            bool haveWholesalePurview = false;

            if (PEContext.Current.User.PurviewInfo != null)
            {
                haveWholesalePurview = PEContext.Current.User.PurviewInfo.Enablepm;
            }
            str2 = ShoppingCart.GetSaleType(dataItem.ProductInfomation, productNum, haveWholesalePurview);
            str  = ShoppingCart.GetProductType(dataItem.ProductInfomation, productNum, haveWholesalePurview);
            AbstractItemInfo info2 = new ConcreteProductInfo(productNum, dataItem.Property, dataItem.ProductInfomation, PEContext.Current.User.UserInfo, false, false, haveWholesalePurview);

            info2.GetItemInfo();
            subTotal    = info2.SubTotal;
            this.total += subTotal;
            if (!string.IsNullOrEmpty(dataItem.Property))
            {
                ((Literal)e.Item.FindControl("LitProperty")).Text = "(" + info2.Property + ")";
            }
            ProductInfo productById = Product.GetProductById(dataItem.ProductId);

            if (productById.Minimum > 0)
            {
                ((Literal)e.Item.FindControl("LblMark")).Text = "(<font color=\"red\">最低购买量" + productById.Minimum.ToString() + "</font>)";
            }
            InsideStaticLabel label = new InsideStaticLabel();
            string            str3  = "<a href='";

            str3 = (str3 + label.GetInfoPath(info2.ProductId.ToString())) + "' Target='_blank'>" + info2.ProductName + "</a>";
            ((Literal)e.Item.FindControl("LitProductName")).Text = str3;
            ((Literal)e.Item.FindControl("LitProductUnit")).Text = info2.Unit;
            ((Literal)e.Item.FindControl("LitTruePrice")).Text   = info2.Price.ToString("0.00");
            ((Literal)e.Item.FindControl("LitSubTotal")).Text    = subTotal.ToString("0.00");
            ExtendedImage image    = (ExtendedImage)e.Item.FindControl("extendedImage");
            ExtendedImage image2   = (ExtendedImage)e.Item.FindControl("extendedPresentImage");
            Control       control  = e.Item.FindControl("ProductImage");
            Control       control2 = e.Item.FindControl("presentImage");

            if (!shopConfig.IsGwcShowProducdtThumb)
            {
                image.Visible    = false;
                control.Visible  = false;
                control2.Visible = false;
            }
            else
            {
                if (!string.IsNullOrEmpty(dataItem.ProductInfomation.ProductThumb))
                {
                    image.Src = dataItem.ProductInfomation.ProductThumb;
                }
                else
                {
                    image.Src = SiteConfig.SiteInfo.VirtualPath + "Images/nopic.gif";
                }
                image.ImageHeight = shopConfig.GwcThumbsHeight;
                image.ImageWidth  = shopConfig.GwcThumbsWidth;
                if (dataItem.ProductInfomation.PresentId > 0)
                {
                    PresentInfo presentById = Present.GetPresentById(dataItem.ProductInfomation.PresentId);
                    if (!string.IsNullOrEmpty(presentById.PresentThumb))
                    {
                        image2.Src = presentById.PresentThumb;
                    }
                    else
                    {
                        image2.Src = SiteConfig.SiteInfo.VirtualPath + "Images/nopic.gif";
                    }
                    image2.ImageHeight = shopConfig.GwcThumbsHeight;
                    image2.ImageWidth  = shopConfig.GwcThumbsWidth;
                }
            }
            if (!shopConfig.IsShowGwcProductType)
            {
                e.Item.FindControl("tdProductType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitProductType")).Text = str;
            }
            if (!shopConfig.IsShowGwcSaleType)
            {
                e.Item.FindControl("tdSaleType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitSaleType")).Text = str2;
            }
            if (!shopConfig.IsShowGwcMarkPrice)
            {
                e.Item.FindControl("tdMarkPrice").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPriceMarket")).Text = info2.PriceMarket.ToString("0.00");
            }
            if (((dataItem.ProductInfomation.SalePromotionType <= 0) || (productNum < dataItem.ProductInfomation.MinNumber)) || dataItem.IsPresent)
            {
                goto Label_07BA;
            }
            e.Item.FindControl("PresentInfomation").Visible = true;
            string           str4      = "";
            string           str5      = "";
            string           str6      = "";
            int              productId = 0;
            AbstractItemInfo info5     = new ConcreteSalePromotionType(productNum, dataItem.ProductInfomation, false, null);

            info5.GetItemInfo();
            switch (dataItem.ProductInfomation.SalePromotionType)
            {
            case 1:
            case 3:
                str5      = "<font color=red>(赠品)</font>";
                str4      = "赠送礼品";
                str6      = "赠送";
                productId = info5.Id;
                goto Label_05B2;

            case 2:
            case 4:
                if (info5.Price <= 0M)
                {
                    str5 = "<font color=red>(赠送赠品)</font>";
                    str6 = "赠送";
                    break;
                }
                str5 = "<font color=red>(换购赠品)</font>";
                str6 = "换购";
                break;

            default:
                goto Label_05B2;
            }
            str4      = "促销礼品";
            productId = info5.Id;
Label_05B2:
            ((HiddenField)e.Item.FindControl("HdnPresentId")).Value   = productId.ToString();
            ((Literal)e.Item.FindControl("LitPresentName")).Text      = info5.ProductName + str5;
            ((Literal)e.Item.FindControl("LitPresentUnit")).Text      = info5.Unit;
            ((Literal)e.Item.FindControl("LitPresentNum")).Text       = info5.Amount.ToString();
            ((Literal)e.Item.FindControl("LitPresentTruePrice")).Text = info5.Price.ToString("0.00");
            ((Literal)e.Item.FindControl("LitPresentSubtotal")).Text  = info5.SubTotal.ToString("0.00");
            if (this.PresentExist(this.cartId, productId))
            {
                ((CheckBox)e.Item.FindControl("ChkPresentId")).Checked = true;
                this.total += info5.SubTotal;
            }
            if (!shopConfig.IsShowGwcProductType)
            {
                e.Item.FindControl("tdPresentType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPresentType")).Text = str4;
            }
            if (!shopConfig.IsShowGwcSaleType)
            {
                e.Item.FindControl("tdPresentSaleType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPresentSaleType")).Text = str6;
            }
            if (!shopConfig.IsShowGwcMarkPrice)
            {
                e.Item.FindControl("tdPresentMarkPrice").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPresentPriceMarket")).Text = info5.PriceMarket.ToString("0.00");
            }
Label_07BA:
            if (e.Item.ItemType == ListItemType.Header)
            {
                Control control9  = e.Item.FindControl("ProductImageTitle");
                Control control10 = e.Item.FindControl("tdProductTypeTitle");
                Control control11 = e.Item.FindControl("tdSaleTypeTitle");
                Control control12 = e.Item.FindControl("tdMarkPriceTitle");
                if (!shopConfig.IsGwcShowProducdtThumb)
                {
                    control9.Visible = false;
                }
                if (!shopConfig.IsShowGwcProductType)
                {
                    control10.Visible = false;
                }
                if (!shopConfig.IsShowGwcSaleType)
                {
                    control11.Visible = false;
                }
                if (!shopConfig.IsShowGwcMarkPrice)
                {
                    control12.Visible = false;
                }
            }
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Control control13 = e.Item.FindControl("footerTdThemeImage");
                Control control14 = e.Item.FindControl("footerTdProductType");
                Control control15 = e.Item.FindControl("footerTdSaleType");
                Control control16 = e.Item.FindControl("footerTdMarkPrice");
                if (!shopConfig.IsGwcShowProducdtThumb)
                {
                    control13.Visible = false;
                }
                if (!shopConfig.IsShowGwcProductType)
                {
                    control14.Visible = false;
                }
                if (!shopConfig.IsShowGwcSaleType)
                {
                    control15.Visible = false;
                }
                if (!shopConfig.IsShowGwcMarkPrice)
                {
                    control16.Visible = false;
                }
            }
        }
Exemple #21
0
        protected void RptShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ShopConfig shopConfig = SiteConfig.ShopConfig;
            bool       isPaymentShowProducdtThumb = true;
            int        paymentThumbsWidth         = 0;
            int        paymentThumbsHeight        = 0;
            bool       isShowPaymentProductType   = true;
            bool       isShowPaymentSaleType      = true;
            bool       isShowPaymentMarkPrice     = true;

            if (this.IsPreview == 0)
            {
                isPaymentShowProducdtThumb = shopConfig.IsPaymentShowProducdtThumb;
                isShowPaymentProductType   = shopConfig.IsShowPaymentProductType;
                isShowPaymentSaleType      = shopConfig.IsShowPaymentSaleType;
                isShowPaymentMarkPrice     = shopConfig.IsShowPaymentMarkPrice;
                paymentThumbsWidth         = shopConfig.PaymentThumbsWidth;
                paymentThumbsHeight        = shopConfig.PaymentThumbsHeight;
            }
            else if (this.IsPreview == 1)
            {
                isPaymentShowProducdtThumb = shopConfig.IsPreviewShowProducdtThumb;
                isShowPaymentProductType   = shopConfig.IsShowPreviewProductType;
                isShowPaymentSaleType      = shopConfig.IsShowPreviewSaleType;
                isShowPaymentMarkPrice     = shopConfig.IsShowPreviewMarkPrice;
                paymentThumbsWidth         = shopConfig.PreviewThumbsWidth;
                paymentThumbsHeight        = shopConfig.PreviewThumbsHeight;
            }
            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                if (e.Item.ItemType == ListItemType.Footer)
                {
                    PresentProjectInfo presentProInfo = new PresentProjectInfo(true);
                    if (this.m_IsPreview != 3)
                    {
                        presentProInfo            = PresentProject.GetPresentProjectByTotalMoney(this.total);
                        this.presentExpInfomation = this.ShowPresentExp(presentProInfo).ToString();
                    }
                    if (this.m_IsPreview == 1)
                    {
                        int         presentId = DataConverter.CLng(this.PresentId);
                        PlaceHolder holder    = (PlaceHolder)e.Item.FindControl("PlhPresentInfo");
                        holder.Visible = false;
                        if (((presentId > 0) && !presentProInfo.IsNull) && (presentProInfo.PresentContent.Contains("1") && (presentId > 0)))
                        {
                            holder.Visible = true;
                            AbstractItemInfo info7 = new ConcretePresentProject(presentId, presentProInfo);
                            info7.GetItemInfo();
                            Label label2 = (Label)e.Item.FindControl("LblProductName");
                            Label label3 = (Label)e.Item.FindControl("LblUnit");
                            Label label4 = (Label)e.Item.FindControl("LblPresentPriceMarket");
                            Label label5 = (Label)e.Item.FindControl("LblPresentPrice");
                            Label label6 = (Label)e.Item.FindControl("LblPresentPrice1");
                            label2.Text  = info7.ProductName;
                            label3.Text  = info7.Unit;
                            label4.Text  = info7.PriceMarket.ToString("0.00");
                            label5.Text  = info7.Price.ToString("0.00");
                            label6.Text  = info7.Price.ToString("0.00");
                            this.weight += info7.TotalWeight;
                            this.total  += info7.Price;
                        }
                        ((PlaceHolder)e.Item.FindControl("PlhMoneyInfo")).Visible = true;
                        Label       label7  = (Label)e.Item.FindControl("LblDeliverCharge");
                        Label       label8  = (Label)e.Item.FindControl("LblTaxRate");
                        Label       label9  = (Label)e.Item.FindControl("LblIncludeTax");
                        Label       label10 = (Label)e.Item.FindControl("LblCoupon");
                        Label       label11 = (Label)e.Item.FindControl("LblTotalMoney");
                        Label       label12 = (Label)e.Item.FindControl("LblTrueTotalMoney");
                        PackageInfo packageByGoodsWeight = Package.GetPackageByGoodsWeight(this.weight);
                        if (!packageByGoodsWeight.IsNull)
                        {
                            this.weight += packageByGoodsWeight.PackageWeight;
                        }
                        decimal         num7            = DeliverCharge.GetDeliverCharge(this.m_DeliverType, this.weight, this.m_ZipCode, this.total, this.m_NeedInvoice);
                        DeliverTypeInfo deliverTypeById = EasyOne.Shop.DeliverType.GetDeliverTypeById(this.m_DeliverType);
                        label7.Text = num7.ToString("0.00");
                        label8.Text = deliverTypeById.TaxRate.ToString();
                        if ((deliverTypeById.IncludeTax == TaxRateType.IncludeTaxNoInvoiceFavourable) || (deliverTypeById.IncludeTax == TaxRateType.IncludeTaxNoInvoiceNoFavourable))
                        {
                            label9.Text = "是";
                        }
                        else
                        {
                            label9.Text = "否";
                        }
                        decimal num8 = this.total + num7;
                        if (this.m_CouponMoney > 0M)
                        {
                            label10.Visible = true;
                            decimal num9 = this.total - this.m_CouponMoney;
                            if (num9 < 0M)
                            {
                                num9 = 0M;
                            }
                            num8         = num9 + num7;
                            label10.Text = "使用优惠券,面值为:" + this.m_CouponMoney.ToString("0.00") + "元,商品实际价格为:" + num9.ToString("0.00") + "元 <br>";
                            label11.Text = num9.ToString("0.00") + "+" + num7.ToString("0.00") + "=" + num8.ToString("0.00") + "元";
                            label12.Text = num8.ToString("0.00");
                        }
                        else
                        {
                            label10.Visible = false;
                            label11.Text    = this.total.ToString("0.00") + "+" + num7.ToString("0.00") + "=" + num8.ToString("0.00") + "元";
                            label12.Text    = num8.ToString("0.00");
                        }
                        this.ViewState["TrueTotalMoney"] = num8;
                    }
                    else
                    {
                        ((PlaceHolder)e.Item.FindControl("PlhMoneyInfo")).Visible = false;
                    }
                    ExtendedImage image3    = (ExtendedImage)e.Item.FindControl("presentImage");
                    Control       control9  = e.Item.FindControl("footerPresentImage");
                    Control       control10 = e.Item.FindControl("footerTdThemeImage");
                    Control       control11 = e.Item.FindControl("footerTdProductType");
                    Control       control12 = e.Item.FindControl("footerTdSaleType");
                    Control       control13 = e.Item.FindControl("footerTdMarkPrice");
                    Control       control14 = e.Item.FindControl("footerTdThemeImage");
                    Control       control15 = e.Item.FindControl("footerTdMoneyInfoSaleType");
                    Control       control16 = e.Item.FindControl("footerTdMoneyInfoMarkPrice");
                    Control       control17 = e.Item.FindControl("footerPresentType");
                    Control       control18 = e.Item.FindControl("footerPresentSaleType");
                    Control       control19 = e.Item.FindControl("footerPresentMarkPrice");
                    if (!isPaymentShowProducdtThumb)
                    {
                        control10.Visible = false;
                        control9.Visible  = false;
                    }
                    else
                    {
                        PresentInfo presentById = Present.GetPresentById(DataConverter.CLng(this.PresentId));
                        if (!string.IsNullOrEmpty(presentById.PresentThumb))
                        {
                            image3.Src = presentById.PresentThumb;
                        }
                        else
                        {
                            image3.Src = SiteConfig.SiteInfo.VirtualPath + "Images/nopic.gif";
                        }
                        image3.Width  = paymentThumbsWidth;
                        image3.Height = paymentThumbsHeight;
                    }
                    if (!isShowPaymentProductType)
                    {
                        control11.Visible = false;
                        control14.Visible = false;
                        control17.Visible = false;
                    }
                    if (!isShowPaymentSaleType)
                    {
                        control12.Visible = false;
                        control15.Visible = false;
                        control18.Visible = false;
                    }
                    if (!isShowPaymentMarkPrice)
                    {
                        control13.Visible = false;
                        control16.Visible = false;
                        control19.Visible = false;
                        return;
                    }
                }
                else if (e.Item.ItemType == ListItemType.Header)
                {
                    Control control20 = e.Item.FindControl("ProductImageTitle");
                    Control control21 = e.Item.FindControl("tdProductTypeTitle");
                    Control control22 = e.Item.FindControl("tdSaleTypeTitle");
                    Control control23 = e.Item.FindControl("tdMarkPriceTitle");
                    if (!isPaymentShowProducdtThumb)
                    {
                        control20.Visible = false;
                    }
                    if (!isShowPaymentProductType)
                    {
                        control21.Visible = false;
                    }
                    if (!isShowPaymentSaleType)
                    {
                        control22.Visible = false;
                    }
                    if (!isShowPaymentMarkPrice)
                    {
                        control23.Visible = false;
                    }
                }
                return;
            }
            int              productNum = 0;
            string           str        = "";
            string           str2       = "";
            decimal          subTotal   = 0M;
            ShoppingCartInfo dataItem   = (ShoppingCartInfo)e.Item.DataItem;

            if (dataItem == null)
            {
                return;
            }
            productNum = dataItem.Quantity;
            bool haveWholesalePurview = Convert.ToBoolean(this.ViewState["HaveWholesalePurview"]);

            str2 = ShoppingCart.GetSaleType(dataItem.ProductInfomation, productNum, haveWholesalePurview);
            str  = ShoppingCart.GetProductType(dataItem.ProductInfomation, productNum, haveWholesalePurview);
            AbstractItemInfo info2 = new ConcreteProductInfo(productNum, dataItem.Property, dataItem.ProductInfomation, this.m_UserInfo, false, false, haveWholesalePurview);

            info2.GetItemInfo();
            subTotal         = info2.SubTotal;
            this.total      += subTotal;
            this.totalExp   += dataItem.ProductInfomation.PresentExp * productNum;
            this.totalMoney += dataItem.ProductInfomation.PresentMoney * productNum;
            this.totalPoint += dataItem.ProductInfomation.PresentPoint * productNum;
            this.weight     += info2.TotalWeight;
            if (!string.IsNullOrEmpty(dataItem.Property))
            {
                ((Literal)e.Item.FindControl("LitProperty")).Text = "(" + info2.Property + ")";
            }
            InsideStaticLabel label = new InsideStaticLabel();
            string            str3  = "<a href='";

            str3 = (str3 + label.GetInfoPath(info2.ProductId.ToString())) + "' Target='_blank'>" + info2.ProductName + "</a>";
            ((Literal)e.Item.FindControl("LitProductName")).Text = str3;
            ((Literal)e.Item.FindControl("LitProductUnit")).Text = info2.Unit;
            ((Literal)e.Item.FindControl("LitTruePrice")).Text   = info2.Price.ToString("0.00");
            ((Literal)e.Item.FindControl("LitSubTotal")).Text    = subTotal.ToString("0.00");
            ExtendedImage image    = (ExtendedImage)e.Item.FindControl("extendedImage");
            ExtendedImage image2   = (ExtendedImage)e.Item.FindControl("extendedPresentImage");
            Control       control  = e.Item.FindControl("ProductImage");
            Control       control2 = e.Item.FindControl("presentImage");

            if (!isPaymentShowProducdtThumb)
            {
                image.Visible    = false;
                control.Visible  = false;
                control2.Visible = false;
            }
            else
            {
                if (!string.IsNullOrEmpty(dataItem.ProductInfomation.ProductThumb))
                {
                    image.Src = dataItem.ProductInfomation.ProductThumb;
                }
                else
                {
                    image.Src = SiteConfig.SiteInfo.VirtualPath + "Images/nopic.gif";
                }
                image.ImageHeight = paymentThumbsHeight;
                image.ImageWidth  = paymentThumbsWidth;
                if (dataItem.ProductInfomation.PresentId > 0)
                {
                    PresentInfo info3 = Present.GetPresentById(dataItem.ProductInfomation.PresentId);
                    if (!string.IsNullOrEmpty(info3.PresentThumb))
                    {
                        image2.Src = info3.PresentThumb;
                    }
                    else
                    {
                        image2.Src = SiteConfig.SiteInfo.VirtualPath + "Images/nopic.gif";
                    }
                    image2.ImageHeight = paymentThumbsHeight;
                    image2.ImageWidth  = paymentThumbsWidth;
                }
            }
            if (!isShowPaymentProductType)
            {
                e.Item.FindControl("tdProductType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitProductType")).Text = str;
            }
            if (!isShowPaymentSaleType)
            {
                e.Item.FindControl("tdSaleType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitSaleType")).Text = str2;
            }
            if (!isShowPaymentMarkPrice)
            {
                e.Item.FindControl("tdMarkPrice").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPriceMarket")).Text = info2.PriceMarket.ToString("0.00");
            }
            int         num5        = Order.CountBuyNum(PEContext.Current.User.UserName, dataItem.ProductId);
            ProductInfo productById = Product.GetProductById(dataItem.ProductId);

            if ((productById.LimitNum > 0) && ((dataItem.Quantity + num5) > productById.LimitNum))
            {
                BaseUserControl.WriteErrMsg(string.Concat(new object[] { "您订购了", num5, productById.Unit, productById.ProductName, ",曾经购买了", num5, productById.Unit, ",而此商品每人限购数量为", productById.LimitNum, productById.Unit, ",请重新调整您的购物车!" }), "ShoppingCart.aspx");
            }
            if ((dataItem.ProductInfomation.SalePromotionType <= 0) || (productNum < dataItem.ProductInfomation.MinNumber))
            {
                return;
            }
            e.Item.FindControl("PresentInfomation").Visible = true;
            string           str4  = "";
            string           str5  = "";
            string           str6  = "";
            AbstractItemInfo info5 = new ConcreteSalePromotionType(productNum, dataItem.ProductInfomation, false, null);

            info5.GetItemInfo();
            switch (dataItem.ProductInfomation.SalePromotionType)
            {
            case 1:
            case 3:
                str5 = "<font color=red>(赠品)</font>";
                str4 = "赠送礼品";
                str6 = "赠送";
                goto Label_06A1;

            case 2:
            case 4:
                if (info5.Price <= 0M)
                {
                    str5 = "<font color=red>(赠送赠品)</font>";
                    str6 = "赠送";
                    break;
                }
                str5 = "<font color=red>(换购赠品)</font>";
                str6 = "换购";
                break;

            default:
                goto Label_06A1;
            }
            str4 = "促销礼品";
Label_06A1:
            if (this.PresentExist(this.m_CartId, info5.Id))
            {
                ((HiddenField)e.Item.FindControl("HdnPresentId")).Value = info5.Id.ToString();
                ExtendedLiteral literal = (ExtendedLiteral)e.Item.FindControl("LitPresentName");
                literal.Text   = info5.ProductName;
                literal.EndTag = str5;
                ((Literal)e.Item.FindControl("LitPresentUnit")).Text      = info5.Unit;
                ((Literal)e.Item.FindControl("LitPresentNum")).Text       = info5.Amount.ToString();
                ((Literal)e.Item.FindControl("LitPresentTruePrice")).Text = info5.Price.ToString("0.00");
                ((Literal)e.Item.FindControl("LitPresentSubtotal")).Text  = info5.SubTotal.ToString("0.00");
                this.total  += info5.SubTotal;
                this.weight += info5.TotalWeight;
            }
            if (!isShowPaymentProductType)
            {
                e.Item.FindControl("tdPresentType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPresentType")).Text = str4;
            }
            if (!isShowPaymentSaleType)
            {
                e.Item.FindControl("tdPresentSaleType").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPresentSaleType")).Text = str6;
            }
            if (!isShowPaymentMarkPrice)
            {
                e.Item.FindControl("tdPresentMarkPrice").Visible = false;
            }
            else
            {
                ((Literal)e.Item.FindControl("LitPresentPriceOriginal")).Text = info5.PriceMarket.ToString("0.00");
            }
        }
Exemple #22
0
        protected void RptPresentList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ShopConfig shopConfig = SiteConfig.ShopConfig;
            bool       isPaymentShowProducdtThumb = true;
            int        paymentThumbsWidth         = 0;
            int        paymentThumbsHeight        = 0;
            bool       isShowPaymentProductType   = true;
            bool       isShowPaymentSaleType      = true;
            bool       isShowPaymentMarkPrice     = true;

            if (this.IsPreview == 0)
            {
                isPaymentShowProducdtThumb = shopConfig.IsPaymentShowProducdtThumb;
                isShowPaymentProductType   = shopConfig.IsShowPaymentProductType;
                isShowPaymentSaleType      = shopConfig.IsShowPaymentSaleType;
                isShowPaymentMarkPrice     = shopConfig.IsShowPaymentMarkPrice;
                paymentThumbsWidth         = shopConfig.PaymentThumbsWidth;
                paymentThumbsHeight        = shopConfig.PaymentThumbsHeight;
            }
            else if (this.IsPreview == 1)
            {
                isPaymentShowProducdtThumb = shopConfig.IsPreviewShowProducdtThumb;
                isShowPaymentProductType   = shopConfig.IsShowPreviewProductType;
                isShowPaymentSaleType      = shopConfig.IsShowPreviewSaleType;
                isShowPaymentMarkPrice     = shopConfig.IsShowPreviewMarkPrice;
                paymentThumbsWidth         = shopConfig.PreviewThumbsWidth;
                paymentThumbsHeight        = shopConfig.PreviewThumbsHeight;
            }
            if ((e.Item.ItemType == ListItemType.AlternatingItem) || (e.Item.ItemType == ListItemType.Item))
            {
                PresentInfo dataItem = (PresentInfo)e.Item.DataItem;
                ((Literal)e.Item.FindControl("LitChangePresentPriceMarket")).Text = dataItem.PriceMarket.ToString("0.00");
                ((Literal)e.Item.FindControl("LitChangePresentTruePrice")).Text   = this.LblPrice.Text;
                ((Literal)e.Item.FindControl("LitChangePresentSubTotal")).Text    = this.LblPrice.Text;
                Control control  = e.Item.FindControl("changePresentImage");
                Control control2 = e.Item.FindControl("changePresentType");
                Control control3 = e.Item.FindControl("changeSaleType");
                Control control4 = e.Item.FindControl("changeMarkPrice");
                if (!isPaymentShowProducdtThumb)
                {
                    control.Visible = false;
                }
                else
                {
                    ExtendedImage image = (ExtendedImage)e.Item.FindControl("changePresentListImage");
                    if (!string.IsNullOrEmpty(dataItem.PresentThumb))
                    {
                        image.Src = dataItem.PresentThumb;
                    }
                    else
                    {
                        image.Src = SiteConfig.SiteInfo.VirtualPath + "Images/nopic.gif";
                    }
                    image.Width  = paymentThumbsWidth;
                    image.Height = paymentThumbsHeight;
                }
                if (!isShowPaymentProductType)
                {
                    control2.Visible = false;
                }
                if (!isShowPaymentSaleType)
                {
                    control3.Visible = false;
                }
                if (!isShowPaymentMarkPrice)
                {
                    control4.Visible = false;
                }
            }
            if (e.Item.ItemType == ListItemType.Header)
            {
                Control control5 = e.Item.FindControl("changePresentHeaderImage");
                Control control6 = e.Item.FindControl("changePresentHeaderProductType");
                Control control7 = e.Item.FindControl("changePresentHeaderSaleType");
                Control control8 = e.Item.FindControl("changePresentHeaderMarkPrice");
                if (!isPaymentShowProducdtThumb)
                {
                    control5.Visible = false;
                }
                if (!isShowPaymentProductType)
                {
                    control6.Visible = false;
                }
                if (!isShowPaymentSaleType)
                {
                    control7.Visible = false;
                }
                if (!isShowPaymentMarkPrice)
                {
                    control8.Visible = false;
                }
            }
        }
Exemple #23
0
        /// <summary>
        /// Encodes the data of the specified image and writes the result to
        /// the specified stream.
        /// </summary>
        /// <param name="image">The image, where the data should be get from.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image data should be written to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <exception cref="System.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 void Encode(ExtendedImage image, Stream stream)
        {
            Guard.NotNull(image, "image");
            Guard.NotNull(stream, "stream");
            
            const int bands = 3;

            int pixelWidth  = image.PixelWidth;
            int pixelHeight = image.PixelHeight;

            byte[] sourcePixels = image.Pixels;

            byte[][,] pixels = new byte[bands][,];

            for (int b = 0; b < bands; b++)
            {
                pixels[b] = new byte[pixelWidth, pixelHeight];
            }

            for (int y = 0; y < pixelHeight; y++)
            {
                for (int x = 0; x < pixelWidth; x++)
                {
                    int offset = (y * pixelWidth + x) * 4;

                    float a = (float)sourcePixels[offset + 3] / 255.0f;

                    pixels[0][x, y] = (byte)(sourcePixels[offset + 0] * a + (1 - a) * _transparentColor.R);
                    pixels[1][x, y] = (byte)(sourcePixels[offset + 1] * a + (1 - a) * _transparentColor.G);
                    pixels[2][x, y] = (byte)(sourcePixels[offset + 2] * a + (1 - a) * _transparentColor.B);
                }
            }

            Image newImage = new Image(new ColorModel { ColorSpace = ColorSpace.RGB, Opaque = false }, pixels);

            if (image.DensityXInt32 > 0 && image.DensityYInt32 > 0)
            {
                newImage.DensityX = image.DensityXInt32;
                newImage.DensityY = image.DensityYInt32;
            }

            // Create a jpg image from the image object.
            DecodedJpeg jpg = new DecodedJpeg(newImage);

            // Create a new encoder and start encoding.
            FluxCoreJpegEncoder fluxCoreJpegEncoder = new FluxCoreJpegEncoder(jpg, _quality, stream);
            fluxCoreJpegEncoder.Encode();
        }
Exemple #24
0
        /// <summary>
        /// Encodes the data of the specified image and writes the result to
        /// the specified stream.
        /// </summary>
        /// <param name="image">The image, where the data should be get from.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image data should be written to.
        /// Cannot be null (Nothing in Visual Basic).</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 void Encode(ExtendedImage image, Stream stream)
        {
            Guard.NotNull(image, "image");
            Guard.NotNull(stream, "stream");

            _image = image;

            _stream = stream;

            // Write the png header.
            stream.Write(
                new byte[] 
                { 
                    0x89, 0x50, 0x4E, 0x47, 
                    0x0D, 0x0A, 0x1A, 0x0A 
                }, 0, 8);

            PngHeader header = new PngHeader();
            header.Width = image.PixelWidth;
            header.Height = image.PixelHeight;
            header.ColorType = 6;
            header.BitDepth = 8;
            header.FilterMethod = 0;
            header.CompressionMethod = 0;
            header.InterlaceMethod = 0;

            WriteHeaderChunk(header);

            WritePhysicsChunk();
            WriteGammaChunk();

            if (IsWritingUncompressed)
            {
                WriteDataChunksFast();
            }
            else
            {
                WriteDataChunks();
            }
            WriteEndChunk();

            stream.Flush();
        }
Exemple #25
0
        /// <summary>
        /// Decodes the image from the specified _stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The _stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</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 void Decode(ExtendedImage image, Stream stream)
        {
            _stream = stream;

            try
            {
                ReadFileHeader();
                ReadInfoHeader();

                int colorMapSize = -1;

                if (_infoHeader.ClrUsed == 0)
                {
                    if (_infoHeader.BitsPerPixel == 1 ||
                        _infoHeader.BitsPerPixel == 4 ||
                        _infoHeader.BitsPerPixel == 8)
                    {
                        colorMapSize = (int)Math.Pow(2, _infoHeader.BitsPerPixel) * 4;
                    }
                }
                else
                {
                    colorMapSize = _infoHeader.ClrUsed * 4;
                }

                byte[] palette = null;

                if (colorMapSize > 0)
                {
                    palette = new byte[colorMapSize];

                    _stream.Read(palette, 0, colorMapSize);
                }

                byte[] imageData = new byte[_infoHeader.Width * _infoHeader.Height * 4];

                switch (_infoHeader.Compression)
                {
                case BmpCompression.RGB:
                    if (_infoHeader.HeaderSize != 40)
                    {
                        throw new ImageFormatException(
                                  string.Format(CultureInfo.CurrentCulture,
                                                "Header Size value '{0}' is not valid.", _infoHeader.HeaderSize));
                    }

                    if (_infoHeader.BitsPerPixel == 32)
                    {
                        ReadRgb32(imageData, _infoHeader.Width, _infoHeader.Height);
                    }
                    else if (_infoHeader.BitsPerPixel == 24)
                    {
                        ReadRgb24(imageData, _infoHeader.Width, _infoHeader.Height);
                    }
                    else if (_infoHeader.BitsPerPixel == 16)
                    {
                        ReadRgb16(imageData, _infoHeader.Width, _infoHeader.Height);
                    }
                    else if (_infoHeader.BitsPerPixel <= 8)
                    {
                        ReadRgbPalette(imageData, palette,
                                       _infoHeader.Width,
                                       _infoHeader.Height,
                                       _infoHeader.BitsPerPixel);
                    }
                    break;

                default:
                    throw new NotSupportedException("Does not support this kind of bitmap files.");
                }

                image.SetPixels(_infoHeader.Width, _infoHeader.Height, imageData);
            }
            catch (IndexOutOfRangeException e)
            {
                throw new ImageFormatException("Bitmap does not have a valid format.", e);
            }
        }
Exemple #26
0
 /// <summary>
 /// Sets all of the properties of the object.
 /// </summary>
 /// <param name="p_booOverwriteAllValues">Whether to overwrite the current info values,
 /// or just the empty ones.</param>
 /// <param name="p_strId">The id of the mod.</param>
 /// <param name="p_strDownloadId">The DownloadId of the mod.</param>
 /// <param name="p_strModName">The name of the mod.</param>
 /// <param name="p_strHumanReadableVersion">The human readable form of the mod's version.</param>
 /// <param name="p_strLastKnownVersion">The last known mod version.</param>
 /// <param name="p_booIsEndorsed">The Endorsement state of the mod.</param>
 /// <param name="p_verMachineVersion">The version of the mod.</param>
 /// <param name="p_strAuthor">The author of the mod.</param>
 /// <param name="p_strCategoryId">The category of the mod.</param>
 /// <param name="p_strCustomCategoryId">The custom category of the mod.</param>
 /// <param name="p_strDescription">The description of the mod.</param>
 /// <param name="p_strInstallDate">The install date of the mod.</param>
 /// <param name="p_uriWebsite">The website of the mod.</param>
 /// <param name="p_eimScreenshot">The mod's screenshot.</param>
 protected void SetAllInfo(bool p_booOverwriteAllValues, string p_strId, string p_strDownloadId, string p_strModName, string p_strFileName, string p_strHumanReadableVersion, string p_strLastKnownVersion, bool?p_booIsEndorsed, Version p_verMachineVersion, string p_strAuthor, Int32 p_intCategoryId, Int32 p_intCustomCategoryId, string p_strDescription, string p_strInstallDate, Uri p_uriWebsite, ExtendedImage p_eimScreenshot)
 {
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(Id))
     {
         Id = p_strId;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(DownloadId))
     {
         DownloadId = p_strDownloadId;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(ModName))
     {
         ModName = p_strModName;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(FileName))
     {
         FileName = p_strFileName;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(HumanReadableVersion))
     {
         HumanReadableVersion = p_strHumanReadableVersion;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(LastKnownVersion))
     {
         LastKnownVersion = p_strLastKnownVersion;
     }
     if (p_booOverwriteAllValues || (IsEndorsed != p_booIsEndorsed))
     {
         IsEndorsed = p_booIsEndorsed;
     }
     if (p_booOverwriteAllValues || (MachineVersion == null))
     {
         MachineVersion = p_verMachineVersion;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(Author))
     {
         Author = p_strAuthor;
     }
     if (p_booOverwriteAllValues || (CategoryId != p_intCategoryId))
     {
         CategoryId = p_intCategoryId;
     }
     if (p_booOverwriteAllValues || (CustomCategoryId != p_intCustomCategoryId))
     {
         CustomCategoryId = p_intCustomCategoryId;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(Description))
     {
         Description = p_strDescription;
     }
     if (p_booOverwriteAllValues || String.IsNullOrEmpty(InstallDate))
     {
         InstallDate = p_strInstallDate;
     }
     if (p_booOverwriteAllValues || (Website == null))
     {
         Website = p_uriWebsite;
     }
     if (p_booOverwriteAllValues || (Screenshot == null))
     {
         Screenshot = p_eimScreenshot;
     }
 }
Exemple #27
0
        /// <summary>
        /// Sets all of the properties of the object.
        /// </summary>
        /// <param name="overwriteAllValues">Whether to overwrite the current info values,
        /// or just the empty ones.</param>
        /// <param name="id">The id of the mod.</param>
        /// <param name="downloadId">The DownloadId of the mod.</param>
        /// <param name="modName">The name of the mod.</param>
        /// <param name="fileName">The filename of the mod?</param>
        /// <param name="humanReadableVersion">The human readable form of the mod's version.</param>
        /// <param name="lastKnownVersion">The last known mod version.</param>
        /// <param name="isEndorsed">The Endorsement state of the mod.</param>
        /// <param name="machineVersion">The version of the mod.</param>
        /// <param name="author">The author of the mod.</param>
        /// <param name="categoryId">The category of the mod.</param>
        /// <param name="customCategoryId">The custom category of the mod.</param>
        /// <param name="description">The description of the mod.</param>
        /// <param name="installDate">The install date of the mod.</param>
        /// <param name="website">The website of the mod.</param>
        /// <param name="screenshot">The mod's screenshot.</param>
        /// <param name="updateWarningEnabled">Whether update warning is enabled for this mod.</param>
        /// <param name="updateChecksEnabled">Whether update checks are enabled for this mod.</param>
        protected void SetAllInfo(bool overwriteAllValues, string id, string downloadId, string modName, string fileName, string humanReadableVersion, string lastKnownVersion, bool?isEndorsed, Version machineVersion, string author, int categoryId, int customCategoryId, string description, string installDate, Uri website, ExtendedImage screenshot, bool updateWarningEnabled, bool updateChecksEnabled)
        {
            if (overwriteAllValues || string.IsNullOrEmpty(Id))
            {
                Id = id;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(DownloadId))
            {
                DownloadId = downloadId;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(ModName))
            {
                ModName = modName;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(FileName))
            {
                FileName = fileName;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(HumanReadableVersion))
            {
                HumanReadableVersion = humanReadableVersion;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(LastKnownVersion))
            {
                LastKnownVersion = lastKnownVersion;
            }

            if (overwriteAllValues || (IsEndorsed != isEndorsed))
            {
                IsEndorsed = isEndorsed;
            }

            if (overwriteAllValues || (MachineVersion == null))
            {
                MachineVersion = machineVersion;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(Author))
            {
                Author = author;
            }

            if (overwriteAllValues || (CategoryId != categoryId))
            {
                CategoryId = categoryId;
            }

            if (overwriteAllValues || (CustomCategoryId != customCategoryId))
            {
                CustomCategoryId = customCategoryId;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(Description))
            {
                Description = description;
            }

            if (overwriteAllValues || string.IsNullOrEmpty(InstallDate))
            {
                InstallDate = installDate;
            }

            if (overwriteAllValues || (Website == null))
            {
                Website = website;
            }

            if (overwriteAllValues || (UpdateWarningEnabled != updateWarningEnabled))
            {
                UpdateWarningEnabled = updateWarningEnabled;
            }

            if (overwriteAllValues || (UpdateChecksEnabled != updateChecksEnabled))
            {
                UpdateChecksEnabled = updateChecksEnabled;
            }
        }
Exemple #28
0
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            content.Text = tishi_str1;

            Decoders.AddDecoder <GifDecoder>();

            dmdgif.UriSource = new Uri(dmd_gif1, UriKind.Relative);


            for (int i = 0; i < 5; i++)
            {
                //////////
                photo[i] = new Image();
                string img = string.Format(@"<Image  
                                xmlns='http://schemas.microsoft.com/client/2007'
                                xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                                Height='95' Width='95' Stretch='Fill' 
                                Grid.Column='{0}' Grid.Row='{1}'>
                                <Image.Clip>
                                <RectangleGeometry  Rect='0, 0, 95, 95' RadiusX='20' RadiusY='20'/>
                                </Image.Clip>
                                </Image>", col, i * 2 + 1);

                Image bmp = XamlReader.Load(img) as Image;

                photo[i] = bmp;
                //////////////
                animated_gif[i] = new AnimatedImage();

                string        gif1         = string.Format(@"<it:AnimatedImage Name='igif'
                                xmlns='http://schemas.microsoft.com/client/2007'
                                xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                                xmlns:it='clr-namespace:ImageTools.Controls;assembly=ImageTools.Controls'
                                Height='95' Width='95' Stretch='Fill' 
                                Grid.Column= '1' Grid.Row='{0}'/>
                                ", i * 2 + 1);
                AnimatedImage animated_GIF = XamlReader.Load(gif1) as AnimatedImage;
                ExtendedImage image        = new ExtendedImage();
                image.UriSource     = new Uri(gif_arr[i], UriKind.Relative);
                animated_GIF.Source = image;
                animated_gif[i]     = animated_GIF;
                ////////////
            }
            if (app.RRF_head_picture != null && app.RRF_navigate_name != null)
            {
                ++app.t_num;
                app.row += 2;
                BitmapImage rec = new BitmapImage();
                rec.UriSource = new Uri(app.RRF_head_picture, UriKind.Absolute);
                app.all_name[app.t_num - 1]  = app.RRF_navigate_name;
                app.RRF_head_picture         = null;
                app.RRF_navigate_name        = null;
                app.SavingImage[app.row / 2] = rec;

                for (int q = 0; q < app.t_num; q++)
                {
                    photo[q].Source = app.SavingImage[q];
                    photolist.Children.Add(photo[q]);
                    switch (q)
                    {
                    case 0: textBlock1.Text = app.all_name[0]; break;

                    case 1: textBlock2.Text = app.all_name[1]; break;

                    case 2: textBlock3.Text = app.all_name[2]; break;

                    case 3: textBlock4.Text = app.all_name[3]; break;

                    case 4: textBlock5.Text = app.all_name[4]; break;
                    }
                }
            }

            if (app.row == 9 && col == 1)
            {
                ((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).IsEnabled = false;
                ((ApplicationBarIconButton)this.ApplicationBar.Buttons[1]).IsEnabled = false;
            }
        }
Exemple #29
0
        /// <summary>
        /// Decodes the image from the specified stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</param>
        /// <exception cref="System.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 void Decode(ExtendedImage image, Stream stream)
        {
            Guard.NotNull(image, "image");
            Guard.NotNull(stream, "stream");

            if (UseLegacyLibrary)
            {
                FluxCoreJpegDecoder fluxCoreJpegDecoder = new FluxCoreJpegDecoder(stream);

                DecodedJpeg jpg = fluxCoreJpegDecoder.Decode();

                jpg.Image.ChangeColorSpace(ColorSpace.RGB);

                int pixelWidth  = jpg.Image.Width;
                int pixelHeight = jpg.Image.Height;

                byte[] pixels = new byte[pixelWidth * pixelHeight * 4];

                byte[][,] sourcePixels = jpg.Image.Raster;

                for (int y = 0; y < pixelHeight; y++)
                {
                    for (int x = 0; x < pixelWidth; x++)
                    {
                        int offset = (y * pixelWidth + x) * 4;

                        pixels[offset + 0] = sourcePixels[0][x, y];
                        pixels[offset + 1] = sourcePixels[1][x, y];
                        pixels[offset + 2] = sourcePixels[2][x, y];
                        pixels[offset + 3] = (byte)255;
                    }
                }

                //-------
                image.DensityXInt32 = jpg.Image.DensityX;
                image.DensityYInt32 = jpg.Image.DensityY;
                image.SetPixels(pixelWidth, pixelHeight, pixels);
            }
            else
            {
                JpegImage jpg = new JpegImage(stream);

                int pixelWidth  = jpg.Width;
                int pixelHeight = jpg.Height;

                byte[] pixels = new byte[pixelWidth * pixelHeight * 4];

                if (!(jpg.Colorspace == Colorspace.RGB && jpg.BitsPerComponent == 8))
                {
                    throw new UnsupportedImageFormatException();
                }

                for (int y = 0; y < pixelHeight; y++)
                {
                    SampleRow row = jpg.GetRow(y);
                    for (int x = 0; x < pixelWidth; x++)
                    {
                        //Sample sample = row.GetAt(x);
                        int offset = (y * pixelWidth + x) * 4;
                        row.GetComponentsAt(x, out pixels[offset + 0], out pixels[offset + 1], out pixels[offset + 2]);
                        //r = (byte)sample[0];
                        //g = (byte)sample[1];
                        //b = (byte)sample[2];
                        //pixels[offset + 0] = r;
                        //pixels[offset + 1] = g;
                        //pixels[offset + 2] = b;
                        pixels[offset + 3] = (byte)255;
                    }
                }

                image.SetPixels(pixelWidth, pixelHeight, pixels);
            }
        }
Exemple #30
0
        /// <summary>
        /// Loads an image asynchronously. If the image is already cached, it will be loaded from the cache. Otherwise it will be added to the cache
        /// </summary>
        /// <param name="url">An absolute URI pointing to the image</param>
        /// <returns>A Bitmap with the image</returns>
        public async static Task<ExtendedImage> LoadCachedImageFromUrlAsync(Uri url)
        {
            try
            {
                using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string file = Path.Combine(CacheFolder, getCachenameFromUri(url));

                    if (cacheContainsUri(url))
                    {
                        ExtendedImage cachedImage = new ExtendedImage();
                        using (IsolatedStorageFileStream cachedFile = storage.OpenFile(file, FileMode.Open, FileAccess.Read))
                        {
                            BitmapImage image = new BitmapImage();
                            image.SetSource(cachedFile);

                            WriteableBitmap tmp = new WriteableBitmap(image);
                            cachedImage = tmp.ToImage();

#if DEBUG
                            App.logger.log("Loaded image {0} from cached file {1}", url, file);
#endif
                            return cachedImage;
                        }
                    }
                    else
                    {
                        ExtendedImage loadedImage = await Helpers.LoadImageFromUrlAsync(url);

                        //GIF files don't support saving with imagetools
                        if (!url.ToString().EndsWith("gif", StringComparison.InvariantCultureIgnoreCase))
                            saveImageToCache(loadedImage, file, storage);

                        return loadedImage;
                    }
                }
            }
            catch (Exception e)
            {
                if (e is IOException)
                {
#if DEBUG
                    App.logger.log("Error loading from cache: {0}", url);
#endif
                }
#if DEBUG
                throw;
#endif
                return null;
            }
        }
Exemple #31
0
        /// <summary>
        /// Decodes the image from the specified stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</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 void Decode(ExtendedImage image, Stream stream)
        {
            _image = image;

            _stream = stream;
            _stream.Seek(8, SeekOrigin.Current);

            bool isEndChunckReached = false;

            PngChunk currentChunk = null;

            byte[] palette      = null;
            byte[] paletteAlpha = null;

            using (MemoryStream dataStream = new MemoryStream())
            {
                while ((currentChunk = ReadChunk()) != null)
                {
                    if (isEndChunckReached)
                    {
                        throw new ImageFormatException("Image does not end with end chunk.");
                    }

                    if (currentChunk.Type == PngChunkTypes.Header)
                    {
                        ReadHeaderChunk(currentChunk.Data);

                        ValidateHeader();
                    }
                    else if (currentChunk.Type == PngChunkTypes.Physical)
                    {
                        ReadPhysicalChunk(currentChunk.Data);
                    }
                    else if (currentChunk.Type == PngChunkTypes.Data)
                    {
                        dataStream.Write(currentChunk.Data, 0, currentChunk.Data.Length);
                    }
                    else if (currentChunk.Type == PngChunkTypes.Palette)
                    {
                        palette = currentChunk.Data;
                    }
                    else if (currentChunk.Type == PngChunkTypes.PaletteAlpha)
                    {
                        paletteAlpha = currentChunk.Data;
                    }
                    else if (currentChunk.Type == PngChunkTypes.Text)
                    {
                        ReadTextChunk(currentChunk.Data);
                    }
                    else if (currentChunk.Type == PngChunkTypes.End)
                    {
                        isEndChunckReached = true;
                    }
                }

                byte[] pixels = new byte[_header.Width * _header.Height * 4];

                PngColorTypeInformation colorTypeInformation = _colorTypes[_header.ColorType];

                if (colorTypeInformation != null)
                {
                    IColorReader colorReader = colorTypeInformation.CreateColorReader(palette, paletteAlpha);

                    ReadScanlines(dataStream, pixels, colorReader, colorTypeInformation);
                }

                image.SetPixels(_header.Width, _header.Height, pixels);
            }
        }
Exemple #32
0
        /// <summary>
        /// Decodes the image from the specified stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</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 void Decode(ExtendedImage image, Stream stream)
        {
            try
            {
                _image = image;

                _stream = stream;
                _stream.Seek(6, SeekOrigin.Current);

                ReadLogicalScreenDescriptor();

                if (_logicalScreenDescriptor.GlobalColorTableFlag == true)
                {
                    _globalColorTable = new byte[_logicalScreenDescriptor.GlobalColorTableSize * 3];

                    // Read the global color table from the stream
                    stream.Read(_globalColorTable, 0, _globalColorTable.Length);
                }

                int nextFlag = stream.ReadByte();
                while (nextFlag != -1)
                {
                    if (nextFlag == ImageLabel)
                    {
                        ReadFrame();
                    }
                    else if (nextFlag == ExtensionIntroducer)
                    {
                        int gcl = stream.ReadByte();
                        switch (gcl)
                        {
                        case GraphicControlLabel:
                            ReadGraphicalControlExtension();
                            break;

                        case CommentLabel:
                            ReadComments();
                            break;

                        case ApplicationExtensionLabel:
                            Skip(12);
                            break;

                        case PlainTextLabel:
                            Skip(13);
                            break;
                        }
                    }
                    else if (nextFlag == EndIntroducer)
                    {
                        break;
                    }
                    nextFlag = stream.ReadByte();
                }
            }
            catch (Exception e)
            {
                this._currentFrame     = null;
                this._globalColorTable = null;
                this._graphicsControl  = null;
                if (this._image != null)
                {
                    this._image.UriSource = null;
                }
                this._image = null;
                this._logicalScreenDescriptor = null;
                this._stream = null;

                throw new Exception("Gif failed to decode");
            }
        }
        private static void WriteImage(BinaryWriter writer, ExtendedImage image)
        {
            int amount = (image.PixelWidth * 3) % 4, offset = 0;
            if (amount != 0)
            {
                amount = 4 - amount;
            }

            byte[] data = image.Pixels;

            for (int y = image.PixelHeight - 1; y >= 0; y--)
            {
                for (int x = 0; x < image.PixelWidth; x++)
                {
                    offset = (y * image.PixelWidth + x) * 4;

                    writer.Write(data[offset + 2]);
                    writer.Write(data[offset + 1]);
                    writer.Write(data[offset + 0]);
                }

                for (int i = 0; i < amount; i++)
                {
                    writer.Write((byte)0);
                }
            }
        }
Exemple #34
0
        // 이미지 로딩 부분 UI 스레드에서 이루어짐
        private async Task LoadImageAsync(ListBox panel, Grid grid, Picture pic)
        {
            // Status를 위한 텍스트 블럭 삽입
            var status = new TextBlock();

            try
            {
                status.Text = "[이미지를 불러오는 중..]";
                grid.Children.Add(status);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HttpUtility.HtmlDecode(pic.Uri));
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
                request.Method    = "GET";

                // 빈 스트링인 경우 요청이 예외가 난다
                if (pic.Referer != string.Empty)
                {
                    request.Headers["Referer"] = pic.Referer;
                }
                request.CookieContainer = WebClientEx.CookieContainer;

                HttpWebResponse response = (HttpWebResponse)await Task <WebResponse> .Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);

                MemoryStream stream = new MemoryStream((int)response.ContentLength);
                await response.GetResponseStream().CopyToAsync(stream);

                stream.Seek(0, SeekOrigin.Begin);

                if (response.ContentType.Equals("image/gif", StringComparison.CurrentCultureIgnoreCase))
                {
                    // grid의 위치를 알아내고
                    int i = panel.Items.IndexOf(grid) + 1;

                    ExtendedImage source = new ExtendedImage();
                    source.SetSource(stream);

                    var image = new AnimatedImage();
                    image.Source         = source;
                    image.Tap           += image_Tap;
                    image.Tag            = pic;
                    image.LoadingFailed += (o, e) =>
                    {
                        var tb = new TextBlock();
                        tb.Text       = "로딩 실패";
                        tb.Foreground = new SolidColorBrush(Colors.Red);
                        grid.Children.Add(tb);
                    };
                    panel.Items.Insert(i, image);
                }

                // 이상하게도 PictureDecoder.DecodeJpeg이 png까지 디코딩을 할 수가 있어서.. 그냥 쓰고 있다
                else if (response.ContentType.Equals("image/jpg", StringComparison.CurrentCultureIgnoreCase) ||
                         response.ContentType.Equals("image/jpeg", StringComparison.CurrentCultureIgnoreCase) ||
                         response.ContentType.Equals("image/png", StringComparison.CurrentCultureIgnoreCase))
                {
                    // 큰 이미지를 잘게 나눈다
                    var wbmps = await Task.Factory.StartNew(() => LoadImage(stream));

                    // grid의 위치를 알아내고
                    int i = panel.Items.IndexOf(grid) + 1;
                    foreach (var wbmp in wbmps)
                    {
                        var image = new Image();
                        image.Source = wbmp;
                        image.Tag    = pic;
                        image.Tap   += image_Tap;
                        panel.Items.Insert(i, image);
                        i++;
                    }
                    // panel.Items.RemoveAt(i);
                }
                else
                {
                    var source = new BitmapImage();
                    source.SetSource(stream);

                    int i = panel.Items.IndexOf(grid) + 1;

                    var image = new Image();
                    image.Source = source;
                    image.Tag    = pic;
                    image.Tap   += image_Tap;
                    panel.Items.Insert(i, image);
                }

                grid.Children.Clear();
            }
            catch
            {
                status.Text = "[이미지 불러오기 실패]";
            }
        }
Exemple #35
0
 /// <summary>
 /// A simple constructor that initializes the object with the given values.
 /// </summary>
 /// <param name="p_strId">The id of the mod.</param>
 /// <param name="p_strDownloadId">The DownloadId of the mod.</param>
 /// <param name="p_strModName">The name of the mod.</param>
 /// <param name="p_strFileName">The name of the mod.</param>
 /// <param name="p_strHumanReadableVersion">The human readable form of the mod's version.</param>
 /// <param name="p_strLastKnownVersion">The last known mod version.</param>
 /// <param name="p_booIsEndorsed">The Endorsement state of the mod.</param>
 /// <param name="p_verMachineVersion">The version of the mod.</param>
 /// <param name="p_strAuthor">The author of the mod.</param>
 /// <param name="p_strCategoryId">The category of the mod.</param>
 /// <param name="p_strCustomCategoryId">The custom category of the mod.</param>
 /// <param name="p_strDescription">The description of the mod.</param>
 /// <param name="p_strInstallDate">The install date of the mod.</param>
 /// <param name="p_uriWebsite">The website of the mod.</param>
 /// <param name="p_eimScreenshot">The mod's screenshot.</param>
 public ModInfo(string p_strId, string p_strDownloadId, string p_strModName, string p_strFileName, string p_strHumanReadableVersion, string p_strLastKnownVersion, bool?p_booIsEndorsed, Version p_verMachineVersion, string p_strAuthor, Int32 p_intCategoryId, Int32 p_intCustomCategoryId, string p_strDescription, string p_strInstallDate, Uri p_uriWebsite, ExtendedImage p_eimScreenshot)
 {
     SetAllInfo(true, p_strId, p_strDownloadId, p_strModName, p_strFileName, p_strHumanReadableVersion, p_strLastKnownVersion, p_booIsEndorsed, p_verMachineVersion, p_strAuthor, p_intCategoryId, p_intCustomCategoryId, p_strDescription, p_strInstallDate, p_uriWebsite, p_eimScreenshot);
 }
        /// <summary>
        /// Decodes the image from the specified _stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The _stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</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 void Decode(ExtendedImage image, Stream stream)
        {
            _stream = stream;

            try
            {
                ReadFileHeader();
                ReadInfoHeader();

                int colorMapSize = -1;

                if (_infoHeader.ClrUsed == 0)
                {
                    if (_infoHeader.BitsPerPixel == 1 ||
                        _infoHeader.BitsPerPixel == 4 ||
                        _infoHeader.BitsPerPixel == 8)
                    {
                        colorMapSize = (int)Math.Pow(2, _infoHeader.BitsPerPixel) * 4;
                    }
                }
                else
                {
                    colorMapSize = _infoHeader.ClrUsed * 4;
                }

                byte[] palette = null;

                if (colorMapSize > 0)
                {
                    palette = new byte[colorMapSize];

                    _stream.Read(palette, 0, colorMapSize);
                }

                byte[] imageData = new byte[_infoHeader.Width * _infoHeader.Height * 4];

                switch (_infoHeader.Compression)
                {
                    case BmpCompression.RGB:
                        if (_infoHeader.HeaderSize != 40)
                        {
                            throw new ImageFormatException(
                                string.Format(CultureInfo.CurrentCulture,
                                    "Header Size value '{0}' is not valid.", _infoHeader.HeaderSize));
                        }

                        if (_infoHeader.BitsPerPixel == 32)
                        {
                            ReadRgb32(imageData, _infoHeader.Width, _infoHeader.Height);
                        }
                        else if (_infoHeader.BitsPerPixel == 24)
                        {
                            ReadRgb24(imageData, _infoHeader.Width, _infoHeader.Height);
                        }
                        else if (_infoHeader.BitsPerPixel == 16)
                        {
                            ReadRgb16(imageData, _infoHeader.Width, _infoHeader.Height);
                        }
                        else if (_infoHeader.BitsPerPixel <= 8)
                        {
                            ReadRgbPalette(imageData, palette,
                                _infoHeader.Width,
                                _infoHeader.Height,
                                _infoHeader.BitsPerPixel);
                        }
                        break;
                    default:
                        throw new NotSupportedException("Does not support this kind of bitmap files.");
                }

                image.SetPixels(_infoHeader.Width, _infoHeader.Height, imageData);
            }
            catch (IndexOutOfRangeException e)
            {
                throw new ImageFormatException("Bitmap does not have a valid format.", e);
            }
        }
Exemple #37
0
        /// <summary>
        /// Decodes the image from the specified stream and sets the data to image.
        /// </summary>
        /// <param name="Image">The image, where the data should be set to. Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="Stream">The stream, where the image should be decoded from. Cannot be null (Nothing in Visual Basic).</param>
        public void Decode(ExtendedImage Image, Stream Stream)
        {
            // Initialize the input.
            byte[] Input = Stream is MemoryStream ? ((MemoryStream)Stream).ToArray() : null;
            // Initialize a new instance of the NanoJPEG class.
            NanoJPEG NanoJPEG = new NanoJPEG();

            // Check if the input is invalid.
            if (Input == null)
            {
                // Initialize a new instance of the MemoryStream class.
                using (MemoryStream MemoryStream = new MemoryStream()) {
                    // Initialize the buffer.
                    byte[] Buffer = new byte[16 * 1024];
                    // Initialize the number of bytes read.
                    int Read;
                    // Read bytes and check if reading was successful.
                    while ((Read = Stream.Read(Buffer, 0, Buffer.Length)) > 0)
                    {
                        // Write the read bytes.
                        MemoryStream.Write(Buffer, 0, Read);
                    }
                    // Set the input.
                    Input = MemoryStream.ToArray();
                }
            }
            // Decode the image.
            if (NanoJPEG.njDecode(Input) == nj_result_t.NJ_OK)
            {
                // Initialize the status indicating color.
                bool IsColor = NanoJPEG.njIsColor();
                // Initialize the RGB-formatted image..
                byte[] Output = NanoJPEG.njGetImage();
                // Initialzie the iterator.
                int i = Output.Length - 3, Height = NanoJPEG.njGetHeight(), Width = NanoJPEG.njGetWidth();
                // Initialize NanoJPEG to dispose of copies.
                NanoJPEG.njInit();
                // Check if the image has color.
                if (IsColor)
                {
                    // Resize the RGB-formatted image to accommendate RGBA-formatting.
                    Array.Resize(ref Output, Output.Length * 4 / 3);
                    // Iterate through each pixel in the RGB-formatting.
                    for (int j = Output.Length - 4; i >= 0; i -= 3, j -= 4)
                    {
                        // Change the pixel from RGB-formatting to RGBA-formatting.
                        Buffer.BlockCopy(Output, i, Output, j, 3);
                        // Set the alpha channel for the pixel.
                        Output[j + 3] = 0;
                    }
                }
                else
                {
                    // Resize the Grayscale image to accommendate RGBA-formatting.
                    Array.Resize(ref Output, Output.Length * 4);
                    // Iterate through each pixel in the RGB-formatting.
                    for (int j = Output.Length - 4; i >= 0; i -= 3, j -= 4)
                    {
                        // Change the pixel from Grayscale to RGBA-formatting.
                        Output[j] = Output[j + 1] = Output[j + 2] = Output[i];
                        // Set the alpha channel for the pixel.
                        Output[j + 3] = 0;
                    }
                }
                // Return the RGBA-formatted image.
                Image.SetPixels(Width, Height, Output);
            }
        }
Exemple #38
0
        public BarcodeResult ReadBarcode(ExtendedImage image)
        {
            byte[] array = new byte[image.PixelWidth * image.PixelHeight * 3];

            byte[] pixels = image.Pixels;

            for (int y = 0; y < image.PixelHeight; y++)
            {
                for (int x = 0; x < image.PixelWidth; x++)
                {
                    int offset = y * image.PixelWidth + x;

                    array[offset * 3 + 0] = pixels[offset * 4 + 0];
                    array[offset * 3 + 1] = pixels[offset * 4 + 1];
                    array[offset * 3 + 2] = pixels[offset * 4 + 2];
                }
            }

            BarcodeResult barcodeResult = null;

            try
            {
                RGBLuminanceSource source = new RGBLuminanceSource(array, image.PixelWidth, image.PixelHeight);

                BinaryBitmap bitmap = null;
                switch (_binarizerMode)
                {
                case BinarizerMode.Hybrid:
                    bitmap = new BinaryBitmap(new HybridBinarizer(source));
                    break;

                case BinarizerMode.Histogram:
                    bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
                    break;

                default:
                    break;
                }

                Result result = _reader.decode(bitmap, _hints);

                barcodeResult      = new BarcodeResult();
                barcodeResult.Text = result.Text;

                if (result.RawBytes != null)
                {
                    foreach (sbyte item in result.RawBytes)
                    {
                        barcodeResult.RawBytes.Add(item);
                    }
                }

                if (result.ResultPoints != null)
                {
                    foreach (ResultPoint point in result.ResultPoints)
                    {
                        barcodeResult.Points.Add(new Point(point.X, point.Y));
                    }
                }

                if (result.BarcodeFormat == BarcodeFormat.CODE_128)
                {
                    barcodeResult.Format = BarcodeResultFormat.Code128;
                }
                else if (result.BarcodeFormat == BarcodeFormat.CODE_39)
                {
                    barcodeResult.Format = BarcodeResultFormat.Code39;
                }
                else if (result.BarcodeFormat == BarcodeFormat.DATAMATRIX)
                {
                    barcodeResult.Format = BarcodeResultFormat.DateMatrix;
                }
                else if (result.BarcodeFormat == BarcodeFormat.EAN_13)
                {
                    barcodeResult.Format = BarcodeResultFormat.Ean13;
                }
                else if (result.BarcodeFormat == BarcodeFormat.EAN_8)
                {
                    barcodeResult.Format = BarcodeResultFormat.Ean8;
                }
                else if (result.BarcodeFormat == BarcodeFormat.ITF)
                {
                    barcodeResult.Format = BarcodeResultFormat.Itf;
                }
                else if (result.BarcodeFormat == BarcodeFormat.PDF417)
                {
                    barcodeResult.Format = BarcodeResultFormat.Pdf417;
                }
                else if (result.BarcodeFormat == BarcodeFormat.QR_CODE)
                {
                    barcodeResult.Format = BarcodeResultFormat.QrCode;
                }
                else if (result.BarcodeFormat == BarcodeFormat.UPC_A)
                {
                    barcodeResult.Format = BarcodeResultFormat.UpcA;
                }
                else if (result.BarcodeFormat == BarcodeFormat.UPC_E)
                {
                    barcodeResult.Format = BarcodeResultFormat.UpcE;
                }
                else
                {
                    barcodeResult.Format = BarcodeResultFormat.Unknown;
                }
            }
            catch (ReaderException)
            {
            }

            return(barcodeResult);
        }
Exemple #39
0
        /// <summary>
        /// Decodes the image from the specified stream and sets
        /// the data to image.
        /// </summary>
        /// <param name="image">The image, where the data should be set to.
        /// Cannot be null (Nothing in Visual Basic).</param>
        /// <param name="stream">The stream, where the image should be
        /// decoded from. Cannot be null (Nothing in Visual Basic).</param>
        /// <exception cref="System.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 void Decode(ExtendedImage image, Stream stream)
        {
            Guard.NotNull(image, "image");
            Guard.NotNull(stream, "stream");

            if (UseLegacyLibrary)
            {
                FluxCoreJpegDecoder fluxCoreJpegDecoder = new FluxCoreJpegDecoder(stream);

                DecodedJpeg jpg = fluxCoreJpegDecoder.Decode();

                jpg.Image.ChangeColorSpace(ColorSpace.RGB);

                int pixelWidth = jpg.Image.Width;
                int pixelHeight = jpg.Image.Height;

                byte[] pixels = new byte[pixelWidth * pixelHeight * 4];

                byte[][,] sourcePixels = jpg.Image.Raster;

                for (int y = 0; y < pixelHeight; y++)
                {
                    for (int x = 0; x < pixelWidth; x++)
                    {
                        int offset = (y * pixelWidth + x) * 4;

                        pixels[offset + 0] = sourcePixels[0][x, y];
                        pixels[offset + 1] = sourcePixels[1][x, y];
                        pixels[offset + 2] = sourcePixels[2][x, y];
                        pixels[offset + 3] = (byte)255;

                    }
                }

                //-------

                //
                image.DensityXInt32 = jpg.Image.DensityX;
                image.DensityYInt32 = jpg.Image.DensityY;

                image.SetPixels(pixelWidth, pixelHeight, pixels);
            }
            else
            {
                JpegImage jpg = new JpegImage(stream);

                int pixelWidth = jpg.Width;
                int pixelHeight = jpg.Height;

                byte[] pixels = new byte[pixelWidth * pixelHeight * 4];

                if (!(jpg.Colorspace == Colorspace.RGB && jpg.BitsPerComponent == 8))
                {
                    throw new UnsupportedImageFormatException();
                }

                for (int y = 0; y < pixelHeight; y++)
                {
                    SampleRow row = jpg.GetRow(y);
                    for (int x = 0; x < pixelWidth; x++)
                    {
                        //Sample sample = row.GetAt(x);
                        int offset = (y * pixelWidth + x) * 4;
                        row.GetComponentsAt(x, out pixels[offset + 0], out pixels[offset + 1], out pixels[offset + 2]);
                        //r = (byte)sample[0];
                        //g = (byte)sample[1];
                        //b = (byte)sample[2];  
                        //pixels[offset + 0] = r;
                        //pixels[offset + 1] = g;
                        //pixels[offset + 2] = b;
                        pixels[offset + 3] = (byte)255;
                    }
                }

                image.SetPixels(pixelWidth, pixelHeight, pixels);
            }
        }
        public void Execute()
        {
            try
            {
                var m = new ServiceManager <GetImageCompletedEventArgs>(delegate(BodyArchitectAccessServiceClient client1, EventHandler <GetImageCompletedEventArgs> operationCompleted)
                {
                    using (OperationContextScope ocs = new OperationContextScope(client1.InnerChannel))
                    {
                        OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("SessionId", "http://MYBASERVICE.TK/", ApplicationState.Current.SessionData.Token.SessionId));
                        OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("PictureId", "http://MYBASERVICE.TK/", picture.PictureIdk__BackingField));
                        OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("Hash", "http://MYBASERVICE.TK/", picture.Hashk__BackingField));
                        ApplicationState.AddCustomHeaders();
                        client1.GetImageCompleted -= operationCompleted;
                        client1.GetImageCompleted += operationCompleted;
                        client1.GetImageAsync();
                    }
                });
                m.OperationCompleted += (s, a) =>
                {
                    if (a.Error != null)
                    {
                        PictureCacheItem item = new PictureCacheItem(null, picture.PictureIdk__BackingField, picture.Hashk__BackingField);
                        PicturesCache.Instance.AddToCache(item);
                        PicturesCache.Instance.Notify(new PictureInfoDTO()
                        {
                            PictureIdk__BackingField = picture.PictureIdk__BackingField, Hashk__BackingField = picture.Hashk__BackingField
                        });
                    }
                    else if (a.Result != null)
                    {
                        MemoryStream  stream = new MemoryStream(a.Result.Result);
                        ExtendedImage desert = new ExtendedImage();
                        desert.SetSource(stream);
                        desert.LoadingFailed += delegate(object sender, UnhandledExceptionEventArgs e)
                        {
                            PictureCacheItem item = new PictureCacheItem(null, picture.PictureIdk__BackingField, picture.Hashk__BackingField);
                            PicturesCache.Instance.AddToCache(item);
                            PicturesCache.Instance.Notify(new PictureInfoDTO()
                            {
                                PictureIdk__BackingField = picture.PictureIdk__BackingField, Hashk__BackingField = picture.Hashk__BackingField
                            });
                        };
                        desert.LoadingCompleted += delegate
                        {
                            ApplicationState.SynchronizationContext.Post(delegate
                            {
                                var image             = desert.ToBitmap();
                                PictureCacheItem item = new PictureCacheItem(image, picture.PictureIdk__BackingField, picture.Hashk__BackingField);
                                PicturesCache.Instance.AddToCache(item);
                                PicturesCache.Instance.Notify(picture);
                                //if (OperationCompleted != null)
                                //{
                                //    OperationCompleted(this, EventArgs.Empty);
                                //}
                            }, null);
                        };
                    }
                };

                m.Run();
            }
            catch (Exception)
            {
                PictureCacheItem item = new PictureCacheItem(null, picture.PictureIdk__BackingField, picture.Hashk__BackingField);
                PicturesCache.Instance.AddToCache(item);
                PicturesCache.Instance.Notify(new PictureInfoDTO()
                {
                    PictureIdk__BackingField = picture.PictureIdk__BackingField, Hashk__BackingField = picture.Hashk__BackingField
                });
            }
        }
Exemple #41
0
        private static void saveImageToCache(ExtendedImage image, string filename, IsolatedStorageFile storage)
        {
            try
            {
                using (IsolatedStorageFileStream cachedFile = storage.OpenFile(filename, FileMode.Create))
                {
                    WriteableBitmap bitmap = ImageExtensions.ToBitmap(image);
                    bitmap.SaveJpeg(cachedFile, bitmap.PixelWidth, bitmap.PixelHeight, 0, 80);

#if DEBUG
                    App.logger.log("Created cached file {0}", filename);
#endif
                }
            }
            catch (Exception)
            {
#if DEBUG
                throw;
#endif
            }
        }
Exemple #42
0
        public ConnectPage()
        {
            InitializeComponent();

            // Sauvegarde de l'avatar dans la mémoire du téléphone
            _webClient = new WebClient();
            _webClient.OpenReadCompleted += (s1, e1) =>
            {
                if (e1.Error == null)
                {
                    try
                    {
                        string fileName         = store["userAvatarFile"] as string;
                        bool   isSpaceAvailable = IsSpaceIsAvailable(e1.Result.Length);
                        if (isSpaceAvailable)
                        {
                            if (isoStore.FileExists(fileName))
                            {
                                isoStore.DeleteFile(fileName);
                            }
                            using (var isfs = new IsolatedStorageFileStream(fileName, FileMode.CreateNew, isoStore))
                            {
                                long   fileLen = e1.Result.Length;
                                byte[] b       = new byte[fileLen];
                                e1.Result.Read(b, 0, b.Length);
                                if (b[0] == 71 && b[1] == 73 && b[2] == 70)
                                {
                                    // File is a GIF, we need to convert it!
                                    var image      = new ExtendedImage();
                                    var gifDecoder = new ImageTools.IO.Gif.GifDecoder();
                                    gifDecoder.Decode(image, new MemoryStream(b));
                                    image.WriteToStream(isfs, "avatar.png");

                                    Dispatcher.BeginInvoke(() =>
                                    {
                                        store.Remove("isConnected");
                                        store.Add("isConnected", "");
                                        NavigationService.Navigate(new Uri("/WelcomePage.xaml?from=connect", UriKind.Relative));
                                    });
                                }
                                else
                                {
                                    isfs.Write(b, 0, b.Length);
                                    isfs.Flush();
                                    Dispatcher.BeginInvoke(() =>
                                    {
                                        store.Remove("isConnected");
                                        store.Add("isConnected", "");
                                        NavigationService.Navigate(new Uri("/WelcomePage.xaml?from=connect", UriKind.Relative));
                                    });
                                }
                            }
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(() => { MessageBox.Show("Erreur lors de la première connexion. La mémoire de votre terminal semble pleine."); });
                        }
                    }
                    catch (Exception ex)
                    {
                        Dispatcher.BeginInvoke(() => { MessageBox.Show("Erreur n°1 dans la sauvegarde de l'avatar : " + ex.Message); });
                    }
                }
                else
                {
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Erreur n°2 dans la sauvegarde de l'avatar : " + e1.Error.Message); });
                }
            };
        }