Inheritance: SimpleImage
		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;
			string filename = EditorUtility.OpenFilePanel("Load file", "", generateFilterValue(fileTypes));
			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))
						{
							IImageDecoder decoder = null;
							switch (Path.GetExtension(filename).ToLower())
							{
								case ".jpg": decoder = new JpegDecoder(); break;
								case ".jpeg": decoder = new JpegDecoder(); break;
								case ".png": decoder = new 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 = 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);
			}
		}
Beispiel #2
0
        private void SaveGraphAsImage()
        {
            //TODO:  ENSURE THAT DATA IS EVEN PRESENT ON THE GRAPH
            //TODO:  THIS SHOULD BE DECOUPLED

            ImageTools.IO.Encoders.AddEncoder <ImageTools.IO.Jpeg.JpegEncoder>();
            ImageTools.IO.Encoders.AddEncoder <ImageTools.IO.Png.PngEncoder>();

            UI.GraphViewModel graphVM = UI.ViewModelLocator.GraphDataStatic;

            ImageTools.ExtendedImage myImage = graphVM.GraphToImage();

            System.Windows.Controls.SaveFileDialog saveFileDialog = new System.Windows.Controls.SaveFileDialog();

            saveFileDialog.Filter      = "JPEG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png";
            saveFileDialog.FilterIndex = 1;

            bool?dialogResult = saveFileDialog.ShowDialog();

            if (dialogResult == true)
            {
                using (Stream fs = (Stream)saveFileDialog.OpenFile())
                {
                    myImage.WriteToStream(fs, saveFileDialog.SafeFileName);
                }
            }
        }
		public static WriteableBitmap GetBitmapSource(ExtendedImage image)
		{
			// Waits for the bitmap to be loaded if it needs so.
			if (!image.IsFilled)
			{
				if (!image.IsLoading)
				{
                    return null;
				}

				ManualResetEvent resetEvent = new ManualResetEvent(false);

				EventHandler onLoaded = new EventHandler((o, e) =>
				{
					resetEvent.Set();
				});

				image.LoadingCompleted += onLoaded;

				resetEvent.WaitOne(1000);

				image.LoadingCompleted -= onLoaded;
			}

			// Converts the bitmap.
            return image.ToBitmap();
		}
        /// <summary>
        /// Cuts the image with the specified rectangle and returns a new image.
        /// </summary>
        /// <param name="source">The image, where a cutted copy should be made from.</param>
        /// <param name="bounds">The bounds of the new image.</param>
        /// <returns>The new cutted image.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null
        /// (Nothing in Visual Basic).</exception>
        public static ExtendedImage Crop(ExtendedImage source, Rectangle bounds)
        {
            Contract.Requires<ArgumentNullException>(source != null, "Source image cannot be null.");
            Contract.Requires<ArgumentException>(source.IsFilled, "Source image has not been loaded.");

            return PerformAction(source, false, (sourceImage, targetImage) => ImageBase.Crop(sourceImage, targetImage, bounds));
        }
        public async void LoadImage(String filename)
        {
            var file = await KnownFolders.PicturesLibrary.GetFileAsync(filename);

            ExtendedImage image = new ExtendedImage();
            image.LoadingCompleted +=
                (o, ea) => Dispatcher.BeginInvoke(() => { AnimatedImage.Source = image; });
            image.SetSource((await file.OpenReadAsync()).AsStreamForRead());
        }
        public static void LoadJpeg(this WriteableBitmap bitmap, Stream sourceStream)
        {
            JpegDecoder decoder = new JpegDecoder();

            var image = new ExtendedImage();

            decoder.Decode(image, sourceStream);

            WP7Utilities.UIThreadInvoke(() => bitmap.SetSource(image.ToStream()));
        }
