public void PageLoaded(object sender, RoutedEventArgs args)
      {
         // Create Image element.
         Image rotated90 = new Image();
         rotated90.Width = 150;

         // Create the TransformedBitmap to use as the Image source.
         TransformedBitmap tb = new TransformedBitmap();

         // Create the source to use as the tb source.
         BitmapImage bi = new BitmapImage();
         bi.BeginInit();
         bi.UriSource = new Uri(@"sampleImages/watermelon.jpg", UriKind.RelativeOrAbsolute);
         bi.EndInit();

         // Properties must be set between BeginInit and EndInit calls.
         tb.BeginInit();
         tb.Source = bi;
         // Set image rotation.
         RotateTransform transform = new RotateTransform(90);
         tb.Transform = transform;
         tb.EndInit();
         // Set the Image source.
         rotated90.Source = tb;

         //Add Image to the UI
         Grid.SetColumn(rotated90, 1);
         Grid.SetRow(rotated90, 1);
         transformedGrid.Children.Add(rotated90);

      }
Ejemplo n.º 2
0
        private void buttonRotate_Click(object sender, RoutedEventArgs e)
        {
            TransformedBitmap tb = new TransformedBitmap();
            tb.BeginInit();
            tb.Transform = new RotateTransform(90);
            tb.Source = this.imageViewModel.LoadedBitmap;
            tb.EndInit();
            this.imageViewModel.LoadedBitmap = tb;

            this.imageViewModel.ClearPositions();
        }
Ejemplo n.º 3
0
        public ShowMyFace()
        {
            Title = "Show My Face";

            ///******************************************************************
            //  3���� ShowMyFace ����
            //******************************************************************/
            Uri uri = new Uri("http://www.charlespetzold.com/PetzoldTattoo.jpg");
            //BitmapImage bitmap = new BitmapImage(uri);
            //Image img = new Image();
            //img.Source = bitmap;
            //Content = img;

            ///******************************************************************
            //  p1245 BitmapImage �ڵ�
            //******************************************************************/
            Image rotated90 = new Image();
            TransformedBitmap tb = new TransformedBitmap();
            FormatConvertedBitmap fb = new FormatConvertedBitmap();
            CroppedBitmap cb = new CroppedBitmap();

            // Create the source to use as the tb source.
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = uri;
            bi.EndInit();

            //cb.BeginInit();
            //cb.Source = bi;
            //Int32Rect rect = new Int32Rect();
            //rect.X = 220;
            //rect.Y = 200;
            //rect.Width = 120;
            //rect.Height = 80;
            //cb.SourceRect = rect;

            //cb.EndInit();

            fb.BeginInit();
            fb.Source = bi;
            fb.DestinationFormat = PixelFormats.Gray2;
            fb.EndInit();

            // Properties must be set between BeginInit and EndInit calls.
            tb.BeginInit();
            tb.Source = fb;
            // Set image rotation.
            tb.Transform = new RotateTransform(90);
            tb.EndInit();
            // Set the Image source.
            rotated90.Source = tb;
            Content = rotated90;
        }
Ejemplo n.º 4
0
        public ScannedImagesModel RotateImage( int rotate )
        {
            var bitmap = GetBitmapImage();

            var rotated = new TransformedBitmap();
            rotated.BeginInit();
            rotated.Source = bitmap;
            var transform = new RotateTransform( rotate );
            rotated.Transform = transform;
            rotated.EndInit();

            // get temporary file
            var filename = PathUtility.GetTempFileName();
            var landscape = ( rotate == 90 || rotate == 270 ) ? !Landscape : Landscape;

            SaveImage( rotated, filename );

            return new ScannedImagesModel( filename, landscape );
        }
        private void handleFrameFn(object sender, FrameReadyEventArgs e)
        {
            //    Int32Rect cropRect = new Int32Rect(400, 380, 300, 200);
            //    BitmapSource croppedImage = new CroppedBitmap(e.BitmapImage, cropRect);
            //    image4.Source = croppedImage;

            if (_rotationAngle != 0)
            {
                TransformedBitmap tmpImage = new TransformedBitmap();

                tmpImage.BeginInit();
                tmpImage.Source = e.BitmapImage; // of type BitmapImage

                RotateTransform transform = new RotateTransform(_rotationAngle);
                tmpImage.Transform = transform;
                tmpImage.EndInit();

                _dispImage.Source = tmpImage;
            }
            else
            {
                _dispImage.Source = e.BitmapImage;
            }
        }
Ejemplo n.º 6
0
		/// <summary>
		/// Resize BitmapSource and reflect Exif orientation to BitmapSource.
		/// </summary>
		/// <param name="bitmapSource">Source BitmapSource</param>
		/// <param name="outerSize">Target outer size</param>
		/// <param name="orientation">Exif orientation</param>
		/// <returns>Outcome BitmapSource</returns>
		private static BitmapSource ResizeAndReflectExifOrientation(BitmapSource bitmapSource, Size outerSize, int orientation)
		{
			var transform = new TransformGroup();
			var centerX = bitmapSource.Width / 2D;
			var centerY = bitmapSource.Height / 2D;
			bool isRotatedRightAngle = false;

			// Reflect Exif orientation.
			switch (orientation)
			{
				case 0: // Invalid
				case 1: // Horizontal (normal)
					break;

				case 2: // Mirror horizontal
					transform.Children.Add(new ScaleTransform(-1, 1, centerX, centerY));
					break;
				case 3: // Rotate 180 clockwise
					transform.Children.Add(new RotateTransform(180D, centerX, centerY));
					break;
				case 4: // Mirror vertical
					transform.Children.Add(new ScaleTransform(1, -1, centerX, centerY));
					break;
				case 5: // Mirror horizontal and rotate 270 clockwise
					transform.Children.Add(new ScaleTransform(-1, 1, centerX, centerY));
					transform.Children.Add(new RotateTransform(270D, centerX, centerY));
					isRotatedRightAngle = true;
					break;
				case 6: // Rotate 90 clockwise
					transform.Children.Add(new RotateTransform(90D, centerX, centerY));
					isRotatedRightAngle = true;
					break;
				case 7: // Mirror horizontal and rotate 90 clockwise
					transform.Children.Add(new ScaleTransform(-1, 1, centerX, centerY));
					transform.Children.Add(new RotateTransform(90D, centerX, centerY));
					isRotatedRightAngle = true;
					break;
				case 8: // Rotate 270 clockwise
					transform.Children.Add(new RotateTransform(270D, centerX, centerY));
					isRotatedRightAngle = true;
					break;
			}

			// Resize.
			if ((0 < bitmapSource.Width) && (0 < bitmapSource.Height)) // For just in case
			{
				var factor = new[]
					{
						(outerSize.Width / (isRotatedRightAngle ? bitmapSource.Height : bitmapSource.Width)), // Scale factor of X
						(outerSize.Height / (isRotatedRightAngle ? bitmapSource.Width : bitmapSource.Height)) // Scale factor of Y
					}
					.Where(x => 0 < x)
					.DefaultIfEmpty(1D)
					.Min();

				transform.Children.Add(new ScaleTransform(factor, factor, centerX, centerY));
			}

			var bitmapTransformed = new TransformedBitmap();
			bitmapTransformed.BeginInit();
			bitmapTransformed.Transform = transform;
			bitmapTransformed.Source = bitmapSource;
			bitmapTransformed.EndInit();

			return bitmapTransformed;
		}
Ejemplo n.º 7
0
        /// <summary>
        /// Scales down and rotates a Wpf bitmap.
        /// </summary>
        /// <param name="sourceWpf">Original Wpf bitmap</param>
        /// <param name="scale">Uniform scaling factor</param>
        /// <param name="angle">Rotation angle</param>
        /// <returns>Scaled and rotated Wpf bitmap</returns>
        private static BitmapSource ScaleDownRotateBitmap(BitmapSource sourceWpf, double scale, int angle)
        {
            if (angle % 90 != 0)
            {
                throw new ArgumentException("Rotation angle should be a multiple of 90 degrees.", "angle");
            }

            // Do not upscale and no rotation.
            if ((float)scale >= 1.0f && angle == 0)
            {
                return sourceWpf;
            }

            // Set up the transformed thumbnail
            TransformedBitmap thumbWpf = new TransformedBitmap();
            thumbWpf.BeginInit();
            thumbWpf.Source = sourceWpf;
            TransformGroup transform = new TransformGroup();

            // Rotation
            if (Math.Abs(angle) % 360 != 0)
                transform.Children.Add(new RotateTransform(Math.Abs(angle)));

            // Scale
            if ((float)scale < 1.0f || angle < 0) // Only downscale
            {
                double xScale = Math.Min(1.0, Math.Max(1.0 / (double)sourceWpf.PixelWidth, scale));
                double yScale = Math.Min(1.0, Math.Max(1.0 / (double)sourceWpf.PixelHeight, scale));

                if (angle < 0)
                    xScale = -xScale;
                transform.Children.Add(new ScaleTransform(xScale, yScale));
            }

            // Apply the tranformation
            thumbWpf.Transform = transform;
            thumbWpf.EndInit();

            return thumbWpf;
        }
