Ejemplo n.º 1
0
        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));
        }
        /// <summary>
        /// Handles the LoadingCompleted event of the image.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void image_LoadingCompleted(object sender, EventArgs e)
        {
            ExtendedImage image = sender as ExtendedImage;

            if (image != null)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    BuildingFilterImage4.Filter = new BlendingFilter(image)
                    {
                        GlobalAlphaFactor = 0.5
                    };

                    ResizeImage1.Image = image;
                    ResizeImage2.Image = ExtendedImage.Resize(image, 900, new BilinearResizer());
                    ResizeImage3.Image = ExtendedImage.Resize(image, 100, new BilinearResizer());
                    ResizeImage4.Image = ExtendedImage.Resize(image, 100, new BilinearResizer());
                });
            }
        }
Ejemplo n.º 3
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);
            }
        }
Ejemplo n.º 4
0
        public static ImageSource SaveThumbnail(ThumbnailOptions options)
        {
            // Make sure this method runs in the UI thread.
            if (!Deployment.Current.Dispatcher.CheckAccess())
            {
                return(Deployment.Current.Dispatcher.Invoke <ImageSource>(() =>
                {
                    return SaveThumbnail(options);
                }));
            }

            // Gets the images.
            WriteableBitmap preferedImage = GetBitmapSource(options.PreferedMedia);
            WriteableBitmap fallbackImage = GetBitmapSource(options.FallbackMedia);

            // Determines which image needs to be saved.
            WriteableBitmap targetImage = preferedImage;

            if (preferedImage == null)
            {
                // Use the fallback image if the prefered image does not exist.
                targetImage = fallbackImage;
            }
            else if (fallbackImage != null && options.MinWidth > -1 && preferedImage.PixelWidth < options.MinWidth && preferedImage.PixelWidth < fallbackImage.PixelWidth)
            {
                // Use the fallback image if its width is bigger than the prefered image's width, the latter being
                // smaller than the min width.
                targetImage = fallbackImage;
            }

            // No image? Return.
            if (targetImage == null)
            {
                return(null);
            }

            // Gets the dimensions of the target image.
            int    targetWidth      = (int)Math.Max(options.MinWidth, targetImage.PixelWidth);
            double sourcePixelRatio = targetImage.PixelWidth / (double)targetImage.PixelHeight;
            int    targetHeight     = (int)Math.Floor(targetWidth / sourcePixelRatio);

            // Blurs the image if needed.
            ExtendedImage targetExtendedImage = null;

            if (options.Blur)
            {
                // Converts the image to an ImageTools image.
                targetExtendedImage = targetImage.ToImage();

                // Resizes the image if it can help decreasing the time needed to blur it.
                // The image is only resized if the target size is less than the original size.
                // Otherwise it means that the original image is smaller than the target size, in which case we blur it
                // as it is and let WP scale up the blurred image later.
                if (targetExtendedImage.PixelHeight * targetExtendedImage.PixelWidth > targetWidth * targetHeight)
                {
                    targetExtendedImage = ExtendedImage.Resize(targetExtendedImage, targetWidth, targetHeight, new ImageTools.Filtering.NearestNeighborResizer());
                }

                // Inits the blur filter if needed and runs it.
                if (_gaussianBlurFilter == null)
                {
                    _gaussianBlurFilter = new ImageTools.Filtering.GaussianBlur()
                    {
                        Variance = 2d
                    };
                }
                targetExtendedImage = ExtendedImage.ApplyFilters(targetExtendedImage, _gaussianBlurFilter);
            }

            // Crops the image if needed.
            if (options.CropRectangle.HasValue)
            {
                if (targetExtendedImage == null)
                {
                    // Converts the image to an ImageTools image.
                    targetExtendedImage = targetImage.ToImage();
                }

                // Computes the downscaled crop rectangle.
                // We're downscaling the crop rectangle instead of upscaling the image and then cropping it,
                // in order to save some time.
                // WP will upscale the cropped image later on.
                int       conformedCropWidth  = Math.Min(options.CropRectangle.Value.Width, targetWidth);
                int       conformedCropHeight = Math.Min(options.CropRectangle.Value.Height, targetHeight);
                double    scaleFactor         = (double)targetExtendedImage.PixelWidth / (double)targetWidth;
                Rectangle crop = options.CropRectangle.Value;
                crop.Width  = (int)(conformedCropWidth * scaleFactor);
                crop.Height = (int)(conformedCropHeight * scaleFactor);
                crop.X      = (int)((double)crop.X * scaleFactor);
                crop.Y      = (int)((double)crop.Y * scaleFactor);

                // Crops the image.
                if (crop.Width > 0 && crop.Height > 0)
                {
                    targetExtendedImage = ExtendedImage.Crop(targetExtendedImage, crop);
                }

                // Stores the final dimensions of the image for later scaling.
                targetWidth  = conformedCropWidth;
                targetHeight = conformedCropHeight;
            }

            if (targetExtendedImage != null)
            {
                targetImage = targetExtendedImage.ToBitmap();
            }

            // Saves the image.
            try
            {
                if (targetWidth > 0 && targetHeight > 0)
                {
                    using (IsolatedStorageFileStream stream = options.IsoStoreFile.OpenFile(options.Filename, FileMode.Create, FileAccess.ReadWrite))
                    {
                        targetImage.SaveJpeg(stream, targetWidth, targetHeight, 0, 100);
                    }
                }
            }
            catch (IsolatedStorageException ex)
            {
                // Nothing to do, let's just dump this for further analysis.
                DebugUtils.DumpException(ex, string.Format("OpenFile(f:{0})", options.Filename), true);
            }
            catch (ArgumentException ex)
            {
                // Nothing to do, let's just dump this for further analysis.
                DebugUtils.DumpException(ex, string.Format("SaveJpeg(w:{0},h:{1})", targetWidth, targetHeight), true);
            }

            // Returns the image.
            return(targetImage);
        }
Ejemplo n.º 5
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;
            }
            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);
            }
        }