Beispiel #7
0
        public GifViewer()
        {
            //http://stackoverflow.com/questions/9667840/how-to-use-gif-animated-image-in-wp-7
            Decoders.AddDecoder<GifDecoder>();
            Uri uri3 = new Uri(@"\ViewModel\Gifs\falling.gif", UriKind.Relative);
            ExtendedImage image3 = new ExtendedImage();

            image3.LoadingCompleted +=
               (o, e) => Dispatcher.BeginInvoke(() => AnimationImage3 = image3);
            image3.UriSource = uri3;
        }
        private async void LoadGifs()
        {
            StorageFile deleteFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Images/TaskDeleteAnimation.gif", UriKind.RelativeOrAbsolute));
            ExtendedImage delteImage = new ExtendedImage();
            delteImage.SetSource(await deleteFile.OpenStreamForReadAsync());
            this.TaskDeleteAnimation.Source = delteImage;

            StorageFile completeFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Images/TaskCompleteAnimation.gif", UriKind.RelativeOrAbsolute));
            ExtendedImage completeImage = new ExtendedImage();
            completeImage.SetSource(await completeFile.OpenStreamForReadAsync());
            this.TaskCompleteAnimation.Source = completeImage;
        }
 private AnimatedImage GifImage()
 {
     var source = new ExtendedImage { UriSource = new Uri(_gifPath, UriKind.RelativeOrAbsolute) };
     var animatedImage = new AnimatedImage {
         AnimationMode = AnimationMode.Repeat,
         Width = ScreenWidth,
         Height = 320,
         Stretch = Stretch.Fill,
         Opacity = Opacity,
         Source = source,
     };
     return animatedImage;
 }
        /// <summary>
        /// Applies the specified filter to the image ath the specified rectangle.
        /// </summary>
        /// <param name="source">The image, where the filter should be applied to.</param>
        /// <param name="filters">The filter, which should be applied to.</param>
        /// <param name="rectangle">The rectangle, where the filter should be applied to.</param>
        /// <returns>
        /// A copy of the image with the applied filter.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// 	<para><paramref name="source"/> is null (Nothing in Visual Basic).</para>
        /// 	<para>- or -</para>
        /// 	<para><paramref name="filters"/> is null (Nothing in Visual Basic).</para>
        /// </exception>
        public static ExtendedImage ApplyFilters(ExtendedImage source, Rectangle rectangle, params IImageFilter[] filters)
        {
            Contract.Requires<ArgumentNullException>(source != null, "Source image cannot be null.");
            Contract.Requires<ArgumentException>(source.IsFilled, "Source image has not been loaded.");
            Contract.Requires<ArgumentNullException>(filters != null, "Filters cannot be null.");

            foreach (IImageFilter filter in filters)
            {
                source = PerformAction(source, true, (sourceImage, targetImage) => filter.Apply(targetImage, sourceImage, rectangle));
            }

            return source;
        }
Beispiel #11
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="index"></param>
        /// <param name="imgContain"></param>
        private void LoadPic(int index, ref ImageTools.Controls.AnimatedImage imgContain)
        {
            if (imgContain.Source != null)
            {
                if (!OutOfTime(index))
                {
                    return;
                }
            }

            if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                MessageBox.Show("网络异常!");
            ExtendedImage image = new ImageTools.ExtendedImage();

            image.UriSource = new Uri(_bindData[index].Url);
            imgContain.Source = image;

            _bindData[index].DownLoadTime = DateTime.Now;
        }
        public static void SaveJpeg(this WriteableBitmap bitmap, Stream targetStream, int targetWidth, int targetHeight, int orientation, int quality)
        {
            ExtendedImage image = null;
            var disp = bitmap.Dispatcher;
            using (var are = new AutoResetEvent(false))
            {
                disp.BeginInvoke(() =>
                {
                    image = bitmap.ToImage();
                    are.Set();
                });
                are.WaitOne();
            }

            var resizer = new NearestNeighborResizer();
            var imageBaseOut = new ExtendedImage(targetWidth, targetHeight);
            resizer.Resize(image, imageBaseOut, targetWidth, targetHeight);
            var encoder = new JpegEncoder {Quality = quality};
            encoder.Encode(imageBaseOut, targetStream);
        }