Ejemplo n.º 8
0
		private static TransformedBitmap CreateTransformedBitmap(BitmapSource source, VCProfile profile)
		{
			var transformedBitmap = new TransformedBitmap();
			transformedBitmap.BeginInit();
			transformedBitmap.Source = source;
			var transformGroup = new TransformGroup();
			transformGroup.Children.Add(new ScaleTransform(profile.FlipHorizontal ? -1 : 1, profile.FlipVertical ? -1 : 1));
			transformGroup.Children.Add(new RotateTransform(ConvertRotationToDegrees(profile.Rotation)));
			transformedBitmap.Transform = transformGroup;
			transformedBitmap.EndInit();
			transformedBitmap.Freeze();

			return transformedBitmap;
		}
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (   value == null || !(value is string)
                || (value as string).Substring (0, 7) == @"Images\"
                || File.Exists (value as string)
                || (value as string).Substring (0, 4).ToLower () == "http"
                || (value as string).Substring (0, 3).ToLower () == "ftp"
            )
                return (value) ;

            string [] sts =(value as string).Split (':') ;
            if ( sts.Length == 3 ) {
                sts [1] =sts [0] + ":" + sts [1] ;
                sts =sts.Where (w => w != sts [0]).ToArray () ;
            }
            BitmapImage bitmap =null ;
            if ( File.Exists (sts [0]) ) {
                FileStream zipStream =File.OpenRead (sts [0]) ;
                //using ( ZipArchive zip =new ZipArchive (zipStream) ) {
                //	ZipArchiveEntry icon =zip.GetEntry (sts [1]) ;
                //	Stream imgStream =icon.Open () ;
                //	Byte [] buffer =new Byte [icon.Length] ;
                //	imgStream.Read (buffer, 0, buffer.Length) ;
                //	var byteStream =new System.IO.MemoryStream (buffer) ;
                //	bitmap =new BitmapImage () ;
                //	bitmap.BeginInit () ;
                //	bitmap.CacheOption =BitmapCacheOption.OnLoad ;
                //	bitmap.StreamSource =byteStream ;
                //	bitmap.EndInit () ;
                //}
            }
            BitmapSource source =bitmap ;
            if (   bitmap.Format == PixelFormats.Bgra32
                || bitmap.Format == PixelFormats.Prgba64
                || bitmap.Format == PixelFormats.Rgba128Float
                || bitmap.Format == PixelFormats.Rgba64
            )
                source =AutoCropBitmap (bitmap) as BitmapSource ;

            TransformedBitmap scaledBitmap =new TransformedBitmap () ;
            scaledBitmap.BeginInit () ;
            scaledBitmap.Source =source ;
            double scale =100 / source.Width ;
            scaledBitmap.Transform =new ScaleTransform (scale, scale, source.Width / 2, source.Height / 2) ;
            scaledBitmap.EndInit () ;

            return (scaledBitmap) ;
        }
        /// <summary>
        /// 画像を拡大する
        /// </summary>
        /// <param name="scaleX"></param>
        /// <param name="scaleY"></param>
        /// <returns></returns>
        public TransformedBitmap scaleImage(double scaleX, double scaleY)
        {
            transimg = null;
            if (transimg == null) {
            transimg = new TransformedBitmap();
            transimg.BeginInit();
                transimg.Source = image;
                transimg.EndInit();
            }
            //transimg.BeginInit();
            if (scalex >= 0)
            {
                scalex += scaleX;
                scaley += scaleY;
            }
            else
            {
                scalex = 1.0;
                scaley = 1.0;
            }
            scale.ScaleX = scalex;
            scale.ScaleY = scaley;
            //transimg.Source = image;

            transimg.Transform = transgroup;
            //transimg.EndInit();

            Debug.WriteLine("x:" + scale.ScaleX);
            Debug.WriteLine("y:" + scale.ScaleY);
            Debug.WriteLine("pixel width after:" + transimg.PixelWidth);
            return transimg;
        }
Ejemplo n.º 11
0
		private byte[] Resize(byte[] bytes, int? width, int? height, int qualityLevel)
		{
			if (bytes == null)
				throw new Exception("Bytes parameter is null.");
			var image = new BitmapImage();
			image.BeginInit();
			if (width.HasValue)
				image.DecodePixelWidth = width.Value;
			if (height.HasValue)
				image.DecodePixelHeight = height.Value;
			image.StreamSource = new MemoryStream(bytes);
			image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
			image.EndInit();
			var transform = new TransformedBitmap();
			transform.BeginInit();
			transform.Source = image;
			transform.EndInit();
			return ToJpegBytes(transform, qualityLevel);
		}
Ejemplo n.º 12
0
		private void RotateButton_OnClick (object sender, RoutedEventArgs e)
			{
			TransformedBitmap RotatedSource = new TransformedBitmap();
			RotatedSource.BeginInit ();
			RotatedSource.Source = Source;
			RotatedSource.Transform = new RotateTransform (90);
			RotatedSource.EndInit ();
			Source = RotatedSource;
			advancedContentPresenter.Background = new ImageBrush(Source);
			advancedContentPresenter.FitToBackgroundImage ();
			}
Ejemplo n.º 13
0
 public static bool ReCreateThumbnail(string thumbnailImageSource, string thumbnailImageDest, int aThumbWidth, int aThumbHeight, int iRotate, bool aFastMode, bool autocreateLargeThumbs, bool fallBack, bool needOverride)
 {
     if (!needOverride && File.Exists(thumbnailImageDest) || (string.IsNullOrEmpty(thumbnailImageSource) || string.IsNullOrEmpty(thumbnailImageDest)) || (aThumbHeight <= 0 || aThumbWidth <= 0))
     return false;
       BitmapSource bitmapSource = (BitmapSource)null;
       Bitmap bitmap1 = (Bitmap)null;
       Bitmap bitmap2 = (Bitmap)null;
       BitmapFrame bitmapFrame = (BitmapFrame)null;
       Image aDrawingImage = (Image)null;
       TransformedBitmap transformedBitmap = (TransformedBitmap)null;
       TransformGroup transformGroup = (TransformGroup)null;
       bool flag = false;
       int num1 = (int)Thumbs.Quality;
       int num2 = aThumbWidth;
       Picture.MediaUrl = thumbnailImageSource;
       try
       {
     bitmapFrame = !fallBack ? BitmapFrame.Create(new Uri(Picture.MediaUrl), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None) : BitmapFrame.Create(new Uri(Picture.MediaUrl), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
     if (bitmapFrame.Thumbnail == null)
     {
       using (ShellObject shellObject = ShellObject.FromParsingName(thumbnailImageSource))
       {
     shellObject.get_Thumbnail().set_RetrievalOption((ShellThumbnailRetrievalOption)0);
     shellObject.get_Thumbnail().set_FormatOption((ShellThumbnailFormatOption)8);
     switch (num1)
     {
       case 0:
         bitmap1 = shellObject.get_Thumbnail().get_MediumBitmap();
         break;
       case 1:
         bitmap1 = shellObject.get_Thumbnail().get_LargeBitmap();
         break;
       case 2:
         bitmap1 = shellObject.get_Thumbnail().get_LargeBitmap();
         break;
       case 3:
         bitmap1 = shellObject.get_Thumbnail().get_ExtraLargeBitmap();
         break;
       case 4:
         bitmap1 = shellObject.get_Thumbnail().get_ExtraLargeBitmap();
         break;
     }
     if (!OSInfo.Win8OrLater())
     {
       switch (iRotate)
       {
         case 1:
           bitmap1.RotateFlip(RotateFlipType.Rotate90FlipNone);
           break;
         case 2:
           bitmap1.RotateFlip(RotateFlipType.Rotate180FlipNone);
           break;
         case 3:
           bitmap1.RotateFlip(RotateFlipType.Rotate270FlipNone);
           break;
       }
     }
     if (bitmap1 != null && !autocreateLargeThumbs)
     {
       int width = aThumbWidth;
       int height = aThumbHeight;
       double num3 = (double)bitmap1.Width / (double)bitmap1.Height;
       if (bitmap1.Width > bitmap1.Height)
         height = (int)Math.Floor((double)width / num3);
       else
         width = (int)Math.Floor(num3 * (double)height);
       try
       {
         GrabUtil.FileDelete(thumbnailImageDest);
       }
       catch (Exception ex)
       {
         Log.Error("Picture: Error deleting old thumbnail - {0}", (object)ex.Message);
       }
       bitmap2 = new Bitmap((Image)bitmap1, width, height);
       bitmap2.Save(thumbnailImageDest, Thumbs.ThumbCodecInfo, Thumbs.ThumbEncoderParams);
       File.SetAttributes(thumbnailImageDest, File.GetAttributes(thumbnailImageDest) | FileAttributes.Hidden);
       flag = true;
     }
     else
     {
       int width = aThumbWidth;
       int height = aThumbHeight;
       double num3 = (double)bitmap1.Width / (double)bitmap1.Height;
       if (bitmap1.Width > bitmap1.Height)
         height = (int)Math.Floor((double)width / num3);
       else
         width = (int)Math.Floor(num3 * (double)height);
       try
       {
         GrabUtil.FileDelete(thumbnailImageDest);
       }
       catch (Exception ex)
       {
         Log.Error("Picture: Error deleting old thumbnail - {0}", (object)ex.Message);
       }
       bitmap2 = new Bitmap((Image)bitmap1, width, height);
       bitmap2.Save(thumbnailImageDest, Thumbs.ThumbCodecInfo, Thumbs.ThumbEncoderParams);
       File.SetAttributes(thumbnailImageDest, File.GetAttributes(thumbnailImageDest) | FileAttributes.Hidden);
       flag = true;
     }
       }
     }
     else
     {
       BitmapMetadata meta = bitmapFrame.Metadata as BitmapMetadata;
       bitmapSource = bitmapFrame.Thumbnail;
       if (autocreateLargeThumbs)
       {
     if (bitmapSource != null)
     {
       transformedBitmap = new TransformedBitmap();
       transformedBitmap.BeginInit();
       transformedBitmap.Source = (BitmapSource)bitmapFrame;
       int pixelHeight = bitmapFrame.PixelHeight;
       int pixelWidth = bitmapFrame.PixelWidth;
       int num3 = bitmapFrame.PixelHeight * num2 / pixelWidth;
       double scaleX = (double)num2 / (double)pixelWidth;
       double scaleY = (double)num3 / (double)pixelHeight;
       transformGroup = new TransformGroup();
       transformGroup.Children.Add((Transform)new ScaleTransform(scaleX, scaleY));
       transformedBitmap.Transform = (Transform)transformGroup;
       transformedBitmap.EndInit();
       bitmapSource = (BitmapSource)transformedBitmap;
       bitmapSource = Picture.MetaOrientation(meta, bitmapSource);
       flag = Picture.BitmapFromSource(bitmapSource, thumbnailImageDest);
     }
       }
       else if (bitmapSource != null)
       {
     bitmapSource = Picture.MetaOrientation(meta, bitmapSource);
     flag = Picture.BitmapFromSource(bitmapSource, thumbnailImageDest);
       }
     }
       }
       catch (Exception ex1)
       {
     try
     {
       try
       {
     using (FileStream fileStream = new FileStream(thumbnailImageSource, FileMode.Open, FileAccess.Read))
     {
       using (aDrawingImage = Image.FromStream((Stream)fileStream, true, false))
         flag = Picture.CreateThumbnail(aDrawingImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
     }
       }
       catch (FileNotFoundException ex2)
       {
     flag = false;
       }
     }
     catch (Exception ex2)
     {
       Log.Warn("Picture: Fast loading of thumbnail {0} failed - trying safe fallback now", (object)thumbnailImageDest);
       try
       {
     try
     {
       using (FileStream fileStream = new FileStream(thumbnailImageDest, FileMode.Open, FileAccess.Read))
       {
         using (aDrawingImage = Image.FromStream((Stream)fileStream, true, false))
           flag = Picture.CreateThumbnail(aDrawingImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
       }
     }
     catch (Exception ex3)
     {
     }
       }
       catch (FileNotFoundException ex3)
       {
     flag = false;
       }
       catch (OutOfMemoryException ex3)
       {
     Log.Warn("Picture: Creating thumbnail failed - image format is not supported of {0}", (object)thumbnailImageSource);
     flag = false;
       }
       catch (Exception ex3)
       {
     Log.Info("Pictures: No thumbnail created for -- {0}", (object)thumbnailImageSource);
     flag = false;
       }
     }
       }
       finally
       {
     if (bitmap1 != null)
       ObjectMethods.SafeDispose((object)bitmap1);
     if (bitmapSource != null)
       ObjectMethods.SafeDispose((object)bitmapSource);
     if (transformedBitmap != null)
       ObjectMethods.SafeDispose((object)transformedBitmap);
     if (transformGroup != null)
       ObjectMethods.SafeDispose((object)transformGroup);
     if (bitmap2 != null)
       ObjectMethods.SafeDispose((object)bitmap2);
     if (Picture.MediaUrl != null)
       ObjectMethods.SafeDispose((object)Picture.MediaUrl);
     if (bitmapFrame != null)
       ObjectMethods.SafeDispose((object)bitmapFrame);
     if (aDrawingImage != null)
       ObjectMethods.SafeDispose((object)aDrawingImage);
       }
       return flag;
 }
Ejemplo n.º 14
0
        public static BitmapSource Transform(BitmapSource source, Transform transform)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (transform == null) throw new ArgumentNullException("transform");

            TransformedBitmap target = new TransformedBitmap();
            target.BeginInit();
            target.Source = source;
            target.Transform = transform;
            target.EndInit();
            target.Freeze();

            return CloneImage(target);
        }
Ejemplo n.º 15
0
 private TransformedBitmap getTransformedBitmap(BitmapImage bi, double angle)
 {
     TransformedBitmap tb = new TransformedBitmap();
     tb.BeginInit();
     tb.Source = bi;
     tb.Transform = new RotateTransform(angle);
     tb.EndInit();
     return tb;
 }
        /// <summary>
        /// 画像を回転させる
        /// </summary>
        /// <returns></returns>
        public TransformedBitmap rotateImage(bool isLeft)
        {
            transimg = new TransformedBitmap();
            transimg.BeginInit();

            if (isLeft)
            {
                rotate.Angle -= 90;
            }
            else
            {
            rotate.Angle += 90;
            }

            if (rotate.Angle == 360 || rotate.Angle == -360)
            {
                rotate.Angle = 0;
            }

            transimg.Source = image;
            transimg.Transform = transgroup;
            transimg.EndInit();
            Debug.WriteLine("rotate"+ rotate.Angle);
            return transimg;
        }
Ejemplo n.º 17
0
        private Image initializeProjectileImage(Uri spriteUri, bool rotate = false)
        {
            Image newImage = new Image();

            newImage.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            newImage.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            newImage.Margin = getRandomEdge();

            TransformedBitmap temp = new TransformedBitmap();
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = spriteUri;
            bi.EndInit();
            temp.BeginInit();
            temp.Source = bi;
            RotateTransform transform;
            if (rotate)
            {
                transform = new RotateTransform(rand.Next(0, 3) * 90);
            }
            else
            {
                transform = new RotateTransform(0);
            }
            temp.Transform = transform;
            temp.EndInit();
            newImage.Source = temp;

            return newImage;
        }
Ejemplo n.º 18
0
        private ImageSource GetBitmapSource(LoadImageRequest loadTask, DisplayOptions loadType)
        {
            DisplayOptions lt = loadType;
            Image image = loadTask.Image;
            string source = loadTask.Source;
            string nSource = source;
            string cacheFile = Path.Combine(AppStateSettings.CacheFolder, "Media", nSource.GetSHA1Hash().ToString() + "s" + loadTask.CachHeight + ".png"); // REVIEW TODO: Used Path instead of String concat.

            if (File.Exists(cacheFile))
            {
                nSource = cacheFile;
                lt = DisplayOptions.FullResolution;
                //return new BitmapImage(new Uri("file://" + cacheFile));
            }

            ImageSource imageSource = null;

            if (!string.IsNullOrWhiteSpace(nSource))
            {
                Stream imageStream = null;

                SourceType sourceType = SourceType.LocalDisk;

                image.Dispatcher.Invoke(new ThreadStart(delegate
                {
                    sourceType = Loader.GetSourceType(image);
                }));


                try
                {
                    if (loadTask.Stream == null)
                    {
                        ILoader loader = LoaderFactory.CreateLoader(sourceType, nSource);
                        imageStream = loader.Load(nSource);
                        loadTask.Stream = imageStream;
                    }
                    else
                    {
                        imageStream = new MemoryStream();
                        loadTask.Stream.Position = 0;
                        loadTask.Stream.CopyTo(imageStream);
                        imageStream.Position = 0;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                if (imageStream != null)
                {
                    try
                    {
                        if (lt == DisplayOptions.Preview)
                        {
                            BitmapFrame bitmapFrame = BitmapFrame.Create(imageStream);
                            imageSource = bitmapFrame.Thumbnail;

                            if (imageSource == null) // Preview it is not embedded into the file
                            {
                                // we'll make a thumbnail image then ... (too bad as the pre-created one is FAST!)
                                TransformedBitmap thumbnail = new TransformedBitmap();
                                thumbnail.BeginInit();
                                thumbnail.Source = bitmapFrame as BitmapSource;

                                // we'll make a reasonable sized thumnbail with a height of 240
                                int pixelH = bitmapFrame.PixelHeight;
                                int pixelW = bitmapFrame.PixelWidth;
                                int decodeH = (int)loadTask.CachHeight;
                                int decodeW = (bitmapFrame.PixelWidth * decodeH) / pixelH;
                                double scaleX = decodeW / (double)pixelW;
                                double scaleY = decodeH / (double)pixelH;
                                TransformGroup transformGroup = new TransformGroup();
                                transformGroup.Children.Add(new ScaleTransform(scaleX, scaleY));
                                thumbnail.Transform = transformGroup;
                                thumbnail.EndInit();

                                // this will disconnect the stream from the image completely ...
                                WriteableBitmap writable = new WriteableBitmap(thumbnail);


                                BitmapFrame frame = BitmapFrame.Create(writable);
                                var encoder = new PngBitmapEncoder();
                                encoder.Frames.Add(frame);

                                using (var stream = File.Create(cacheFile))
                                {
                                    encoder.Save(stream);
                                }


                                writable.Freeze();
                                imageSource = writable;
                            }
                        }
                        else if (lt == DisplayOptions.FullResolution)
                        {
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.BeginInit();
                            bitmapImage.StreamSource = imageStream;
                            bitmapImage.EndInit();
                            imageSource = bitmapImage;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }

                if (imageSource == null)
                {
                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, true);
                    }));
                }
                else
                {
                    imageSource.Freeze();

                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, false);
                    }));
                }
            }
            else
            {
                image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Loader.SetErrorDetected(image, false);
                }));
            }

            return imageSource;
        }
Ejemplo n.º 19
0
        private ImageSource GetBitmapSource(LoadImageRequest loadTask, DisplayOptions loadType)
        {
            Image image = loadTask.Image;
            object source = loadTask.Source;
            ImageSource imageSource = null;

            if (source != null)
            {
                Stream imageStream = null;

                SourceType sourceType = SourceType.LocalDisk;

                image.Dispatcher.Invoke(new ThreadStart(delegate
                {
                    sourceType = Loader.GetSourceType(image);
                }));

                try
                {
                    if (loadType != DisplayOptions.VideoPreview)
                    {
                        if (loadTask.Stream == null)
                        {
                            ILoader loader = LoaderFactory.CreateLoader(sourceType);
                            imageStream = loader.Load(source);
                            loadTask.Stream = imageStream;
                        }
                        else
                        {
                            imageStream = new MemoryStream();
                            loadTask.Stream.Position = 0;
                            loadTask.Stream.CopyTo(imageStream);
                            imageStream.Position = 0;
                        }
                    }
                    else if (sourceType == SourceType.ZipFile)
                    {
                        throw new InvalidOperationException("Can't load video preview from zip file.");
                    }
                }
                catch (Exception) { }

                if (imageStream != null || loadType == DisplayOptions.VideoPreview)
                {
                    try
                    {
                        if (loadType == DisplayOptions.Preview)
                        {
                            BitmapFrame bitmapFrame = BitmapFrame.Create(imageStream);
                            int rotation = GetRotation(bitmapFrame.Metadata as BitmapMetadata);

                            if (bitmapFrame.Thumbnail != null)
                            {
                                BitmapSource src = bitmapFrame.Thumbnail;
                                // crop black bars if necessary
                                double ratio = (double)bitmapFrame.PixelWidth / bitmapFrame.PixelHeight;
                                double thumbRatio = (double)src.PixelWidth / src.PixelHeight;
                                if (Math.Abs(ratio - thumbRatio) >= 0.01)
                                {
                                    if (ratio > thumbRatio) // crop top/bottom
                                    {
                                        int newHeight = (int)(src.PixelWidth / ratio);
                                        int top = (src.PixelHeight - newHeight) / 2;
                                        src = new CroppedBitmap(src, new Int32Rect(0, top, src.PixelWidth, newHeight));
                                    }
                                    else // crop left/right
                                    {
                                        int newWidth = (int)(src.PixelHeight * ratio);
                                        int left = (src.PixelWidth - newWidth) / 2;
                                        src = new CroppedBitmap(src, new Int32Rect(left, 0, newWidth, src.PixelHeight));
                                    }
                                }

                                TransformedBitmap thumbnail = new TransformedBitmap();
                                thumbnail.BeginInit();
                                thumbnail.Source = src;
                                TransformGroup transformGroup = new TransformGroup();
                                // rotate according to metadata
                                transformGroup.Children.Add(new RotateTransform(rotation));
                                thumbnail.Transform = transformGroup;
                                thumbnail.EndInit();
                                imageSource = thumbnail;
                            }
                            else // Preview it is not embedded into the file
                            {
                                // we'll make a thumbnail image then ... (too bad as the pre-created one is FAST!)
                                TransformedBitmap thumbnail = new TransformedBitmap();
                                thumbnail.BeginInit();
                                thumbnail.Source = bitmapFrame as BitmapSource;

                                // we'll make a reasonable sized thumnbail with a height of 240
                                int pixelH = bitmapFrame.PixelHeight;
                                int pixelW = bitmapFrame.PixelWidth;
                                int decodeH = 240;
                                int decodeW = (pixelW * decodeH) / pixelH;
                                double scaleX = decodeW / (double)pixelW;
                                double scaleY = decodeH / (double)pixelH;
                                TransformGroup transformGroup = new TransformGroup();
                                transformGroup.Children.Add(new ScaleTransform(scaleX, scaleY));
                                transformGroup.Children.Add(new RotateTransform(rotation));
                                thumbnail.Transform = transformGroup;
                                thumbnail.EndInit();

                                // this will disconnect the stream from the image completely ...
                                WriteableBitmap writable = new WriteableBitmap(thumbnail);
                                writable.Freeze();
                                imageSource = writable;
                            }
                        }
                        else if (loadType == DisplayOptions.Combined || loadType == DisplayOptions.FullResolution)
                        {
                            BitmapFrame bitmapFrame = BitmapFrame.Create(imageStream);
                            int rotation = GetRotation(bitmapFrame.Metadata as BitmapMetadata);

                            TransformedBitmap bitmapImage = new TransformedBitmap();
                            bitmapImage.BeginInit();
                            bitmapImage.Source = bitmapFrame as BitmapSource;
                            TransformGroup transformGroup = new TransformGroup();
                            transformGroup.Children.Add(new RotateTransform(rotation));
                            bitmapImage.Transform = transformGroup;
                            bitmapImage.EndInit();

                            WriteableBitmap writable = new WriteableBitmap(bitmapImage);
                            writable.Freeze();

                            imageSource = writable;
                        }
                        else if (loadType == DisplayOptions.VideoPreview)
                        {
                            var player = new MediaPlayer { Volume = 0, ScrubbingEnabled = true };

                            Uri uri;
                            if (loadTask.Source is string)
                                uri = new Uri(loadTask.Source as string);
                            else if (loadTask.Source is Uri)
                                uri = loadTask.Source as Uri;
                            else
                                throw new InvalidOperationException();

                            player.Open(uri);
                            player.Pause();
                            player.Position = new TimeSpan(0, 0, 20); // go to 20 seconds (if the video is shorter, a black image will be captured)

                            Thread.Sleep(1000);

                            int i = 0;
                            while (i < 10 && (player.NaturalDuration.TimeSpan.TotalSeconds* player.BufferingProgress) <= 20)
                            {
                                Thread.Sleep(100);
                                i++;
                            }

                            var pixelW = player.NaturalVideoWidth;
                            var pixelH = player.NaturalVideoHeight;

                            int decodeH = 240;
                            int decodeW = (pixelW * decodeH) / pixelH;

                            var rtb = new RenderTargetBitmap(decodeW, decodeH, 96, 96, PixelFormats.Pbgra32);
                            DrawingVisual dv = new DrawingVisual();

                            using (DrawingContext dc = dv.RenderOpen())
                                dc.DrawVideo(player, new Rect(0, 0, decodeW, decodeH));

                            rtb.Render(dv);
                            imageSource = (ImageSource)BitmapFrame.Create(rtb).GetCurrentValueAsFrozen();
                            player.Close();
                        }
                    }
                    catch (Exception) { }
                }

                if (imageSource == null)
                {
                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, true);
                    }));
                }
                else
                {
                    imageSource.Freeze();

                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, false);
                    }));
                }
            }
            else
            {
                image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Loader.SetErrorDetected(image, false);
                }));
            }

            return imageSource;
        }