Beispiel #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExtendedImage"/> class
        /// by making a copy from another image.
        /// </summary>
        /// <param name="other">The other image, where the clone should be made from.</param>
        /// <exception cref="ArgumentNullException"><paramref name="other"/> is null
        /// (Nothing in Visual Basic).</exception>
        public ExtendedImage(ExtendedImage other)
            : base(other)
        {
            Contract.Requires <ArgumentNullException>(other != null, "Other image cannot be null.");
            Contract.Requires <ArgumentException>(other.IsFilled, "Other image has not been loaded.");
            Contract.Ensures(IsFilled);

            foreach (ImageFrame frame in other.Frames)
            {
                if (frame != null)
                {
                    if (!frame.IsFilled)
                    {
                        throw new ArgumentException("The image contains a frame that has not been loaded yet.");
                    }

                    Frames.Add(new ImageFrame(frame));
                }
            }

            DensityX = DefaultDensityX;
            DensityY = DefaultDensityY;
        }
Beispiel #14
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);
        }
Beispiel #15
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);
        }
        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));
                }
            }
        }
        /// <summary>
        /// Converts the image to a stream, which can be assigned to
        /// a silverlight image control as image source and applies the specified
        /// filter before converting the image. The encoder to use will be created by
        /// the file extension name.
        /// </summary>
        /// <param name="image">The image, which should be converted. Cannot be null
        /// (Nothing in Visual Basic).</param>
        /// <param name="extension">The file extension to create the <see cref="IImageEncoder"/> that
        /// will be used to create an image stream.</param>
        /// <returns>The resulting stream.</returns>
        /// <exception cref="ArgumentException"><paramref name="extension"/> is empty or
        /// contains only blanks.</exception>
        /// <exception cref="ArgumentNullException">
        ///     <para><paramref name="image"/> is null (Nothing in Visual Basic).</para>
        ///     <para>- or -</para>
        ///     <para><paramref name="extension"/> is null (Nothing in Visual Basic).</para>
        /// </exception>
        public static Stream ToStreamByExtension(this ExtendedImage image, string extension)
        {
            Contract.Requires <ArgumentNullException>(image != null, "Image cannot be null.");
            Contract.Requires <ArgumentException>(image.IsFilled, "Image has not been loaded.");
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(extension), "Extension cannot be null or empty.");

            IImageEncoder encoder = null;

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

            MemoryStream memoryStream = null;

            try
            {
                memoryStream = new MemoryStream();
                encoder.Encode(image, memoryStream);

                memoryStream.Seek(0, SeekOrigin.Begin);
            }
            catch
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
                throw;
            }
            return(memoryStream);
        }