Ejemplo n.º 20
0
        internal override void FinalizeCreation()
        {
            _bitmapInit.EnsureInitializedComplete();
            Uri uri = UriSource;

            if (_baseUri != null)
            {
                uri = new Uri(_baseUri, UriSource);
            }

            if ((CreateOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
            {
                ImagingCache.RemoveFromImageCache(uri);
            }

            BitmapImage bitmapImage = CheckCache(uri);

            if (bitmapImage != null &&
                bitmapImage.CheckAccess() &&
                bitmapImage.SourceRect.Equals(SourceRect) &&
                bitmapImage.DecodePixelWidth == DecodePixelWidth &&
                bitmapImage.DecodePixelHeight == DecodePixelHeight &&
                bitmapImage.Rotation == Rotation &&
                (bitmapImage.CreateOptions & BitmapCreateOptions.IgnoreColorProfile) ==
                (CreateOptions & BitmapCreateOptions.IgnoreColorProfile)
                )
            {
                _syncObject = bitmapImage.SyncObject;
                lock (_syncObject)
                {
                    WicSourceHandle   = bitmapImage.WicSourceHandle;
                    IsSourceCached    = bitmapImage.IsSourceCached;
                    _convertedDUCEPtr = bitmapImage._convertedDUCEPtr;

                    //
                    // We nee d to keep the strong reference to the cached image for a few reasons:
                    //
                    //    The application may release the original cached image and then keep a
                    //    reference to this image only, in which case, the cache can be collected.
                    //    This will cause a few undesirable results:
                    //    1. The application may choose to decode the same URI again in which case
                    //       we will not retrieve it from the cache even though we have a copy already
                    //       decoded.
                    //    2. The original cached image holds onto the file stream indirectly which if
                    //       collected can cause bad behavior if the entire image is not loaded into
                    //       memory.
                    //
                    _cachedBitmapImage = bitmapImage;
                }
                UpdateCachedSettings();
                return;
            }

            BitmapDecoder decoder = null;

            if (_decoder == null)
            {
                // Note: We do not want to insert in the cache if there is a chance that
                //       the decode pixel width/height may cause the decoder LOD to change
                decoder = BitmapDecoder.CreateFromUriOrStream(
                    _baseUri,
                    UriSource,
                    StreamSource,
                    CreateOptions & ~BitmapCreateOptions.DelayCreation,
                    BitmapCacheOption.None, // do not cache the frames since we will do that here
                    _uriCachePolicy,
                    false
                    );

                if (decoder.IsDownloading)
                {
                    _isDownloading             = true;
                    _decoder                   = decoder;
                    decoder.DownloadProgress  += OnDownloadProgress;
                    decoder.DownloadCompleted += OnDownloadCompleted;
                    decoder.DownloadFailed    += OnDownloadFailed;
                }
                else
                {
                    Debug.Assert(decoder.SyncObject != null);
                }
            }
            else
            {
                // We already had a decoder, meaning we were downloading
                Debug.Assert(!_decoder.IsDownloading);
                decoder  = _decoder;
                _decoder = null;
            }

            if (decoder.Frames.Count == 0)
            {
                throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames));
            }

            BitmapFrame  frame  = decoder.Frames[0];
            BitmapSource source = frame;

            Int32Rect sourceRect = SourceRect;

            if (sourceRect.X == 0 && sourceRect.Y == 0 &&
                sourceRect.Width == source.PixelWidth &&
                sourceRect.Height == source.PixelHeight)
            {
                sourceRect = Int32Rect.Empty;
            }

            if (!sourceRect.IsEmpty)
            {
                CroppedBitmap croppedSource = new CroppedBitmap();
                croppedSource.BeginInit();
                croppedSource.Source     = source;
                croppedSource.SourceRect = sourceRect;
                croppedSource.EndInit();

                source = croppedSource;
                if (_isDownloading)
                {
                    // Unregister the download events because this is a dummy image. See comment below.
                    source.UnregisterDownloadEventSource();
                }
            }

            int finalWidth  = DecodePixelWidth;
            int finalHeight = DecodePixelHeight;

            if (finalWidth == 0 && finalHeight == 0)
            {
                finalWidth  = source.PixelWidth;
                finalHeight = source.PixelHeight;
            }
            else if (finalWidth == 0)
            {
                finalWidth = (source.PixelWidth * finalHeight) / source.PixelHeight;
            }
            else if (finalHeight == 0)
            {
                finalHeight = (source.PixelHeight * finalWidth) / source.PixelWidth;
            }

            if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight ||
                Rotation != Rotation.Rotate0)
            {
                TransformedBitmap transformedSource = new TransformedBitmap();
                transformedSource.BeginInit();
                transformedSource.Source = source;

                TransformGroup transformGroup = new TransformGroup();

                if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight)
                {
                    int oldWidth  = source.PixelWidth;
                    int oldHeight = source.PixelHeight;

                    Debug.Assert(oldWidth > 0 && oldHeight > 0);

                    transformGroup.Children.Add(
                        new ScaleTransform(
                            (1.0 * finalWidth) / oldWidth,
                            (1.0 * finalHeight) / oldHeight));
                }

                if (Rotation != Rotation.Rotate0)
                {
                    double rotation = 0.0;

                    switch (Rotation)
                    {
                    case Rotation.Rotate0:
                        rotation = 0.0;
                        break;

                    case Rotation.Rotate90:
                        rotation = 90.0;
                        break;

                    case Rotation.Rotate180:
                        rotation = 180.0;
                        break;

                    case Rotation.Rotate270:
                        rotation = 270.0;
                        break;

                    default:
                        Debug.Assert(false);
                        break;
                    }

                    transformGroup.Children.Add(new RotateTransform(rotation));
                }

                transformedSource.Transform = transformGroup;

                transformedSource.EndInit();

                source = transformedSource;
                if (_isDownloading)
                {
                    //
                    // If we're currently downloading, then the BitmapFrameDecode isn't actually
                    // the image, it's just a 1x1 placeholder. The chain we're currently building
                    // will be replaced with another chain once download completes, so there's no
                    // need to have this chain handle DownloadCompleted.
                    //
                    // Having this chain handle DownloadCompleted is actually a bad thing. Because
                    // the dummy is just 1x1, the TransformedBitmap we're building here will have
                    // a large scaling factor (to scale the image from 1x1 up to whatever
                    // DecodePixelWidth/Height specifies). When the TransformedBitmap receives
                    // DownloadCompleted from the BFD, it will call into WIC to create a new
                    // bitmap scaler using the same large scaling factor, which can produce a huge
                    // bitmap (since the BFD is now no longer 1x1). This problem is made worse if
                    // this BitmapImage has BitmapCacheOption.OnLoad, since that will put a
                    // CachedBitmap after the TransformedBitmap. When DownloadCompleted propagates
                    // from the TransformedBitmap down to the CachedBitmap, the CachedBitmap will
                    // call CreateBitmapFromSource using the TransformedBitmap, which calls
                    // CopyPixels on the huge TransformedBitmap. We want to avoid chewing up the
                    // CPU and the memory, so we unregister the download event handlers here.
                    //
                    source.UnregisterDownloadEventSource();
                }
            }

            //
            // If the original image has a color profile and IgnoreColorProfile is not one of the create options,
            // apply the profile so bits are color-corrected.
            //
            if ((CreateOptions & BitmapCreateOptions.IgnoreColorProfile) == 0 &&
                frame.ColorContexts != null &&
                frame.ColorContexts[0] != null &&
                frame.ColorContexts[0].IsValid &&
                source.Format.Format != PixelFormatEnum.Extended
                )
            {
                // NOTE: Never do this for a non-MIL pixel format, because the format converter has
                // special knowledge to deal with the profile

                PixelFormat  duceFormat   = BitmapSource.GetClosestDUCEFormat(source.Format, source.Palette);
                bool         changeFormat = (source.Format != duceFormat);
                ColorContext destinationColorContext;

                // We need to make sure, we can actually create the ColorContext for the destination duceFormat
                // If the duceFormat is gray or scRGB, the following is not supported, so we cannot
                // create the ColorConvertedBitmap
                try
                {
                    destinationColorContext = new ColorContext(duceFormat);
                }
                catch (NotSupportedException)
                {
                    destinationColorContext = null;
                }

                if (destinationColorContext != null)
                {
                    bool conversionSuccess = false;
                    bool badColorContext   = false;

                    // First try if the color converter can handle the source format directly
                    // Its possible that the color converter does not support certain pixelformats, so put a try/catch here.
                    try
                    {
                        ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap(
                            source,
                            frame.ColorContexts[0],
                            destinationColorContext,
                            duceFormat
                            );

                        source = colorConvertedBitmap;
                        if (_isDownloading)
                        {
                            // Unregister the download events because this is a dummy image. See comment above.
                            source.UnregisterDownloadEventSource();
                        }
                        conversionSuccess = true;
                    }
                    catch (NotSupportedException)
                    {
                    }
                    catch (FileFormatException)
                    {
                        // If the file contains a bad color context, we catch the exception here
                        // and don't bother trying the color conversion below, since color transform isn't possible
                        // with the given color context.
                        badColorContext = true;
                    }

                    if (!conversionSuccess && !badColorContext && changeFormat)
                    {   // If the conversion failed, we first use
                        // a FormatConvertedBitmap, and then Color Convert that one...
                        FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(source, duceFormat, source.Palette, 0.0);

                        ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap(
                            formatConvertedBitmap,
                            frame.ColorContexts[0],
                            destinationColorContext,
                            duceFormat
                            );

                        source = colorConvertedBitmap;
                        if (_isDownloading)
                        {
                            // Unregister the download events because this is a dummy image. See comment above.
                            source.UnregisterDownloadEventSource();
                        }
                    }
                }
            }

            if (CacheOption != BitmapCacheOption.None)
            {
                try
                {
                    // The bitmaps bits could be corrupt, and this will cause an exception if the CachedBitmap forces a decode.
                    CachedBitmap cachedSource = new CachedBitmap(source, CreateOptions & ~BitmapCreateOptions.DelayCreation, CacheOption);
                    source = cachedSource;
                    if (_isDownloading)
                    {
                        // Unregister the download events because this is a dummy image. See comment above.
                        source.UnregisterDownloadEventSource();
                    }
                }
                catch (Exception e)
                {
                    RecoverFromDecodeFailure(e);
                    CreationCompleted = true; // we're bailing out because the decode failed
                    return;
                }
            }

            // If CacheOption == OnLoad, no need to keep the stream around
            if (decoder != null && CacheOption == BitmapCacheOption.OnLoad)
            {
                decoder.CloseStream();
            }
            else if (CacheOption != BitmapCacheOption.OnLoad)
            {
                //ensure that we don't GC the source
                _finalSource = source;
            }

            WicSourceHandle = source.WicSourceHandle;
            IsSourceCached  = source.IsSourceCached;

            CreationCompleted = true;
            UpdateCachedSettings();

            // Only insert in the imaging cache if download is complete
            if (!IsDownloading)
            {
                InsertInCache(uri);
            }
        }
Ejemplo n.º 21
0
        private static Ruban GenRuban(string str, FrameworkElement uc, Base.LibGroup tuple, bool gray)
        {
            Ruban rb = null;
            if (str == "C0")
                rb = new Ruban(uc.TryFindResource("tuxCard000") as Image, 0);
            else if (str.StartsWith("C"))
            {
                ushort ut = ushort.Parse(str.Substring(1));
                Tux tux = tuple.TL.DecodeTux(ut);
                if (tux != null)
                {
                    Image image = uc.TryFindResource("tuxCard" + tux.Code) as Image;
                    if (image != null)
                        rb = new Ruban(image, ut);
                    else
                        rb = new Ruban(uc.TryFindResource("tuxCard000") as Image, ut);
                }
                else
                    rb = new Ruban(uc.TryFindResource("tuxCard000") as Image, ut);
                rb.ToolTip = Tips.IchiDisplay.GetTuxTip(tuple, ut);
            }
            else if (str.StartsWith("M"))
            {
                ushort ut = ushort.Parse(str.Substring(1));
                NMB nmb = NMBLib.Decode(ut, tuple.ML, tuple.NL);
                if (nmb != null)
                {
                    Image image = uc.TryFindResource("monCard" + nmb.Code) as Image;
                    Image2Gray(ref image, gray);
                    if (image != null)
                        rb = new Ruban(image, ut);
                    else
                        rb = new Ruban(uc.TryFindResource("monCard000") as Image, ut);
                    if (nmb.IsMonster())
                        rb.ToolTip = Tips.IchiDisplay.GetMonTip(tuple, NMBLib.OriginalMonster(ut));
                    else if (nmb.IsNPC())
                        rb.ToolTip = Tips.IchiDisplay.GetNPCTip(tuple, NMBLib.OriginalNPC(ut));
                }
                else
                    rb = new Ruban(uc.TryFindResource("monCard000") as Image, ut);
            }
            else if (str.StartsWith("H0"))
                rb = new Ruban(uc.TryFindResource("hroCard000") as Image, 0);
            else if (str.StartsWith("H"))
            {
                ushort ut = ushort.Parse(str.Substring("H".Length));
                Hero hro = tuple.HL.InstanceHero(ut);
                if (hro != null)
                {
                    Image image = uc.TryFindResource("hroCard" + hro.Ofcode) as Image;
                    Image2Gray(ref image, gray);
                    if (image != null)
                        rb = new Ruban(image, ut);
                    else
                        rb = new Ruban(uc.TryFindResource("hroCard000") as Image, ut);
                }
                else rb = new Ruban(uc.TryFindResource("hroCard000") as Image, ut);
                rb.ToolTip = Tips.IchiDisplay.GetHeroTip(tuple, ut);
            }
            else if (str.StartsWith("D"))
            {
                ushort ut = ushort.Parse(str.Substring("D".Length));
                Image image = uc.TryFindResource("diceImg" + ut) as Image;
                if (image != null)
                    rb = new Ruban(image, ut);
                else
                    rb = new Ruban(uc.TryFindResource("diceImg000") as Image, ut);
                rb.ToolTip = null;
            }
            else if (str.StartsWith("G"))
            {
                ushort dbSerial = ushort.Parse(str.Substring("G".Length));
                Tux tux = tuple.TL.EncodeTuxDbSerial(dbSerial);
                if (tux != null)
                {
                    Image image = uc.TryFindResource("tuxCard" + tux.Code) as Image;
                    Image2Gray(ref image, gray);
                    if (image != null)
                        rb = new Ruban(image, dbSerial);
                    else
                        rb = new Ruban(uc.TryFindResource("tuxCard000") as Image, dbSerial);
                    rb.ToolTip = Tips.IchiDisplay.GetTuxDbSerialTip(tuple, dbSerial);
                }
                else
                    rb = new Ruban(uc.TryFindResource("tuxCard000") as Image, dbSerial);
            }
            else if (str.StartsWith("I"))
            {
                ushort ut = ushort.Parse(str.Substring("I".Length));
                Image image = uc.TryFindResource("exspCard" + ut) as Image;
                if (image != null)
                    rb = new Ruban(image, ut);
                else
                    rb = new Ruban(uc.TryFindResource("diceImg000") as Image, ut);
                rb.ToolTip = Tips.IchiDisplay.GetExspTip(tuple, "I" + ut);
            }
            else if (str.StartsWith("E0"))
            {
                Image image = uc.TryFindResource("eveCard000") as Image;
                image.RenderTransform = new RotateTransform(90);
                rb = new Ruban(image, 0);
            }
            else if (str.StartsWith("E"))
            {
                ushort ut = ushort.Parse(str.Substring("E".Length));
                Evenement eve = tuple.EL.DecodeEvenement(ut);
                Image image = uc.TryFindResource("eveCard" + eve.Code) as Image
                    ?? uc.TryFindResource("eveCard000") as Image;

                FormatConvertedBitmap bp = new FormatConvertedBitmap();
                bp.BeginInit();
                bp.Source = image.Source as BitmapSource;
                bp.EndInit();

                TransformedBitmap tb = new TransformedBitmap();
                tb.BeginInit();
                tb.Source = bp;
                tb.Transform = new RotateTransform(90);
                tb.EndInit();

                image = new Image() { Source = tb };
                Image2Gray(ref image, gray);
                rb = new Ruban(image, ut);
                rb.ToolTip = Tips.IchiDisplay.GetEveTip(tuple, ut);
            }
            else if (str.StartsWith("R"))
            {
                ushort ut = ushort.Parse(str.Substring("R".Length));
                Image image = uc.TryFindResource("runeCard" + ut) as Image;
                if (image != null)
                    rb = new Ruban(image, ut);
                else
                    rb = new Ruban(uc.TryFindResource("runeCard000") as Image, ut);
                rb.ToolTip = Tips.IchiDisplay.GetRuneTip(tuple, ut);
            }
            else if (str.StartsWith("V"))
            {
                ushort ut = ushort.Parse(str.Substring("V".Length));
                Image image = uc.TryFindResource("fiveImg" + ut) as Image;
                if (image != null)
                    rb = new Ruban(image, ut);
                else
                    rb = new Ruban(uc.TryFindResource("diceImg000") as Image, ut);
                rb.ToolTip = Tips.IchiDisplay.GetFiveTip(tuple, ut);
            }
            return rb;
        }
Ejemplo n.º 22
0
        private ImageSource GetBitmapSource(LoadImageRequest loadTask, DisplayOptions loadType)
        {
            Image image = loadTask.Image;
            string source = loadTask.Source;

            ImageSource imageSource = null;

            if (!string.IsNullOrWhiteSpace(source))
            {
                Stream imageStream = null;

                SourceType sourceType = SourceType.LocalDisk;

                image.Dispatcher.Invoke(new ThreadStart(delegate
                {
                    sourceType = Loader.GetSourceType(image);
                }));

                try
                {
                    if (loadTask.Stream == null)
                    {
                        ILoader loader = LoaderFactory.CreateLoader(sourceType);
                        imageStream = loader.Load(source);
                        loadTask.Stream = imageStream;
                    }
                    else
                    {
                        imageStream = new MemoryStream();
                        loadTask.Stream.Position = 0;
                        loadTask.Stream.CopyTo(imageStream);
                        imageStream.Position = 0;
                    }
                }
                catch (Exception) { }

                if (imageStream != null)
                {
                    try
                    {
                        if (loadType == DisplayOptions.Preview)
                        {
                            BitmapFrame bitmapFrame = BitmapFrame.Create(imageStream);
                            imageSource = bitmapFrame.Thumbnail;

                            if (imageSource == null) // Preview it is not embedded into the file
                            {
                                // we'll make a thumbnail image then ... (too bad as the pre-created one is FAST!)
                                TransformedBitmap thumbnail = new TransformedBitmap();
                                thumbnail.BeginInit();
                                thumbnail.Source = bitmapFrame as BitmapSource;

                                // we'll make a reasonable sized thumnbail with a height of 240
                                int pixelH = bitmapFrame.PixelHeight;
                                int pixelW = bitmapFrame.PixelWidth;
                                int decodeH = 240;
                                int decodeW = (bitmapFrame.PixelWidth * decodeH) / pixelH;
                                double scaleX = decodeW / (double)pixelW;
                                double scaleY = decodeH / (double)pixelH;
                                TransformGroup transformGroup = new TransformGroup();
                                transformGroup.Children.Add(new ScaleTransform(scaleX, scaleY));
                                thumbnail.Transform = transformGroup;
                                thumbnail.EndInit();

                                // this will disconnect the stream from the image completely ...
                                WriteableBitmap writable = new WriteableBitmap(thumbnail);
                                writable.Freeze();
                                imageSource = writable;
                            }
                        }
                        else if (loadType == DisplayOptions.FullResolution)
                        {
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.BeginInit();
                            bitmapImage.StreamSource = imageStream;
                            bitmapImage.EndInit();
                            imageSource = bitmapImage;
                        }
                    }
                    catch (Exception) { }
                }

                if (imageSource == null)
                {
                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, true);
                    }));
                }
                else
                {
                    imageSource.Freeze();

                    image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                    {
                        Loader.SetErrorDetected(image, false);
                    }));
                }
            }
            else
            {
                image.Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Loader.SetErrorDetected(image, false);
                }));
            }

            return imageSource;
        }