Beispiel #18
0
        /// <summary>
        /// Resizes the specified image by using the specified <see cref="IImageResizer"/> and
        /// returns new image which has the specified maximum
        /// extension in x and y direction.
        /// </summary>
        /// <param name="source">The source image to resize.</param>
        /// <param name="size">The maximum size of the image in x and y direction.</param>
        /// <param name="resizer">The resizer, which should resize the image.</param>
        /// <returns>The resized image.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null
        /// (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentException"><paramref name="size"/> is negative.</exception>
        public static ExtendedImage Resize(ExtendedImage source, int size, IImageResizer resizer)
        {
            Contract.Requires <ArgumentNullException>(source != null, "Source image cannot be null.");
            Contract.Requires <ArgumentException>(source.IsFilled, "Source image has not been loaded.");
            Contract.Requires <ArgumentNullException>(resizer != null, "Image Resizer cannot be null.");

            int width  = 0;
            int height = 0;

            float ratio = (float)source.PixelWidth / source.PixelHeight;

            if (source.PixelWidth > source.PixelHeight && ratio > 0)
            {
                width  = size;
                height = (int)(width / ratio);
            }
            else
            {
                height = size;
                width  = (int)(height * ratio);
            }

            return(PerformAction(source, false, (sourceImage, targetImage) => resizer.Resize(sourceImage, targetImage, width, height)));
        }
        /// <summary>
        /// Gets the traffic map.
        /// </summary>
        /// <returns></returns>
        public IObservable<ExtendedImage> GetTrafficMap()
        {
            return new AnonymousObservable<ExtendedImage>(observer =>
            {
                IObservable<MemoryStream> observable = ObservableHelper.StreamFromUri(new Uri(DfwTranstarUri.TrafficMapUri));

                observable.Subscribe(stream =>
                {
                    if (stream != null)
                    {
                        var decoder = new ImageTools.IO.Gif.GifDecoder();
                        var image = new ExtendedImage();
                        decoder.Decode(image, stream);

                        observer.OnNext(image);
                        observer.OnCompleted();
                    }
                }, ex =>
                {
                    observer.OnError(new Exception("Unable to retrieve traffic data.", ex));
                });

                return Disposable.Empty;
            });
        }
        /// <summary>
        /// Transforms the specified image by flipping and rotating it. First the image
        /// will be rotated, then the image will be flipped. A new image will be returned. The original image
        /// will not be changed.
        /// </summary>
        /// <param name="source">The image, which should be transformed.</param>
        /// <param name="rotationType">Type of the rotation.</param>
        /// <param name="flippingType">Type of the flipping.</param>
        /// <returns>The new and transformed image.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null
        /// (Nothing in Visual Basic).</exception>
        public static ExtendedImage Transform(ExtendedImage source, RotationType rotationType, FlippingType flippingType)
        {
            Contract.Requires<ArgumentNullException>(source != null, "Source image cannot be null.");
            Contract.Requires<ArgumentException>(source.IsFilled, "Source image has not been loaded.");

            return PerformAction(source, false, (sourceImage, targetImage) => ImageBase.Transform(sourceImage, targetImage, rotationType, flippingType));
        }
        public IEnumerable<IResult> LoadViewSignature()
        {
            if (this.IsLoadedSignature)
                yield break;

            // Initialize Objects here

            switch (AssistantMode) {
                case ViewMode.Add:
                    break;
                case ViewMode.Edit:
                    if (!string.IsNullOrWhiteSpace(this.User.Signature.Signature)) {
                        ExImage = new ExtendedImage();
                        ExImage.SetSource(new MemoryStream(System.Convert.FromBase64String(Security.AesDecrypt(this.User.Signature.Signature, SessionInfo.Instance.CurrentUser.BaseKey))));
                    }
                    break;
                default:
                    break;
            }

            UpdateSummarySignature();
            this.IsLoadedSignature = true;
        }
        public void LoadImage()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "Image Files (*.jpg;*.png;*.bmp;*gif)|*.jpg;*.png;*.bmp;*.gif";
            if (openFileDialog.ShowDialog() == true) {

                FileInfo fileInfo = openFileDialog.File;
                exImage = new ExtendedImage();
                exImage.LoadingFailed += ExImageLoadingFailed;
                exImage.LoadingCompleted += ExImageOnLoadingCompleted;
                exImage.SetSource(fileInfo.OpenRead());
                //exImage.UriSource = new Uri(fileInfo.DirectoryName + "/erd.png", UriKind.Absolute);
            }
        }