Ejemplo n.º 23
0
		BitmapSource GetBitmapSourceFromFile (String FileName, double PictureWidth, double PictureHeight)
			{
			BitmapImage InputBitmapImage = new BitmapImage ();
			InputBitmapImage.BeginInit ();
			InputBitmapImage.UriSource = new Uri (FileName);
			InputBitmapImage.EndInit ();
			double Width = InputBitmapImage.PixelWidth;
			double Height = InputBitmapImage.PixelHeight;
			double InputAspectRatio = Width / Height;
			double FrameAspectRatio = (double) PictureWidth / (double) PictureHeight;
			double ScalingX = PictureWidth / Width;
			double ScalingY = PictureHeight / Height;
			//if (InputAspectRatio >= FrameAspectRatio)
			//    Scaling = PictureWidth / Width;
			//else
			//    Scaling = PictureHeight / Height;
			TransformedBitmap ResultBitmapImage = new TransformedBitmap ();
			ResultBitmapImage.BeginInit ();
			ResultBitmapImage.Source = InputBitmapImage;
			ResultBitmapImage.Transform = new ScaleTransform (ScalingX, ScalingY, Width / 2, Height / 2);
			ResultBitmapImage.EndInit ();
			return ResultBitmapImage;

			}
Ejemplo n.º 24
0
		private BitmapSource GetBildBitmapSourceFromContentRow (DataRow FrameContentRow, DataRow FrameRow, Rect DrawingRect)
			{
			if (m_Pkg == null)
				return null;
			List<String> AvailablePictures = m_Pkg.GetOriginalDocumentNamesInPackage ();
			String PictureName = String.Empty;
			if (FrameRow ["Typ"].ToString () == "Bild")
				PictureName = FrameContentRow ["NameID"].ToString ();
			if (FrameRow ["Typ"].ToString () == "Logo")
				PictureName = FrameContentRow ["PictureName"].ToString ();
			if (FrameRow ["Typ"].ToString () == "Video")
				{
				PictureName = "VideoDesignPattern";
				AvailablePictures.Add ("\\VideoDesignPattern.png");
				}
			if (String.IsNullOrEmpty (PictureName))
				return null;

			foreach (String AvailablePicture in AvailablePictures)
				{
				try
					{
					if (AvailablePicture.IndexOf ("\\" + PictureName + ".", StringComparison.OrdinalIgnoreCase) == -1)
						continue;
					String Extension = Path.GetExtension (AvailablePicture.ToUpper ());
					BitmapImage InputBitmapImage = new BitmapImage ();
					if (PictureName == "VideoDesignPattern")
						{
						InputBitmapImage.BeginInit ();
						InputBitmapImage.UriSource = new Uri ("pack://application:,,,/CVM;Component/Resources/VideoDesignPattern.png");
						InputBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
						InputBitmapImage.EndInit ();
						}
					else
						{
						Stream BitmapSourceStream =  m_Pkg.GetStreamFromOriginalDocumentName (AvailablePicture);
						InputBitmapImage.BeginInit ();
						InputBitmapImage.StreamSource = BitmapSourceStream;
						InputBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
						InputBitmapImage.EndInit ();
						BitmapSourceStream.Close ();
						BitmapSourceStream.Dispose ();
						}

					double Width = InputBitmapImage.PixelWidth;
					double Height = InputBitmapImage.PixelHeight;
					double InputAspectRatio = Width / Height;
					double FrameAspectRatio = (double) DrawingRect.Width / (double) DrawingRect.Height;
					double Scaling = 1;
					if (InputAspectRatio >= FrameAspectRatio)
						Scaling = DrawingRect.Width / Width;
					else
						Scaling = DrawingRect.Height / Height;
					try
						{
						TransformedBitmap ResultBitmapImage = new TransformedBitmap();
						ResultBitmapImage.BeginInit();
						ResultBitmapImage.Source = InputBitmapImage;
						ResultBitmapImage.Transform = new ScaleTransform(Scaling, Scaling);
						ResultBitmapImage.EndInit();

						InputBitmapImage.Freeze();
						return ResultBitmapImage;

						}
					catch (Exception Excp)
						{
						String MemoryMessage = "PackageName = \"" + PackageName + "\"";
						Basics.ShowUsedMemory(MemoryMessage);
						Basics.ReportErrorToEventViewer("Beim PackageName = \"" + PackageName + "\"\r\n"
							+ "bei FrameContentRow.ID \"" + FrameContentRow["ID"].ToString()
							+ "\"\r\nund FrameRow.ID \"" + FrameRow["ID"].ToString()
							+ "\"\r\nund AvailablePicture \"" + AvailablePicture
							+ "\"\r\nund Scaling \"" + Convert.ToString(Scaling)
							+ "\"\r\nund InputBitmapImage.PixelWidth \"" + Convert.ToString (InputBitmapImage.PixelWidth)
							+ "\"\r\nund InputBitmapImage.PixelHeight \"" + Convert.ToString (InputBitmapImage.PixelHeight)
							+ "\"\r\nund DrawingRect.Width  \"" + Convert.ToString(DrawingRect.Width)
							+ "\"\r\nund DrawingRect.Height \"" + Convert.ToString(DrawingRect.Height)
							+ "\"\r\nist wahrscheinlich die Farbtiefe < \"32 Bit"
							+ "\"\r\ntrat folgendes Problem auf\r\n\"" + Excp.ToString() + "\"");
						return null;
						}
					}
				catch (Exception Excp)
					{
					String MemoryMessage = "PackageName = \"" + PackageName + "\"";
					Basics.ShowUsedMemory(MemoryMessage);
					Basics.ReportErrorToEventViewer("Beim PackageName = \"" + PackageName + "\"\r\n"
						+ "bei FrameContentRow.ID \"" + FrameContentRow ["ID"].ToString ()
						+ "\"\r\nund FrameRow.ID \"" + FrameRow["ID"].ToString()
						+ "\"\r\nund AvailablePicture \"" + AvailablePicture
						+ "\"\r\ntrat folgendes Problem auf\r\n\"" + Excp.ToString() + "\"");
					continue;
					}
				}
			return null;
			}
Ejemplo n.º 25
0
 private TransformedBitmap RotateImg(BitmapImage bi)
 {
     // Properties must be set between BeginInit and EndInit calls.
     TransformedBitmap tb = new TransformedBitmap();
     tb.BeginInit();
     tb.Source = bi;
     // Set image rotation.
     RotateTransform transform = new RotateTransform(270);
     tb.Transform = transform;
     tb.EndInit();
     return tb;
 }
Ejemplo n.º 26
0
        private static bool Report(int hwnd, int lParam)
        {
            IntPtr ptr = new IntPtr(hwnd);
            tagWINDOWINFO info = new tagWINDOWINFO();
            GetWindowInfo(ptr, ref info);

            if (IsWindowVisible(ptr) && !IsIconic(ptr) && info.cxWindowBorders > 0 && info.cyWindowBorders > 0)
            {
                string title = GetText(new IntPtr(hwnd));

                if (title != "")
                {
                    WindowSpec spec = new WindowSpec();
                    spec.Caption = title;
                    spec.Hwnd = ptr;
                    spec.Info = info;

                    Bitmap bm = GetWindowPreview(spec);
                    BitmapImage bi = ConvertBitmapToBitmapImage(bm);
                    TransformedBitmap tb = new TransformedBitmap();
                    tb.BeginInit();
                    tb.Source = bi;

                    double ratio = bi.Height / bi.Width;
                    double newHeight = 150 * ratio;
                    double scaleX = 150 / bi.Width;
                    double scaleY =  newHeight / bi.Height;

                    ScaleTransform transform = new ScaleTransform(scaleX, scaleY);
                    tb.Transform = transform;
                    tb.EndInit();
                    spec.Preview = tb;
                    WindowNames.Add(spec);
                }
            }

            return true;
        }
Ejemplo n.º 27
0
 public static void Rotate(int angle,ref BitmapSource img)
 {
     if (img != null)
     {
         var tb = new TransformedBitmap();
         tb.BeginInit();
         tb.Source = img;
         var transform = new RotateTransform(angle);
         tb.Transform = transform;
         tb.EndInit();
         img = BitmapSourceToBitmapImage(tb);
     }
 }
Ejemplo n.º 28
0
        internal override void FinalizeCreation() 
        {
            _bitmapInit.EnsureInitializedComplete(); 
            Uri uri = UriSource; 
            if (_baseUri != null)
                uri = new Uri(_baseUri, UriSource); 

            if ((CreateOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
            {
                ImagingCache.RemoveFromImageCache(uri); 
            }
 
            BitmapImage bitmapImage = CheckCache(uri); 

            if (bitmapImage != null && 
                bitmapImage.CheckAccess() &&
                bitmapImage.SourceRect.Equals(SourceRect) &&
                bitmapImage.DecodePixelWidth == DecodePixelWidth &&
                bitmapImage.DecodePixelHeight == DecodePixelHeight && 
                bitmapImage.Rotation == Rotation &&
                (bitmapImage.CreateOptions & BitmapCreateOptions.IgnoreColorProfile) == 
                (CreateOptions & BitmapCreateOptions.IgnoreColorProfile) 
               )
            { 
                _syncObject = bitmapImage.SyncObject;
                lock (_syncObject)
                {
                    WicSourceHandle = bitmapImage.WicSourceHandle; 
                    IsSourceCached = bitmapImage.IsSourceCached;
                    _convertedDUCEPtr = bitmapImage._convertedDUCEPtr; 
 
                    //
                    // We nee d to keep the strong reference to the cached image for a few reasons: 
                    //
                    //    The application may release the original cached image and then keep a
                    //    reference to this image only, in which case, the cache can be collected.
                    //    This will cause a few undesirable results: 
                    //    1. The application may choose to decode the same URI again in which case
                    //       we will not retrieve it from the cache even though we have a copy already 
                    //       decoded. 
                    //    2. The original cached image holds onto the file stream indirectly which if
                    //       collected can cause bad behavior if the entire image is not loaded into 
                    //       memory.
                    //
                    _cachedBitmapImage = bitmapImage;
                } 
                UpdateCachedSettings();
                return; 
            } 

            BitmapDecoder decoder = null; 
            if (_decoder == null)
            {
                // Note: We do not want to insert in the cache if there is a chance that
                //       the decode pixel width/height may cause the decoder LOD to change 
                decoder = BitmapDecoder.CreateFromUriOrStream(
                    _baseUri, 
                    UriSource, 
                    StreamSource,
                    CreateOptions & ~BitmapCreateOptions.DelayCreation, 
                    BitmapCacheOption.None, // do not cache the frames since we will do that here
                    _uriCachePolicy,
                    false
                    ); 

                if (decoder.IsDownloading) 
                { 
                    _isDownloading = true;
                    _decoder = decoder; 
                    decoder.DownloadProgress += OnDownloadProgress;
                    decoder.DownloadCompleted += OnDownloadCompleted;
                    decoder.DownloadFailed += OnDownloadFailed;
                } 
                else
                { 
                    Debug.Assert(decoder.SyncObject != null); 
                }
            } 
            else
            {
                // We already had a decoder, meaning we were downloading
                Debug.Assert(!_decoder.IsDownloading); 
                decoder = _decoder;
                _decoder = null; 
            } 

            if (decoder.Frames.Count == 0) 
            {
                throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames));
            }
 
            BitmapFrame frame = decoder.Frames[0];
            BitmapSource source = frame; 
 
            Int32Rect sourceRect = SourceRect;
 
            if (sourceRect.X == 0 && sourceRect.Y == 0 &&
                sourceRect.Width == source.PixelWidth &&
                sourceRect.Height == source.PixelHeight)
            { 
                sourceRect = Int32Rect.Empty;
            } 
 
            if (!sourceRect.IsEmpty)
            { 
                CroppedBitmap croppedSource = new CroppedBitmap();
                croppedSource.BeginInit();
                croppedSource.Source = source;
                croppedSource.SourceRect = sourceRect; 
                croppedSource.EndInit();
 
                source = croppedSource; 
                if (_isDownloading)
                { 
                    // Unregister the download events because this is a dummy image. See comment below.
                    source.UnregisterDownloadEventSource();
                }
            } 

            int finalWidth = DecodePixelWidth; 
            int finalHeight = DecodePixelHeight; 

            if (finalWidth == 0 && finalHeight == 0) 
            {
                finalWidth = source.PixelWidth;
                finalHeight = source.PixelHeight;
            } 
            else if (finalWidth == 0)
            { 
                finalWidth = (source.PixelWidth * finalHeight) / source.PixelHeight; 
            }
            else if (finalHeight == 0) 
            {
                finalHeight = (source.PixelHeight * finalWidth) / source.PixelWidth;
            }
 
            if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight ||
                Rotation != Rotation.Rotate0) 
            { 
                TransformedBitmap transformedSource = new TransformedBitmap();
                transformedSource.BeginInit(); 
                transformedSource.Source = source;

                TransformGroup transformGroup = new TransformGroup();
 
                if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight)
                { 
                    int oldWidth = source.PixelWidth; 
                    int oldHeight = source.PixelHeight;
 
                    Debug.Assert(oldWidth > 0 && oldHeight > 0);

                    transformGroup.Children.Add(
                        new ScaleTransform( 
                            (1.0*finalWidth)/ oldWidth,
                            (1.0*finalHeight)/oldHeight)); 
                } 

                if (Rotation != Rotation.Rotate0) 
                {
                    double rotation = 0.0;

                    switch (Rotation) 
                    {
                        case Rotation.Rotate0: 
                            rotation = 0.0; 
                            break;
                        case Rotation.Rotate90: 
                            rotation = 90.0;
                            break;
                        case Rotation.Rotate180:
                            rotation = 180.0; 
                            break;
                        case Rotation.Rotate270: 
                            rotation = 270.0; 
                            break;
                        default: 
                            Debug.Assert(false);
                            break;
                    }
 
                    transformGroup.Children.Add(new RotateTransform(rotation));
                } 
 
                transformedSource.Transform = transformGroup;
 
                transformedSource.EndInit();

                source = transformedSource;
                if (_isDownloading) 
                {
                    // 
                    // If we're currently downloading, then the BitmapFrameDecode isn't actually 
                    // the image, it's just a 1x1 placeholder. The chain we're currently building
                    // will be replaced with another chain once download completes, so there's no 
                    // need to have this chain handle DownloadCompleted.
                    //
                    // Having this chain handle DownloadCompleted is actually a bad thing. Because
                    // the dummy is just 1x1, the TransformedBitmap we're building here will have 
                    // a large scaling factor (to scale the image from 1x1 up to whatever
                    // DecodePixelWidth/Height specifies). When the TransformedBitmap receives 
                    // DownloadCompleted from the BFD, it will call into WIC to create a new 
                    // bitmap scaler using the same large scaling factor, which can produce a huge
                    // bitmap (since the BFD is now no longer 1x1). This problem is made worse if 
                    // this BitmapImage has BitmapCacheOption.OnLoad, since that will put a
                    // CachedBitmap after the TransformedBitmap. When DownloadCompleted propagates
                    // from the TransformedBitmap down to the CachedBitmap, the CachedBitmap will
                    // call CreateBitmapFromSource using the TransformedBitmap, which calls 
                    // CopyPixels on the huge TransformedBitmap. We want to avoid chewing up the
                    // CPU and the memory, so we unregister the download event handlers here. 
                    // 
                    source.UnregisterDownloadEventSource();
                } 
            }

            //
            // If the original image has a color profile and IgnoreColorProfile is not one of the create options, 
            // apply the profile so bits are color-corrected.
            // 
            if ((CreateOptions & BitmapCreateOptions.IgnoreColorProfile) == 0 && 
                frame.ColorContexts != null &&
                frame.ColorContexts[0] != null && 
                frame.ColorContexts[0].IsValid &&
                source.Format.Format != PixelFormatEnum.Extended
                )
            { 
                // NOTE: Never do this for a non-MIL pixel format, because the format converter has
                // special knowledge to deal with the profile 
 
                PixelFormat duceFormat = BitmapSource.GetClosestDUCEFormat(source.Format, source.Palette);
                bool changeFormat = (source.Format != duceFormat); 
                ColorContext destinationColorContext;

                // We need to make sure, we can actually create the ColorContext for the destination duceFormat
                // If the duceFormat is gray or scRGB, the following is not supported, so we cannot 
                // create the ColorConvertedBitmap
                try 
                { 
                    destinationColorContext= new ColorContext(duceFormat);
                } 
                catch (NotSupportedException)
                {
                    destinationColorContext = null;
                } 

                if (destinationColorContext != null) 
                { 
                    bool conversionSuccess = false;
                    bool badColorContext = false; 

                    // First try if the color converter can handle the source format directly
                    // Its possible that the color converter does not support certain pixelformats, so put a try/catch here.
                    try 
                    {
                        ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap( 
                            source, 
                            frame.ColorContexts[0],
                            destinationColorContext, 
                            duceFormat
                            );

                        source = colorConvertedBitmap; 
                        if (_isDownloading)
                        { 
                            // Unregister the download events because this is a dummy image. See comment above. 
                            source.UnregisterDownloadEventSource();
                        } 
                        conversionSuccess = true;
                    }
                    catch (NotSupportedException)
                    { 
                    }
                    catch (FileFormatException) 
                    { 
                        // If the file contains a bad color context, we catch the exception here
                        // and don't bother trying the color conversion below, since color transform isn't possible 
                        // with the given color context.
                        badColorContext = true;
                    }
 
                    if (!conversionSuccess && !badColorContext && changeFormat)
                    {   // If the conversion failed, we first use 
                        // a FormatConvertedBitmap, and then Color Convert that one... 
                        FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(source, duceFormat, source.Palette, 0.0);
 
                        ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap(
                            formatConvertedBitmap,
                            frame.ColorContexts[0],
                            destinationColorContext, 
                            duceFormat
                            ); 
 
                        source = colorConvertedBitmap;
                        if (_isDownloading) 
                        {
                            // Unregister the download events because this is a dummy image. See comment above.
                            source.UnregisterDownloadEventSource();
                        } 
                    }
                } 
            } 

            if (CacheOption != BitmapCacheOption.None) 
            {
                try
                {
                    // The bitmaps bits could be corrupt, and this will cause an exception if the CachedBitmap forces a decode. 
                    CachedBitmap cachedSource = new CachedBitmap(source, CreateOptions & ~BitmapCreateOptions.DelayCreation, CacheOption);
                    source = cachedSource; 
                    if (_isDownloading) 
                    {
                        // Unregister the download events because this is a dummy image. See comment above. 
                        source.UnregisterDownloadEventSource();
                    }
                }
                catch (Exception e) 
                {
                    RecoverFromDecodeFailure(e); 
                    CreationCompleted = true; // we're bailing out because the decode failed 
                    return;
                } 
            }

            // If CacheOption == OnLoad, no need to keep the stream around
            if (decoder != null && CacheOption == BitmapCacheOption.OnLoad) 
            {
                decoder.CloseStream(); 
            } 
            else if (CacheOption != BitmapCacheOption.OnLoad)
            { 
                //ensure that we don't GC the source
                _finalSource = source;
            }
 
            WicSourceHandle = source.WicSourceHandle;
            IsSourceCached = source.IsSourceCached; 
 
            CreationCompleted = true;
            UpdateCachedSettings(); 

            // Only insert in the imaging cache if download is complete
            if (!IsDownloading)
            { 
                InsertInCache(uri);
            } 
        } 
        /// <summary>Exports Slide to an image using a Canvas definition.</summary>
        /// <param name="surface">Canvas to draw into.</param>
        public BitmapImage Export(Canvas surface)
        {
            // Save current canvas transform
            Transform lyTransform =surface.LayoutTransform ;
            // Reset current transform (in case it is scaled or rotated)
            surface.LayoutTransform =null ;

            // Get the size of canvas
            Size size =new Size (surface.Width, surface.Height) ;
            // Measure and arrange the surface
            surface.Measure (size) ;
            surface.Arrange (new Rect (size)) ;

            // Create a render bitmap and push the surface to it
            RenderTargetBitmap renderBitmap =
                new RenderTargetBitmap (
                    (int)size.Width,
                    (int)size.Height,
                    96d, 96d,
                    PixelFormats.Pbgra32) ;
            renderBitmap.Render (surface) ;

            // Restore previously saved layout
            surface.LayoutTransform =lyTransform ;

            // Use png encoder for our data
            PngBitmapEncoder encoder =new PngBitmapEncoder () ;
            //// Push the rendered bitmap to it
            //encoder.Frames.Add (BitmapFrame.Create (renderBitmap)) ;
            //BitmapImage bitmapImage =new BitmapImage () ;
            //using ( var stream = new MemoryStream () ) {
            //	encoder.Save (stream) ;
            //	stream.Seek (0, SeekOrigin.Begin) ;
            //	bitmapImage.BeginInit () ;
            //	bitmapImage.CacheOption =BitmapCacheOption.OnLoad ;
            //	bitmapImage.StreamSource =stream ;
            //	bitmapImage.EndInit () ;
            //}

            var tb =new TransformedBitmap () ;
            tb.BeginInit () ;
            tb.Source =renderBitmap ;
            var transform =new ScaleTransform (1, -1, 0, 0) ;
            tb.Transform =transform ;
            tb.EndInit () ;

            BitmapImage bitmapImage =new BitmapImage () ;
            encoder =new PngBitmapEncoder () ;
            encoder.Frames.Add (BitmapFrame.Create (tb)) ;
            MemoryStream memoryStream =new MemoryStream () ;
            encoder.Save (memoryStream) ;
            bitmapImage.BeginInit () ;
            bitmapImage.StreamSource =new MemoryStream (memoryStream.ToArray ()) ;
            bitmapImage.EndInit () ;
            memoryStream.Close () ;

            return (bitmapImage) ;
        }