Beispiel #23
0
        private void DoWork(object sender, DoWorkEventArgs args)
        {
            string url = args.Argument.ToString();
            string name = string.Format("image-{0}.jpg", DateTime.Now.Ticks);

            if (url.Contains("/") && !url.Contains("attachment.php"))
            {
                var tokens = url.Split('/');
                name = tokens[tokens.Length - 1];
            }

            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            Stream data = null;

            request.BeginGetResponse(state =>
                {
                    try
                    {
                        var response = request.EndGetResponse(state);
                        data = response.GetResponseStream();
                    }
                    catch (Exception ex) { Console.WriteLine(ex.Message); }
                    finally { signal.Set(); }

                }, request);

            signal.WaitOne(App.Settings.ThreadTimeout);

            if (worker.CancellationPending) { args.Cancel = true; return; }

            if (data == null)
            {
                args.Result = Awful.Core.Models.ActionResult.Failure;
                return;
            }

             if (worker.CancellationPending) { args.Cancel = true; return; }
             IsolatedStorageFileStream fileStream = null;

            try
            {
                MediaLibrary lib = new MediaLibrary();

                string tempFile = name;
                var dispatch = Deployment.Current.Dispatcher;
                var dispatchSignal = new AutoResetEvent(false);
                var store = IsolatedStorageFile.GetUserStoreForApplication();

                dispatch.BeginInvoke(() =>
                    {
                        try
                        {
                            if (store.FileExists(tempFile))
                                store.DeleteFile(tempFile);

                            fileStream = store.CreateFile(tempFile);
                            WriteableBitmap bitmap;

                            try
                            {
                                var decoder = new GifDecoder();
                                var image = new ExtendedImage();
                                decoder.Decode(image, data);
                                bitmap = image.ToBitmap();
                            }
                            catch (Exception ex)
                            {
                                var image = new BitmapImage();
                                image.SetSource(data);
                                bitmap = new WriteableBitmap(image);
                            }

                            bitmap.SaveJpeg(fileStream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                            fileStream.Close();
                            dispatchSignal.Set();
                        }
                        catch (Exception ex) { dispatchSignal.Set(); }
                    });

                dispatchSignal.WaitOne();
                fileStream = store.OpenFile(tempFile, FileMode.Open, FileAccess.Read);
                lib.SavePicture(name, fileStream);
                fileStream.Close();
                store.DeleteFile(tempFile);

                args.Result = Awful.Core.Models.ActionResult.Success;
            }
            catch (Exception ex)
            {
                if (fileStream != null)
                    fileStream.Close();

                Console.WriteLine(ex.Message);
                args.Result = Awful.Core.Models.ActionResult.Failure;
            }
        }
        private static ExtendedImage PerformAction(ExtendedImage source, bool clone, Action<ImageBase, ImageBase> action)
        {
            VerifyHasLoaded(source);

            ExtendedImage transformedImage = clone ? new ExtendedImage(source) : new ExtendedImage();
            
            action(source, transformedImage);

            foreach (ImageFrame frame in source.Frames)
            {
                ImageFrame temp = new ImageFrame();

                action(frame, temp);

                if (!clone)
                {
                    transformedImage.Frames.Add(temp);
                }
            }

            return transformedImage;
        }        
		public override Codec.DecodeResult Decode( Stream input )
		{
			var wait = new ManualResetEvent( false );
			var its = new ExtendedImage();
			its.LoadingCompleted += ( s, e ) => wait.Set();
			its.LoadingFailed += ( s, e ) =>
									{
										Debug.WriteLine( e.ExceptionObject.ToString() );
										wait.Set();
									};
			its.SetSource( input );
			wait.WaitOne();
			return Decode( its );
		}
        /// <summary>
        /// Resizes the specified image by using the specified <see cref="IImageResizer"/> and
        /// returns new image which has the specified maximum
        /// extension in x and y direction.
        /// </summary>
        /// <param name="source">The source image to resize.</param>
        /// <param name="size">The maximum size of the image in x and y direction.</param>
        /// <param name="resizer">The resizer, which should resize the image.</param>
        /// <returns>The resized image.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null
        /// (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentException"><paramref name="size"/> is negative.</exception>
        public static ExtendedImage Resize(ExtendedImage source, int size, IImageResizer resizer)
        {
            Contract.Requires<ArgumentNullException>(source != null, "Source image cannot be null.");
            Contract.Requires<ArgumentException>(source.IsFilled, "Source image has not been loaded.");
            Contract.Requires<ArgumentNullException>(resizer != null, "Image Resizer cannot be null.");

            int width = 0;
            int height = 0;

            float ratio = (float)source.PixelWidth / source.PixelHeight;

            if (source.PixelWidth > source.PixelHeight && ratio > 0)
            {
                width = size;
                height = (int)(width / ratio);
            }
            else
            {
                height = size;
                width = (int)(height * ratio);
            }

            return PerformAction(source, false, (sourceImage, targetImage) => resizer.Resize(sourceImage, targetImage, width, height));
        }
		public static WriteableBitmap GetBitmapSource(byte[] data)
		{
			using (MemoryStream ms = new MemoryStream(data))
			{
				try
				{
					// Tries to load the image using Windows Phone's internals.
					BitmapImage image = null;
					image = new BitmapImage();
					image.SetSource(ms);

					return new WriteableBitmap(image);
				}
				catch (Exception)
				{
					try
					{
						// Resets the memory stream's position.
                        ms.Position = 0;

                        // It didn't work. Now try with ImageTools.
						ExtendedImage eim = new ExtendedImage();
						eim.SetSource(ms);

                        // Gets the image source for the image.
						WriteableBitmap bs = GetBitmapSource(eim);
                        if (bs == null)
                        {
                            // Something went wrong.
                            DebugUtils.DumpData(data, "ImageTools failed to generate an image source.");
                        }
                        return bs;
					}
					catch (Exception e)
					{
						// Dump data!
						DebugUtils.DumpData(data, e);
						return null;
					}
				}
			}
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="ExtendedImage"/> class
        /// by making a copy from another image.
        /// </summary>
        /// <param name="other">The other image, where the clone should be made from.</param>
        /// <exception cref="ArgumentNullException"><paramref name="other"/> is null
        /// (Nothing in Visual Basic).</exception>
        public ExtendedImage(ExtendedImage other)
            : base(other)
        {
            Contract.Requires<ArgumentNullException>(other != null, "Other image cannot be null.");
            Contract.Requires<ArgumentException>(other.IsFilled, "Other image has not been loaded.");
            Contract.Ensures(IsFilled);

            foreach (ImageFrame frame in other.Frames)
            {
                if (frame != null)
                {
                    if (!frame.IsFilled)
                    {
                        throw new ArgumentException("The image contains a frame that has not been loaded yet.");
                    }

                    Frames.Add(new ImageFrame(frame));
                }
            }

            DensityX = DefaultDensityX;
            DensityY = DefaultDensityY;
        }
 BarcodeResult IBarcodeReader.ReadBarcode(ExtendedImage image)
 {
     Contract.Requires<ArgumentNullException>(image != null, "Image cannot be null.");
     Contract.Requires<ArgumentException>(image.IsFilled, "Image cannot be empty.");
     throw new NotImplementedException();
 }
Beispiel #30
0
        private void ViewCurrentImageButton_Click(object sender, RoutedEventArgs e)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendEvent("splashchanger", "click", "View Current Image", 0);
            try
            {
            #if WP8
                CustomMessageBox cmb = new CustomMessageBox()
                {
                    IsLeftButtonEnabled = true,
                    IsRightButtonEnabled = true,
                    RightButtonContent = "Shutdown",
                    LeftButtonContent = "Startup",
                    Message = "Which boot screen you'd like to view?"

                };
                cmb.Dismissed += new EventHandler<DismissedEventArgs>((dsender, de) =>
                {
                    string screen = "Boot";
                    if (de.Result == CustomMessageBoxResult.RightButton)
                    {
                        screen = "Shutdown";
                    }
                    try {
                    using (var stream = System.IO.File.OpenRead(Registry.ReadString(RegistryHive.HKLM, @"SYSTEM\Shell\BootScreens", "WP" + screen + "ScreenOverride")))
                    {
            #else

                using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!store.FileExists("mologo.bmp"))
                    {

                        string dir = @"\Applications\Data\abc1e9fe-b4ab-402c-ab21-11e97e3fde3a\Data\IsolatedStore";
                        WP7RootToolsSDK.FileSystem.CopyFile(@"\windows\mologo.bmp", dir + "\\mologo.bmp");
                    }
                    using (var stream = store.OpenFile("mologo.bmp", System.IO.FileMode.Open))
                    {
            #endif
            #if WP8
                        var iso = new ExtendedImage();
                        var dec = new ImageTools.IO.Bmp.BmpDecoder();
                        dec.Decode(iso, stream);
                        SplashImage.Source = iso.ToBitmap();
                        SplashImage.Visibility = Visibility.Visible;
                    }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Failed", MessageBoxButton.OK);
                    }
                });
                cmb.Show();
            #else
                        MessageBox.Show("Feature not implemented yet!");
                }
            #endif

            #if !WP8
            }
Beispiel #31
0
        private void saveImage(Stream image, bool shutdown = false)
        {
            using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                string filename = "mologo.bmp";
                if (shutdown)
                {
                    filename = "mologo_shutdown.bmp";
                }
            #if WP8
                using (var stream = File.Open(splashDir+filename,FileMode.Create))
            #else
                using (var stream = store.OpenFile(filename, System.IO.FileMode.Create))
            #endif
                {
                    var img = new Image();
                    img.Width = ResolutionSize.Width;
                    img.Height = ResolutionSize.Height;
                    var bi = new BitmapImage();
                    bi.SetSource(image);

                    img.Source = bi;
                    var img1 = img.ToImage();
                    IImageEncoder encoder = new BmpEncoder();
                    ExtendedImage ei = new ExtendedImage(img1);

                    if (ei.PixelHeight != (int)ResolutionSize.Height || ei.PixelWidth != (int)ResolutionSize.Width)
                    {
                        byte[] pixels = new byte[((int)ResolutionSize.Height) * ((int)ResolutionSize.Width)];
                        int i = 0;
                        foreach (byte b in pixels)
                        {
                            if (ei.Pixels.Length < i)
                            {
                                pixels[i] = b;
                            }
                            else
                            {
                                pixels[i] = 0;
                            }
                            i++;
                        }
                        ei.SetPixels((int)ResolutionSize.Width, (int)ResolutionSize.Height, ei.Pixels);
                    }
                    encoder.Encode(ei, stream);
                }
            }
        }