Ejemplo n.º 30
0
    /// <summary>
    /// Creates a thumbnail of the specified image
    /// </summary>
    /// <param name="thumbnailImageSource">The source filename to load a System.Drawing.Image from</param>
    /// <param name="thumbnailImageDest">Filename of the thumbnail to create</param>
    /// <param name="aThumbWidth">Maximum width of the thumbnail</param>
    /// <param name="aThumbHeight">Maximum height of the thumbnail</param>
    /// <param name="autocreateLargeThumbs">Auto create large thumbnail</param>
    /// <param name="iRotate">
    /// 0 = no rotate
    /// 1 = rotate 90 degrees
    /// 2 = rotate 180 degrees
    /// 3 = rotate 270 degrees
    /// <param name="fallBack">Needed if generated file need to be delete (for ex in temp folder)</param>
    /// </param>
    /// <returns>Whether the thumb has been successfully created</returns>
    public static bool CreateThumbnail(string thumbnailImageSource, string thumbnailImageDest, int aThumbWidth,
                                       int aThumbHeight, int iRotate, bool aFastMode, bool autocreateLargeThumbs, bool fallBack)
    {
      if (File.Exists(thumbnailImageDest))
      {
        return false;
      }

      if (string.IsNullOrEmpty(thumbnailImageSource) || string.IsNullOrEmpty(thumbnailImageDest) || aThumbHeight <= 0 ||
          aThumbHeight <= 0)
      {
        return false;
      }

      BitmapSource ret = null;
      BitmapMetadata meta = null;
      Bitmap shellThumb = null;
      Bitmap myTargetThumb = null;
      BitmapFrame frame = null;
      Image myImage = null;

      TransformedBitmap thumbnail = null;
      TransformGroup transformGroup = null;

      double angle = 0;

      bool result = false;
      int iQuality = (int) Thumbs.Quality;
      int decodeW = aThumbWidth;

      MediaUrl = thumbnailImageSource;

      try
      {
        if (fallBack)
        {
          frame = BitmapFrame.Create(new Uri(MediaUrl), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        }
        else
        {
          //Try generate Bitmap frame : speedy and low memory !
          frame = BitmapFrame.Create(new Uri(MediaUrl), BitmapCreateOptions.DelayCreation,
                                     BitmapCacheOption.None);
        }

        if (frame.Thumbnail == null) //If it failed try second method (slower and use more memory)
        {
          using (ShellObject shellFile = ShellObject.FromParsingName(thumbnailImageSource))
          {
            shellFile.Thumbnail.RetrievalOption = ShellThumbnailRetrievalOption.Default;
            shellFile.Thumbnail.FormatOption = ShellThumbnailFormatOption.ThumbnailOnly;

            switch (iQuality)
            {
              case 0:
                shellThumb = shellFile.Thumbnail.MediumBitmap;
                break;
              case 1:
                shellThumb = shellFile.Thumbnail.LargeBitmap;
                break;
              case 2:
                shellThumb = shellFile.Thumbnail.LargeBitmap;
                break;
              case 3:
                shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
                break;
              case 4:
                shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
                break;
              default:
                break;
            }

            switch (iRotate)
            {
              case 1:
                shellThumb.RotateFlip(RotateFlipType.Rotate90FlipNone);
                break;
              case 2:
                shellThumb.RotateFlip(RotateFlipType.Rotate180FlipNone);
                break;
              case 3:
                shellThumb.RotateFlip(RotateFlipType.Rotate270FlipNone);
                break;
              default:
                break;
            }

            if (shellThumb != null && !autocreateLargeThumbs)
            {
              int iWidth = aThumbWidth;
              int iHeight = aThumbHeight;
              double fAR = (shellThumb.Width)/((float) shellThumb.Height);

              if (shellThumb.Width > shellThumb.Height)
                iHeight = (int) Math.Floor((((float) iWidth)/fAR));
              else
                iWidth = (int) Math.Floor((fAR*((float) iHeight)));

              try
              {
                Util.Utils.FileDelete(thumbnailImageDest);
              }
              catch (Exception ex)
              {
                Log.Error("Picture: Error deleting old thumbnail - {0}", ex.Message);
              }

              // Write small thumbnail
              myTargetThumb = new Bitmap(shellThumb, iWidth, iHeight);
              myTargetThumb.Save(thumbnailImageDest, Thumbs.ThumbCodecInfo, Thumbs.ThumbEncoderParams);
              File.SetAttributes(thumbnailImageDest, File.GetAttributes(thumbnailImageDest) | FileAttributes.Hidden);
              result = true;
            }
            else
            {
              int iWidth = aThumbWidth;
              int iHeight = aThumbHeight;
              double fAR = (shellThumb.Width)/((float) shellThumb.Height);

              if (shellThumb.Width > shellThumb.Height)
                iHeight = (int) Math.Floor((((float) iWidth)/fAR));
              else
                iWidth = (int) Math.Floor((fAR*((float) iHeight)));

              try
              {
                Util.Utils.FileDelete(thumbnailImageDest);
              }
              catch (Exception ex)
              {
                Log.Error("Picture: Error deleting old thumbnail - {0}", ex.Message);
              }

              // Write Large thumbnail
              myTargetThumb = new Bitmap(shellThumb, iWidth, iHeight);
              myTargetThumb.Save(thumbnailImageDest, Thumbs.ThumbCodecInfo, Thumbs.ThumbEncoderParams);
              File.SetAttributes(thumbnailImageDest, File.GetAttributes(thumbnailImageDest) | FileAttributes.Hidden);
              result = true;
            }
          }
        }
        else
        {
          //Detect metas image
          meta = frame.Metadata as BitmapMetadata;
          ret = frame.Thumbnail;

          //if ((meta != null) && (ret != null)) //si on a des meta, tentative de récupération de l'orientation
          //{
          //  if (meta.GetQuery("/app1/ifd/{ushort=274}") != null)
          //  {
          //    orientation =
          //      (ExifOrientations)
          //      Enum.Parse(typeof (ExifOrientations), meta.GetQuery("/app1/ifd/{ushort=274}").ToString());
          //  }

          //  switch (orientation)
          //  {
          //    case ExifOrientations.Rotate90:
          //      angle = -90;
          //      break;
          //    case ExifOrientations.Rotate180:
          //      angle = 180;
          //      break;
          //    case ExifOrientations.Rotate270:
          //      angle = 90;
          //      break;
          //  }

          //  if (angle != 0) //on doit effectuer une rotation de l'image
          //  {
          //    ret = new TransformedBitmap(ret.Clone(), new RotateTransform(angle));
          //    ret.Freeze();
          //  }
          //}

          if (autocreateLargeThumbs)
          {
            if (ret != null)
            {
              // we'll make a thumbnail image then ... (too bad as the pre-created one is FAST!)
              thumbnail = new TransformedBitmap();
              thumbnail.BeginInit();
              thumbnail.Source = frame as BitmapSource;

              // we'll make a reasonable sized thumnbail
              int pixelH = frame.PixelHeight;
              int pixelW = frame.PixelWidth;
              int decodeH = (frame.PixelHeight*decodeW)/pixelW;
              double scaleX = decodeW/(double) pixelW;
              double scaleY = decodeH/(double) pixelH;

              transformGroup = new TransformGroup();
              transformGroup.Children.Add(new ScaleTransform(scaleX, scaleY));
              thumbnail.Transform = transformGroup;
              thumbnail.EndInit();
              ret = thumbnail;

              // Write Large thumbnail
              result = BitmapFromSource(ret, thumbnailImageDest);
            }
          }
          else
          {
            if (ret != null)
            {
              // Write small thumbnail
              result = BitmapFromSource(ret, thumbnailImageDest);
            }
          }
        }

      }
      catch (Exception ex)
      {
        try
        {
          try
          {
            myImage = ImageFast.FromFile(thumbnailImageSource);
          }
          catch (FileNotFoundException)
          {
            result = false;
          }
          result = CreateThumbnail(myImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
        }
        catch (Exception)
        {
          Log.Warn("Picture: Fast loading of thumbnail {0} failed - trying safe fallback now", thumbnailImageDest);

          try
          {
            try
            {
              myImage = ImageFast.FromFile(thumbnailImageDest);
              result = CreateThumbnail(myImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
            }
            catch (Exception)
            {
              myImage = Image.FromFile(thumbnailImageDest, true);
              result = CreateThumbnail(myImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
            }
          }
          catch (FileNotFoundException)
          {
            result = false;
          }
          catch (OutOfMemoryException)
          {
            Log.Warn("Picture: Creating thumbnail failed - image format is not supported of {0}", thumbnailImageSource);
            result = false;
          }
          catch (Exception)
          {
            Log.Info("Pictures: No thumbnail created for -- {0}", thumbnailImageSource);
            result = false;
          }
        }
      }
      finally
      {
        if (shellThumb != null)
          shellThumb.SafeDispose();
        if (ret != null)
          ret.SafeDispose();
        if (thumbnail != null)
          thumbnail.SafeDispose();
        if (transformGroup != null)
          transformGroup.SafeDispose();
        if (myTargetThumb != null)
          myTargetThumb.SafeDispose();
        if (MediaUrl != null)
          MediaUrl.SafeDispose();
        if (frame != null)
          frame.SafeDispose();
        if (myImage != null)
          myImage.SafeDispose();
      }

      if (result && Util.Utils.IsFileExistsCacheEnabled())
      {
        Log.Debug("CreateThumbnail : FileExistsInCache updated with new file: {0}", thumbnailImageDest);
        Util.Utils.DoInsertExistingFileIntoCache(thumbnailImageDest);
      }
      return result;
    }
Ejemplo n.º 31
0
        private static BitmapSource FlipBitmap(BitmapSource flipped, bool flipX, bool flipY)
        {
            System.Windows.Media.Transform tr = new System.Windows.Media.ScaleTransform((flipX ? -1 : 1), (flipY ? -1 : 1));

            TransformedBitmap transformedBmp = new TransformedBitmap();
            transformedBmp.BeginInit();
            transformedBmp.Source = flipped;
            transformedBmp.Transform = tr;
            transformedBmp.EndInit();
            return transformedBmp;
        }