Beispiel #32
0
 BarcodeResult IBarcodeReader.ReadBarcode(ExtendedImage image)
 {
     Contract.Requires <ArgumentNullException>(image != null, "Image cannot be null.");
     Contract.Requires <ArgumentException>(image.IsFilled, "Image cannot be empty.");
     throw new NotImplementedException();
 }
        /// <summary>
        /// Resizes the specified image by using the specified <see cref="IImageResizer"/> and
        /// return a new image with
        /// the spezified size which is a resized version of the passed image.
        /// </summary>
        /// <param name="source">The width of the new image. Must be greater than zero.</param>
        /// <param name="width">The width of the new image. Must be greater than zero.</param>
        /// <param name="height">The height of the new image. Must be greater than zero.</param>
        /// <param name="resizer">The resizer, which should resize the image.</param>
        /// <returns>The new image.</returns>
        /// <exception cref="ArgumentNullException">
        /// 	<para><paramref name="resizer"/> is null (Nothing in Visual Basic).</para>
        /// 	<para>- or -</para>
        /// 	<para><paramref name="source"/> is null (Nothing in Visual Basic).</para>
        /// </exception>
        /// <exception cref="ArgumentException">
        /// 	<para><paramref name="width"/> is negative.</para>
        /// 	<para>- or -</para>
        /// 	<para><paramref name="height"/> is negative.</para>
        /// </exception>
        public static ExtendedImage Resize(ExtendedImage source, int width, int height, IImageResizer resizer)
        {
            Contract.Requires<ArgumentNullException>(source != null, "Source image cannot be null.");
            Contract.Requires<ArgumentException>(source.IsFilled, "Source image has not been loaded.");
            Contract.Requires<ArgumentNullException>(resizer != null, "Image Resizer cannot be null.");

            return PerformAction(source, false, (sourceImage, targetImage) => resizer.Resize(sourceImage, targetImage, width, height));
        }
        private void DownloadUserImage(string host, LocomotiveImage img)
        {
            if (!string.IsNullOrEmpty(img.Url))
            {
                WebClient webClient = new WebClient();
                webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
                {
                    if (e.Error != null)
                        Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(e.Error.Message, App.Name, MessageBoxButton.OK); });
                    else
                    {
                        int imageIdx = (int)e.UserState;

                        ExtendedImage eimg = new ExtendedImage();
                        var bd = new BmpDecoder();
                        //var bd = new PngDecoder();
                        //var bd = new JpegDecoder();
                        //var bd = new GifDecoder();
                        bd.Decode(eimg, e.Result);
                        //MemoryStream ms = (MemoryStream)eimg.ToStreamByExtension("bmp");

                        //BitmapImage bi = new BitmapImage();
                        //bi.SetSource(ms);

                        //App.EcosModel.LocomotivesManager.ItemsUser[imageIdx].BitmapImage = bi;

                        e.Result.Close();
                    }
                };

                webClient.OpenReadAsync(new Uri(host + img.Url, UriKind.Absolute), img.Index);
            }
        }
		private void init(Stream stream, GIFFrameUpdatedCallbackMethod frameUpdatedCallback)
		{
			// set gif frame update callback
			this.FrameUpdatedCallback = frameUpdatedCallback;

			// decode gif image
			var gifDecoder = new GifDecoder();
			var image = new ExtendedImage();
			gifDecoder.Decode(image, stream);

			// add frames and load unity textures
			frames = new List<TextureGIFFrame>();
			var firstFrame = new TextureGIFFrame(createTexture(image.PixelWidth, image.PixelHeight, image.Pixels), TimeSpan.FromSeconds(image.DelayTime / 100d));
			frames.Add(firstFrame);
			var lastFrame = firstFrame;
			foreach (var frame in image.Frames)
			{
				var newFrame = new TextureGIFFrame(createTexture(frame.PixelWidth, frame.PixelHeight, frame.Pixels), TimeSpan.FromSeconds(frame.DelayTime / 100d));
				frames.Add(newFrame);
				if (lastFrame != null) lastFrame.nextFrame = newFrame;
				lastFrame = newFrame;
			}

			// set starting image
			CurrentFrame = frames[0];
			lastFrame.nextFrame = firstFrame;
		}
		protected DecodeResult Decode( ExtendedImage input )
		{
			var w = (int)ClosestPowerOfTwo( input.PixelWidth );
			var h = (int)ClosestPowerOfTwo( input.PixelHeight );

			var id = new ImageCodec.ImageData
			{
				width = w,
				height = h,
				depth = 1,
				size = 0,
				numMipMaps = -1,
				format = PixelFormat.A8B8G8R8
			};

			for ( int i = System.Math.Min( w, h ), s = w * h; i > 0; i >>= 1, s >>= 2, id.numMipMaps++ )
				id.size += s;

			var bp = new byte[ id.size * 4 ];
			var ofs = 0;

#if DEBUGMIPMAPS
						var cval = new[] { 0xFFF00000, 0xFF00F100, 0xFF0000F2, 0xFFF3F300, 0xFF00F4F4, 0xFFF500F5, 0xFFF6F6F6 };
						var cidx = 0;
#endif

			while ( ofs < bp.Length )
			{
				var wb = ExtendedImage.Resize( input, w, h, Resizer );
#if DEBUGMIPMAPS
							var c=(int)cval[cidx%cval.Length];
							for (var i = 0; i < wb.Pixels.Length; i++)
								wb.Pixels[i] = c;
							cidx++;
#endif

				var len = w * h * 4;
				Buffer.BlockCopy( wb.Pixels, 0, bp, ofs, len );
				ofs += len;

				w >>= 1;
				h >>= 1;
			}

			return new DecodeResult( new MemoryStream( bp ), id );
		}
        private static void VerifyHasLoaded(ExtendedImage image)
        {
            Contract.Requires(image != null);

            if (!image.IsFilled)
            {
                throw new InvalidOperationException("Image has not been loaded");
            }

            foreach (ImageFrame frame in image.Frames)
            {
                if (frame != null && frame.IsFilled)
                {
                    throw new InvalidOperationException("Not all frames has been loaded yet.");
                }
            }
        }