コード例 #1
0
ファイル: MyKONST.cs プロジェクト: Ttxman/NanoTrans
        public static string JpgToBase64(BitmapFrame aBMP)
        {
            try
            {
                string pBase64String = null;
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                //BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(aBMP);
                MemoryStream ms = new MemoryStream();

                //Convert.ToBase64String
                encoder.Save(ms);
                byte[] pPole = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(pPole, 0, pPole.Length);
                pBase64String = Convert.ToBase64String(pPole);
                ms.Close();
                return pBase64String;
            }
            catch (Exception)
            {

                return null;
            }
        }
コード例 #2
0
// using System.Windows.Media.Imaging;

class Load { void Load() 
{
    // Loads the images to tile (no need to specify PngBitmapDecoder, the correct decoder is automatically selected)
System.Windows.Media.Imaging.BitmapFrame frame1 = BitmapDecoder.Create(new Uri(path1), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
BitmapFrame frame2 = BitmapDecoder.Create(new Uri(path2), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
BitmapFrame frame3 = BitmapDecoder.Create(new Uri(path3), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
BitmapFrame frame4 = BitmapDecoder.Create(new Uri(path4), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

// Gets the size of the images (I assume each image has the same size)
int imageWidth = frame1.PixelWidth;
int imageHeight = frame1.PixelHeight;

// Draws the images into a DrawingVisual component
System.Windows.Media.DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
    drawingContext.DrawImage(frame1, new Rect(0, 0, imageWidth, imageHeight));
    drawingContext.DrawImage(frame2, new Rect(imageWidth, 0, imageWidth, imageHeight));
    drawingContext.DrawImage(frame3, new Rect(0, imageHeight, imageWidth, imageHeight));
    drawingContext.DrawImage(frame4, new Rect(imageWidth, imageHeight, imageWidth, imageHeight));
}

// Converts the Visual (DrawingVisual) into a BitmapSource
System.Windows.Media.Imaging.RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth * 2, imageHeight * 2, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);

// Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));

// Saves the image into a file using the encoder
using (System.IO.Stream stream = File.Create(pathTileImage))
    encoder.Save(stream);
}
コード例 #3
0
ファイル: Gui.cs プロジェクト: kav-it/SharpLib
        public static IntPtr GetIconHandle(ImageSource source)
        {
            System.Windows.Media.Imaging.BitmapFrame frame = source as System.Windows.Media.Imaging.BitmapFrame;

            if (frame != null && frame.Decoder.Frames.Count > 0)
            {
                frame = frame.Decoder.Frames[0];

                int width  = frame.PixelWidth;
                int height = frame.PixelHeight;
                int stride = width * ((frame.Format.BitsPerPixel + 7) / 8);

                Byte[] bits = new Byte[height * stride];

                frame.CopyPixels(bits, stride, 0);

                GCHandle gcHandle = GCHandle.Alloc(bits, GCHandleType.Pinned);

                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(
                    width,
                    height,
                    stride,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb,
                    gcHandle.AddrOfPinnedObject());

                IntPtr hIcon = bitmap.GetHicon();

                gcHandle.Free();

                return(hIcon);
            }

            return(IntPtr.Zero);
        }
コード例 #4
0
 private void GenerateImage()
 {
     if (_imageBoxBorder.RenderSize.Width > 0 && _imageBoxBorder.RenderSize.Height > 0)
     {
         _generatedImage = HtmlRender.RenderToImage(_html, _imageBoxBorder.RenderSize, null, DemoUtils.OnStylesheetLoad, HtmlRenderingHelper.OnImageLoad);
         _imageBox.Source = _generatedImage;
     }
 }
コード例 #5
0
	    public DesignTimeSearchResult(BitmapFrame icon, string processName, string title, string error = null)
		{
			View = new BasicListEntry();
			Icon = icon;
			ProcessName = processName;
			Title = title;
		    Error = error;
		}
コード例 #6
0
 private static byte[] ToByteArray(BitmapFrame bfResize)
 {
     MemoryStream msStream = new MemoryStream();
     JpegBitmapEncoder encoder = new JpegBitmapEncoder();
     encoder.Frames.Add(bfResize);
     encoder.Save(msStream);
     return msStream.ToArray();
 }
コード例 #7
0
 public static byte[] ImageToByte(BitmapFrame bfResize)
 {
     using (MemoryStream msStream = new MemoryStream())
     {
         PngBitmapEncoder pbdDecoder = new PngBitmapEncoder();
         pbdDecoder.Frames.Add(bfResize);
         pbdDecoder.Save(msStream);
         return msStream.ToArray();
     }
 }
コード例 #8
0
 /// <summary>
 /// 转换Bitmap到BitmapSource
 /// </summary>
 /// <param name="bmp"></param>
 /// <returns></returns>
 public static System.Windows.Media.Imaging.BitmapSource GetBitmapSource(System.Drawing.Bitmap bmp)
 {
     System.Windows.Media.Imaging.BitmapFrame bf = null;
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
         bf = System.Windows.Media.Imaging.BitmapFrame.Create(ms, System.Windows.Media.Imaging.BitmapCreateOptions.None, System.Windows.Media.Imaging.BitmapCacheOption.OnLoad);
     }
     return(bf);
 }
コード例 #9
0
        private static MemoryStream GetPngStream(BitmapFrame photo)
        {
            MemoryStream result = new MemoryStream();

            PngBitmapEncoder targetEncoder = new PngBitmapEncoder();
            targetEncoder.Frames.Add(photo);
            targetEncoder.Save(result);

            return result;
        }
コード例 #10
0
        /// <summary>
        /// DIO圖片
        /// 網址:localhost:50471/img/wry?t=2018-1-1_0:0:0
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public ActionResult wry(String t)
        {
            if (t == null || t == "")
            {
                t = "2018-1-1";
            }


            String html = html_640_360;

            html = html.Replace("{url}", Server.MapPath("~/Image/wry.jpg"));


            try {
                //初始化時間
                t = t.Replace(" ", "-").Replace(":", "-").Replace("_", "-").Replace("/", "-").Replace(":", "-").Replace("\\", "-");
                t = t.Replace("--", "-").Replace("--", "-").Replace("--", "-");
                String[] tt   = t.Split('-');
                int[]    ar_d = { 2018, 1, 1, 0, 0, 0 };
                for (int i = 0; i < 6; i++)
                {
                    try {
                        ar_d[i] = Int32.Parse(tt[i]);
                    } catch { }
                }
                DateTime d = new DateTime(ar_d[0], ar_d[1], ar_d[2], ar_d[3], ar_d[4], ar_d[5]);

                double output = ((DateTime.Now - d).TotalSeconds);//與目前的時間相減,並換成『秒』

                if (output >= 0)
                {
                    html = html.Replace("{txt}", output.ToString("0") + "秒過去了");
                }
                else
                {
                    output = output * -1;
                    html   = html.Replace("{txt}", "還有" + output.ToString("0") + "秒");
                }
            } catch (Exception) {
                html = html.Replace("{txt}", "wryyyyyy");
            }

            System.Windows.Media.Imaging.BitmapFrame image = HtmlRender.RenderToImage(html);

            byte[] imgBytes;
            var    png = new JpegBitmapEncoder();

            png.Frames.Add(image);
            using (MemoryStream mem = new MemoryStream()) {
                png.Save(mem);
                imgBytes = mem.ToArray();  // and use the imgBytes array in your SQL operation
            }

            return(File(imgBytes, "image/jpeg"));
        }
コード例 #11
0
ファイル: MultiSizeImage.cs プロジェクト: Exe0/Eto
		/// <summary>
		/// Gets the pixel depth (in bits per pixel, bpp) of the specified frame
		/// </summary>
		/// <param name="frame">The frame to get BPP for</param>
		/// <returns>The number of bits per pixel in the frame</returns>
		static int GetFramePixelDepth (BitmapFrame frame)
		{
			if (frame.Decoder.CodecInfo.ContainerFormat == new Guid("{a3a860c4-338f-4c17-919a-fba4b5628f21}")
			    && frame.Thumbnail != null)
			{
				// Windows Icon format, original pixel depth is in the thumbnail
				return frame.Thumbnail.Format.BitsPerPixel;
			}
			// Other formats, just assume the frame has the correct BPP info
			return frame.Format.BitsPerPixel;
		}
コード例 #12
0
        /// <summary>
        /// 转换Bitmap到BitmapSource
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static BitmapSource GetBitmapSource(System.Drawing.Bitmap bmp)
        {
            System.Windows.Media.Imaging.BitmapFrame bf = null;

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                bf = System.Windows.Media.Imaging.BitmapFrame.Create(ms, System.Windows.Media.Imaging.BitmapCreateOptions.None, System.Windows.Media.Imaging.BitmapCacheOption.OnLoad);
            }
            return(bf);
            //return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
        }
コード例 #13
0
ファイル: Map.cs プロジェクト: ColonelBlack94/ToolDev_GPD415
        public void SetTile(int _x, int _y, BitmapFrame _image)
        {
            // hat das bild noch keine ID?
            if(!images.Contains(_image))
            {
                // id erstellen
                images.Add(_image);
            }

            // id setzen
            Tiles[_x, _y] = images.IndexOf(_image);
        }
コード例 #14
0
        public ElementAnimationsViewModel()
        {
            Animations = new ObservableCollection<AnimationViewModel>();

            mPlayTimer = new DispatcherTimer();
            mPlayTimer.Interval = new TimeSpan(0, 0, 0, 0, mTimerFrequencyInMs);
            mPlayTimer.Tick += HandlePlayTimerTick;

            mPlayBitmap = BitmapLoader.Self.LoadImage("PlayIcon.png");

            mStopBitmap = BitmapLoader.Self.LoadImage("StopIcon.png");
        }
コード例 #15
0
        //Function to Gen the sprite sheet with a string of images
        public void GenSheet(string[] images)
        {
            BitmapFrame[] frames = new BitmapFrame[images.Length];
            // Atlas Dimensions
            int iW = 0;
            int iH = 0;

            // Loads the images to tile (no need to specify PngBitmapDecoder, the correct decoder is automatically selected)
            for (int i = 0; i < images.Length; i++)
            {
               frames[i] = BitmapDecoder.Create(new Uri(images[i]), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            }
            //Make it so that the two biggest heights and widths depict size
            for(int i = 0; i<frames.Length; i++)
            {
                iW += frames[i].PixelWidth;
            }
            for(int i = 1; i<frames.Length; i++)
            {
                iH = Math.Max(frames[i-1].PixelHeight, frames[i].PixelHeight);
            }
            // Draws the images into a DrawingVisual component
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                int prevFrames = 0;//var prevFrames changed during loop
                for (int i = 0; i < frames.Length; i++)
                {
                    //loading all the images using a for loop for a finite number of images
                    drawingContext.DrawImage(frames[i], new Rect(prevFrames, 0, frames[i].PixelWidth, frames[i].PixelHeight));
                    //saves the width of the prevFrame so that the next image can draw next to it and produces a row of images
                    prevFrames += frames[i].PixelWidth;

                }
            }
            // Converts the Visual (DrawingVisual) into a BitmapSource
            RenderTargetBitmap bmp = new RenderTargetBitmap(iW, iH, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(drawingVisual);

            // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));

            string directory = Directory.GetCurrentDirectory();

            // Saves the image into a file using the encoder
            using (Stream stream = File.Create(directory + @"\tile.png"))
                encoder.Save(stream);
            Vector[] eeek = stripSorter(frames);

            XML eek = new XML();
            eek.BuildXMLDoc(images, frames, iW, iH, eeek);
        }
コード例 #16
0
ファイル: Utils.cs プロジェクト: eakova/resizer
 public static byte[] ToByteArrayWpf(BitmapFrame targetFrame, int quality)
 {
     byte[] targetBytes;
     using (var memoryStream = new MemoryStream()) {
         var targetEncoder = new JpegBitmapEncoder {
                                                       QualityLevel = quality
                                                   };
         targetEncoder.Frames.Add(targetFrame);
         targetEncoder.Save(memoryStream);
         targetBytes = memoryStream.ToArray();
     }
     return targetBytes;
 }
コード例 #17
0
 private static BitmapFrame Resize(BitmapFrame photo, int width, int height, BitmapScalingMode scalingMode)
 {
     DrawingGroup group = new DrawingGroup();
     RenderOptions.SetBitmapScalingMode(group, scalingMode);
     group.Children.Add(new ImageDrawing(photo, new Rect(0, 0, width, height)));
     DrawingVisual targetVisual = new DrawingVisual();
     DrawingContext targetContext = targetVisual.RenderOpen();
     targetContext.DrawDrawing(group);
     RenderTargetBitmap target = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
     targetContext.Close();
     target.Render(targetVisual);
     BitmapFrame targetFrame = BitmapFrame.Create(target);
     return targetFrame;
 }
コード例 #18
0
        internal static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
        {
            // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));

            using (MemoryStream outStream = new())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(bitmapImage));
                enc.Save(outStream);
                Bitmap bitmap = new(outStream);

                return(new Bitmap(bitmap));
            }
        }
コード例 #19
0
 private void CreateImageFile(FileStream file,BitmapFrame frame,ImageType type)
 {
     if(file==null)return;
     BitmapEncoder encoder=null;
     switch(type)
     {
     case ImageType.Bmp:encoder=new BmpBitmapEncoder();break;
     case ImageType.Jpg:encoder=new JpegBitmapEncoder(){QualityLevel=100};break;
     case ImageType.Png:encoder=new PngBitmapEncoder();break;
     case ImageType.Gif:encoder=new GifBitmapEncoder();break;
     case ImageType.Tiff:encoder=new TiffBitmapEncoder(){Compression=TiffCompressOption.Default};break;
     }
     encoder.Frames.Add(frame);
     encoder.Save(file);
 }
コード例 #20
0
 /// <summary>
 /// ThumbnailExceptionWorkArround when image cause a format exception by accessing the Thumbnail
 /// </summary>
 /// <param name="frame"></param>
 /// <returns></returns>
 static BitmapSource GetThumbnail(BitmapFrame frame)
 {
     try
     {
         if (frame != null &&
             frame.PixelWidth == 16 && frame.PixelHeight == 16 &&
             ((frame.Format == PixelFormats.Bgra32) || (frame.Format == PixelFormats.Bgr24)))
             return frame;
         else
             return null;
     }
     catch (Exception)
     {
         return null;
     }
 }
コード例 #21
0
ファイル: GifAnimation.cs プロジェクト: QuocHuy7a10/Arianrhod
 private BitmapImage ConvertToBitmapImage(BitmapFrame bf)
 {
     BmpBitmapEncoder encoder = new BmpBitmapEncoder
     {
         Frames = { bf }
     };
     MemoryStream stream = new MemoryStream();
     encoder.Save(stream);
     stream.Seek(0L, SeekOrigin.Begin);
     BitmapImage image = new BitmapImage();
     image.BeginInit();
     image.StreamSource = stream;
     image.EndInit();
     stream.Close();
     return image;
 }
コード例 #22
0
        private void WriteImage(Path visual, ImageBrush brush)
        {
            System.Windows.Media.Imaging.BitmapFrame frame = brush.ImageSource as System.Windows.Media.Imaging.BitmapFrame;


            PDFImage img = PDFDocument.CreateObject <PDFImage>();

            string key = "R" + Page.Resources.ID + "I" + img.ID;

            Page.Resources.XObject[key] = img;

            img.ColorSpace       = "DeviceRGB";
            img.BitsPerComponent = 8;

            System.Windows.Media.Imaging.JpegBitmapEncoder enc = new JpegBitmapEncoder();


            /*TransformedBitmap tb = new TransformedBitmap(frame, new ScaleTransform {
             *      ScaleX = brush.Viewport.Width / frame.Width ,
             *      ScaleY = brush.Viewport.Height / frame.Height
             * });*/

            var tb = frame;

            img.Width  = tb.PixelWidth;
            img.Height = tb.PixelHeight;

            enc.Frames.Add(BitmapFrame.Create(tb));
            enc.QualityLevel = 100;
            enc.Save(img.Stream);

            Page.ContentStream.WriteLine("q");

            PathGeometry pg = PathGeometry.CreateFromGeometry(visual.Data);
            Point        p  = pg.Figures.First().StartPoint;

            p = TransformPoint(visual, p);



            Page.ContentStream.WriteLine("{0} 0 0 {1} {2} {3} cm", brush.Viewport.Width, brush.Viewport.Height, p.X, p.Y - brush.Viewport.Height);

            Page.ContentStream.WriteLine("/" + key + " Do");
            Page.ContentStream.WriteLine("Q");
        }
コード例 #23
0
ファイル: PhotoModel.cs プロジェクト: virucho/TouchInfoPoint
        /// <summary>
        /// Constructor
        /// </summary>
        public Photo(string path, string name)
        {
            _source = new Uri(path);
            _image = BitmapFrame.Create(_source);
            //_name = name.Remove(name.Length - 4); //Remove fileextension
            _name = Tools.RemoveExtension(name);
            _name = Tools.RemoveStartNumber(_name);

            //Create Thumbnail for png and Bmp images
            if (_image.Thumbnail == null)
            {
                _myThumbnail = new BitmapImage();
                _myThumbnail.BeginInit();
                _myThumbnail.UriSource = _source;
                _myThumbnail.DecodePixelWidth = 436;
                _myThumbnail.DecodePixelHeight = 326;
                _myThumbnail.EndInit();
            }
        }
コード例 #24
0
        private void AddToolboxImage(BitmapFrame _image)
        {
            // neues bild erstellen
            Image newImage = new Image();

            // groesse des bildes festlegen
            newImage.Width = 50.0f;
            newImage.Height = 50.0f;
            newImage.Margin = new Thickness(5.0d);

            // event registrieren
            newImage.MouseDown += Image_MouseDown;

            // bildquelle angeben
            newImage.Source = _image;

            // bild der toolbox hinzufuegen
            ToolBoxStackPanel.Children.Add(newImage);
        }
コード例 #25
0
        /// <summary>
        /// Converts the Frame to a Bitmapimage
        /// </summary>
        /// <param name="bitmapFrame"></param>
        /// <returns></returns>
        public static BitmapImage FrameToBitmap(BitmapFrame bitmapFrame)
        {
            BitmapImage bImg = new BitmapImage();
            BitmapEncoder encoder = new PngBitmapEncoder(); //new JpegBitmapEncoder();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                encoder.Frames.Add(bitmapFrame);
                encoder.Save(memoryStream);
                bImg.BeginInit();
                bImg.CacheOption = BitmapCacheOption.OnLoad;
                bImg.CreateOptions = BitmapCreateOptions.None;
                bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
                bImg.EndInit();

                bImg.Freeze();
            }

            return bImg;
        }
コード例 #26
0
        public FlipDigit()
        {
            InitializeComponent();

            _step = 0;
            _current = 0;
            Pace = 300;
            _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(Pace / 7) };
            _timer.Tick += timer_Tick;

            var digitsTop = Application.GetContentStream(new Uri(@"digits-top.png", UriKind.RelativeOrAbsolute));
            if (digitsTop != null)
                _digitsTop = BitmapFrame.Create(digitsTop.Stream);

            var digitsBottom = Application.GetContentStream(new Uri(@"digits-bottom.png", UriKind.RelativeOrAbsolute));
            if (digitsBottom != null)
                _digitsBottom = BitmapFrame.Create(digitsBottom.Stream);

            goToNumber(0, 0);
        }
コード例 #27
0
ファイル: XML.cs プロジェクト: JayStilla/SpriteMapGenerator
        //Create declaration
        public void BuildXMLDoc(string[] filename, BitmapFrame[] frames, int width, int height, Vector[] xy)
        {
            XDeclaration XMLdec = new XDeclaration("1.0", "UTF-8", "yes");
            //fill with frames
            Object[] XMLelem = new Object[frames.Length];
            for (int i = 0; i < frames.Length; i++)
            {
                XElement node = new XElement("SubTexture");

                BitmapFrame eek = frames[i];

                node.SetAttributeValue("name", filename[i]);
                node.SetAttributeValue("x", xy[i].X);
                node.SetAttributeValue("y", xy[i].Y);
                node.SetAttributeValue("width", frames[i].PixelWidth);
                node.SetAttributeValue("height", frames[i].PixelHeight);

                XMLelem[i] = node;

            }
            XElement XMLRootNode = new XElement("TextureAtlas", XMLelem);
            XMLRootNode.SetAttributeValue("imagePath", "Naw");

            XDocument XMLdoc = new XDocument(XMLdec, XMLRootNode);

            AtlasXML = XMLdoc;

            Microsoft.Win32.SaveFileDialog saveDiag = new Microsoft.Win32.SaveFileDialog();
            Nullable<bool> diagResult = saveDiag.ShowDialog();

            if (diagResult == true)
            {
                FileStream XMLstream = new FileStream(saveDiag.FileName, FileMode.Create);
                XMLdoc.Save(XMLstream);
                XMLstream.Close();
            }
            else
            {
                return;
            }
        }
コード例 #28
0
 public CommunitySessionWindow(SessionTabItem sessionTabItem)
 {
     this.sessionTabItems = new ObservableCollection<SessionTabItem>();
     //WindowHelper.Hook(this, "headerBackground", new string[] { "controlBox", "toolBar" });
     this.InitializeComponent();
     Util_UserSettings_ContactSessionWindow.SettingsChanged += new PropertyChangedEventHandler(this.Util_UserSettings_CommunitySessionWindow_SettingsChanged);
     this.SetSendButtonToolTip();
     this.AddSession(sessionTabItem);
     if (_icon == null)
     {
         _icon = BitmapFrame.Create(new Uri(EnvironmentPath.Startup + @"res\community16.ico", UriKind.Absolute));
     }
     base.Icon = _icon;
     this.BindWindowTitleAndIcon();
     this.communityManager = this.CurrentSessionTabItem.CommunitySession.Community.CommunityManager;
     this.communityManager.RefreshAllMemberInfo();
     this.communityManager.SortManager.SortEvent += new EventHandler<EventArgs>(this.CommunityMemberSortManager_Sort);
     this.communityManager.SortManager.RequestSorting();
     this.CurrentSessionTabItem.CommunitySession.Community.PropertyChanged += new PropertyChangedEventHandler(this.CommunitySessionWindow_PropertyChanged);
     Buddy.BuddyPropertyChanged += new PropertyChangedEventHandler(this.Buddy_BuddyPropertyChanged);
     this.communityManager.MemberChanged += new EventHandler(this.communityManager_MemberChanged);
     this.CalcMemberCount();
     this.SetMsgSetImage();
 }
コード例 #29
0
 private static void AddIcon(AvalonEditTextOutput output, BitmapFrame frame)
 {
   output.AddUIElement(() => new Image { Source = frame });
 }
コード例 #30
0
        /// <summary>
        /// 喬瑟夫 圖片
        /// 網址:localhost:50471/img/kira?t=2018-1-1_0:0:0
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public ActionResult joseph(String t)
        {
            if (t == null || t == "")
            {
                t = "2018-1-1";
            }


            String html = html_640_360;

            html = html.Replace("{url}", Server.MapPath("~/Image/joseph.jpg"));


            try {
                //初始化時間
                t = t.Replace(" ", "-").Replace(":", "-").Replace("_", "-").Replace("/", "-").Replace(":", "-").Replace("\\", "-");
                t = t.Replace("--", "-").Replace("--", "-").Replace("--", "-");
                String[] tt   = t.Split('-');
                int[]    ar_d = { 2018, 1, 1, 0, 0, 0 };
                for (int i = 0; i < 6; i++)
                {
                    try {
                        ar_d[i] = Int32.Parse(tt[i]);
                    } catch { }
                }

                DateTime d = new DateTime(ar_d[0], ar_d[1], ar_d[2], ar_d[3], ar_d[4], ar_d[5]);


                //與目前的時間相減,並換成『秒』
                int int_天 = 0;
                int int_時 = 0;
                int int_分 = 0;
                int int_秒 = 0;

                if (DateTime.Now > d)  //已經過了

                {
                    int_天 = Int32.Parse((DateTime.Now - d).ToString("dd"));
                    int_時 = ((DateTime.Now - d).Hours);
                    int_分 = ((DateTime.Now - d).Minutes);
                    int_秒 = ((DateTime.Now - d).Seconds);
                }
                else    //還沒到

                {
                    int_天 = Int32.Parse((d - DateTime.Now).ToString("dd"));
                    int_時 = ((d - DateTime.Now).Hours);
                    int_分 = ((d - DateTime.Now).Minutes);
                    int_秒 = ((d - DateTime.Now).Seconds);
                }


                String output = "";

                if (int_天 != 0)
                {
                    output += int_天 + "天";
                }
                if (int_時 != 0)
                {
                    output += int_時 + "小時";
                }
                if (int_分 != 0)
                {
                    output += int_分 + "分";
                }
                if (int_秒 != 0)
                {
                    output += int_秒 + "秒";
                }


                if (DateTime.Now > d)  //已經過了
                {
                    html = html.Replace("{txt}", "" + output + "過去了");
                }
                else    //還沒到
                {
                    html = html.Replace("{txt}", "還有" + output);
                }
            } catch (Exception) {
                html = html.Replace("{txt}", "kono 喬瑟夫 da");
            }



            //把html轉成圖片
            System.Windows.Media.Imaging.BitmapFrame image = HtmlRender.RenderToImage(html);


            //把圖片變成jpg形式
            byte[] imgBytes;
            var    png = new JpegBitmapEncoder();

            png.Frames.Add(image);
            using (MemoryStream mem = new MemoryStream()) {
                png.Save(mem);
                imgBytes = mem.ToArray();  // and use the imgBytes array in your SQL operation
            }


            return(File(imgBytes, "image/jpeg"));
        }
コード例 #31
0
        private void SaveFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions, BitmapFrame frame)
        {
            SetupFrame(frameEncodeHandle, encoderOptions);

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeInitialized;

            // Set the size
            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetSize(
                              frameEncodeHandle,
                              frame.PixelWidth,
                              frame.PixelHeight
                              ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeSizeSet;

            // Set the resolution
            double dpiX = frame.DpiX;
            double dpiY = frame.DpiY;

            if (dpiX <= 0)
            {
                dpiX = 96;
            }
            if (dpiY <= 0)
            {
                dpiY = 96;
            }

            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetResolution(
                              frameEncodeHandle,
                              dpiX,
                              dpiY
                              ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeResolutionSet;

            if (_supportsFrameThumbnails)
            {
                // Set the thumbnail.
                BitmapSource thumbnail = frame.Thumbnail;

                if (thumbnail != null)
                {
                    SafeMILHandle thumbnailHandle = thumbnail.WicSourceHandle;

                    lock (thumbnail.SyncObject)
                    {
                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetThumbnail(
                                          frameEncodeHandle,
                                          thumbnailHandle
                                          ));

                        // Helpful for debugging stress and remote dumps
                        _encodeState = EncodeState.FrameEncodeThumbnailSet;
                    }
                }
            }

            // if the source has been color corrected, we want to use a corresponding color profile
            if (frame._isColorCorrected)
            {
                ColorContext colorContext     = new ColorContext(frame.Format);
                IntPtr[]     colorContextPtrs = new IntPtr[1] {
                    colorContext.ColorContextHandle.DangerousGetHandle()
                };

                int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                    frameEncodeHandle,
                    1,
                    colorContextPtrs
                    );

                // It's possible that some encoders may not support color contexts so don't check hr
                if (hr == HRESULT.S_OK)
                {
                    // Helpful for debugging stress and remote dumps
                    _encodeState = EncodeState.FrameEncodeColorContextsSet;
                }
            }
            // if the caller has explicitly provided color contexts, add them to the encoder
            else
            {
                IList <ColorContext> colorContexts = frame.ColorContexts;
                if (colorContexts != null && colorContexts.Count > 0)
                {
                    int count = colorContexts.Count;

                    // Marshal can't convert SafeMILHandle[] so we must
                    {
                        IntPtr[] colorContextPtrs = new IntPtr[count];
                        for (int i = 0; i < count; ++i)
                        {
                            colorContextPtrs[i] = colorContexts[i].ColorContextHandle.DangerousGetHandle();
                        }

                        int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                            frameEncodeHandle,
                            (uint)count,
                            colorContextPtrs
                            );

                        // It's possible that some encoders may not support color contexts so don't check hr
                        if (hr == HRESULT.S_OK)
                        {
                            // Helpful for debugging stress and remote dumps
                            _encodeState = EncodeState.FrameEncodeColorContextsSet;
                        }
                    }
                }
            }

            // Set the pixel format and palette

            lock (frame.SyncObject)
            {
                SafeMILHandle outSourceHandle    = new SafeMILHandle();
                SafeMILHandle bitmapSourceHandle = frame.WicSourceHandle;
                SafeMILHandle paletteHandle      = new SafeMILHandle();

                // Set the pixel format and palette of the bitmap.
                // This could (but hopefully won't) introduce a format converter.
                HRESULT.Check(UnsafeNativeMethods.WICCodec.WICSetEncoderFormat(
                                  bitmapSourceHandle,
                                  paletteHandle,
                                  frameEncodeHandle,
                                  out outSourceHandle
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeFormatSet;
                _writeSourceHandles.Add(outSourceHandle);

                // Set the metadata
                if (_supportsFrameMetadata)
                {
                    BitmapMetadata metadata = frame.Metadata as BitmapMetadata;

                    // If the frame has metadata associated with a different container format, then we ignore it.
                    if (metadata != null && metadata.GuidFormat == ContainerFormat)
                    {
                        SafeMILHandle /* IWICMetadataQueryWriter */ metadataHandle = new SafeMILHandle();

                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.GetMetadataQueryWriter(
                                          frameEncodeHandle,
                                          out metadataHandle
                                          ));

                        PROPVARIANT propVar = new PROPVARIANT();

                        try
                        {
                            propVar.Init(metadata);

                            lock (metadata.SyncObject)
                            {
                                HRESULT.Check(UnsafeNativeMethods.WICMetadataQueryWriter.SetMetadataByName(
                                                  metadataHandle,
                                                  "/",
                                                  ref propVar
                                                  ));

                                // Helpful for debugging stress and remote dumps
                                _encodeState = EncodeState.FrameEncodeMetadataSet;
                            }
                        }
                        finally
                        {
                            propVar.Clear();
                        }
                    }
                }

                Int32Rect r = new Int32Rect();
                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.WriteSource(
                                  frameEncodeHandle,
                                  outSourceHandle,
                                  ref r
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeSourceWritten;

                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.Commit(
                                  frameEncodeHandle
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeCommitted;
            }
        }
コード例 #32
0
    // since inheritance of Window does not work, the eventhandler have to be static methods and added after generation of the Window object

    // keyboard is pressed
    private static void InkCanvas_KeyDown(object sender, KeyEventArgs e)
    {
        Key Taste = e.Key;
        // the sender object is the object that generated the event
        InkCanvas objInkCanvas = (InkCanvas)sender;

        if (Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftCtrl))
// the following line only works with .Net 4.x
//		if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
        {         // if Ctrl is pressed
            switch (Taste)
            {
            case Key.C:                     // copy marked area
                objInkCanvas.CopySelection();
                break;

            case Key.O:                     // open ink drawing
                Microsoft.Win32.OpenFileDialog objOpenDialog = new Microsoft.Win32.OpenFileDialog();
                objOpenDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objOpenDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objOpenDialog.FileName, FileMode.Open);
                    objInkCanvas.Strokes.Add(new StrokeCollection(objFileStream));
                    objFileStream.Dispose();
                }
                break;

            case Key.P:                     // save grafic as PNG file
                Microsoft.Win32.SaveFileDialog objPNGDialog = new Microsoft.Win32.SaveFileDialog();
                objPNGDialog.Filter = "png files (*.png)|*.png";
                if ((bool)objPNGDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objPNGDialog.FileName, FileMode.Create);
                    System.Windows.Media.Imaging.RenderTargetBitmap objRenderBitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)objInkCanvas.ActualWidth, (int)objInkCanvas.ActualHeight, 96.0, 96.0, System.Windows.Media.PixelFormats.Default);
                    objRenderBitmap.Render(objInkCanvas);
                    System.Windows.Media.Imaging.BitmapFrame      objBitmapFrame = System.Windows.Media.Imaging.BitmapFrame.Create(objRenderBitmap);
                    System.Windows.Media.Imaging.PngBitmapEncoder objImgEncoder  = new System.Windows.Media.Imaging.PngBitmapEncoder();
// alternative for JPG:								System.Windows.Media.Imaging.JpegBitmapEncoder objImgEncoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
                    objImgEncoder.Frames.Add(objBitmapFrame);
                    objImgEncoder.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.S:                             // save ink drawing
                Microsoft.Win32.SaveFileDialog objSaveDialog = new Microsoft.Win32.SaveFileDialog();
                objSaveDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objSaveDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objSaveDialog.FileName, FileMode.Create);
                    objInkCanvas.Strokes.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.V:                     // paste marked area
                objInkCanvas.Paste();
                break;

            case Key.X:                     // cut marked area
                objInkCanvas.CutSelection();
                break;
            }
        }
        else
        {         // no Ctrl key is pressed
            if (Keyboard.Modifiers == ModifierKeys.None)
            {     // only when no other modifier keys are pressed
                switch (Taste)
                {
                case Key.B:                         // next background color
                    Brush ActualBackColor = (Brush)BrushQueue.Dequeue();
                    BrushQueue.Enqueue(ActualBackColor);
                    objInkCanvas.Background = ActualBackColor;
                    break;

                case Key.C:                         // clear window content
                    objInkCanvas.Strokes.Clear();
                    break;

                case Key.D:                         // switch to draw mode
                    if (objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreHighLightSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreHighLightSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreHighLightColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Ellipse;
                        objInkCanvas.DefaultDrawingAttributes.IsHighlighter = false;
                        objInkCanvas.DefaultDrawingAttributes.Color         = StoreInkColor;
                        objInkCanvas.DefaultDrawingAttributes.Height        = StoreInkSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width         = StoreInkSizeWidth;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    break;

                case Key.E:                         // // switch to erase mode (and toggle it)
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByStroke:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;

                    case InkCanvasEditingMode.EraseByPoint:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
                        break;

                    case InkCanvasEditingMode.Ink:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;
                    }
                    break;

                case Key.H:                         // switch to highlight mode
                    if (!objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreInkSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreInkSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreInkColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.Color = StoreHighLightColor;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    objInkCanvas.DefaultDrawingAttributes.IsHighlighter = true;
                    objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Rectangle;
                    if (StoreHighLightSizeWidth > 0.0)
                    {
                        objInkCanvas.DefaultDrawingAttributes.Height = StoreHighLightSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width  = StoreHighLightSizeWidth;
                    }
                    break;

                case Key.N:                         // next foreground color
                    Color ActualFrontColor = (Color)ColorQueue.Dequeue();
                    ColorQueue.Enqueue(ActualFrontColor);
                    objInkCanvas.DefaultDrawingAttributes.Color = ActualFrontColor;
                    break;

                case Key.Q:                         // close window
                    // event is handled now
                    e.Handled = true;
                    // parent object is Window
                    ((Window)(objInkCanvas).Parent).Close();
                    break;

                case Key.S:                         // start marking
                    objInkCanvas.Select(new System.Windows.Ink.StrokeCollection());
                    break;

                case Key.OemMinus:                         // shrink brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width > 3.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width - 2.0, objInkCanvas.EraserShape.Height - 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height > 3.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height - 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width - 2.0;
                        }
                        break;
                    }
                    break;

                case Key.OemPlus:                         // enlarge brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width < 50.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width + 2.0, objInkCanvas.EraserShape.Height + 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height < 50.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height + 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width + 2.0;
                        }
                        break;
                    }
                    break;
                }
            }
        }
    }
コード例 #33
0
        internal static BitmapSourceSafeMILHandle CreateCachedBitmap(
            BitmapFrame frame,
            BitmapSourceSafeMILHandle wicSource,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            BitmapPalette palette
            )
        {
            BitmapSourceSafeMILHandle wicConverter = null;
            BitmapSourceSafeMILHandle wicConvertedSource = null;

            // For NoCache, return the original
            if (cacheOption == BitmapCacheOption.None)
            {
                return wicSource;
            }

            using (FactoryMaker factoryMaker = new FactoryMaker())
            {
                IntPtr wicFactory = factoryMaker.ImagingFactoryPtr;
                bool changeFormat = false;
                PixelFormat originalFmt = PixelFormats.Pbgra32;

                WICBitmapCreateCacheOptions wicCache = WICBitmapCreateCacheOptions.WICBitmapCacheOnLoad;
                if (cacheOption == BitmapCacheOption.OnDemand)
                {
                    wicCache = WICBitmapCreateCacheOptions.WICBitmapCacheOnDemand;
                }

                originalFmt = PixelFormat.GetPixelFormat(wicSource);
                PixelFormat destFmt = originalFmt;

                // check that we need to change the format of the bitmap
                if (0 == (createOptions & BitmapCreateOptions.PreservePixelFormat))
                {
                    if (!IsCompatibleFormat(originalFmt))
                        changeFormat = true;

                    destFmt = BitmapSource.GetClosestDUCEFormat(originalFmt, palette);
                }

                if (frame != null &&
                    (createOptions & BitmapCreateOptions.IgnoreColorProfile) == 0 &&
                    frame.ColorContexts != null &&
                    frame.ColorContexts[0] != null &&
                    frame.ColorContexts[0].IsValid &&
                    !frame._isColorCorrected &&
                    PixelFormat.GetPixelFormat(wicSource).Format != PixelFormatEnum.Extended
                    )
                {
                    ColorContext destinationColorContext;

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

                    if (destinationColorContext != null)
                    {
                        // NOTE: Never do this for a non-MIL pixel format, because the format converter has
                        // special knowledge to deal with the profile

                        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(
                                frame,
                                frame.ColorContexts[0],
                                destinationColorContext,
                                destFmt
                                );

                            wicSource = colorConvertedBitmap.WicSourceHandle;
                            frame._isColorCorrected = true;
                            conversionSuccess = true;
                            changeFormat = false;   // Changeformat no longer necessary, because destFmt already created
                            // by ColorConvertedBitmap
                        }
                        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 && changeFormat && !badColorContext)
                        {   // If the conversion failed, we first use
                            // a FormatConvertedBitmap, and then Color Convert that one...
                            changeFormat = false;

                            FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(frame, destFmt, null, 0.0);

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

                            wicSource = colorConvertedBitmap.WicSourceHandle;
                            frame._isColorCorrected = true;
                            Debug.Assert(destFmt == colorConvertedBitmap.Format);
                            changeFormat = false;   // Changeformat no longer necessary, because destFmt already created
                            // by ColorConvertedBitmap
                        }
                    }
                }

                if (changeFormat)
                {
                    // start up a format converter
                    Guid fmtDestFmt = destFmt.Guid;
                    HRESULT.Check(UnsafeNativeMethods.WICCodec.WICConvertBitmapSource(
                            ref fmtDestFmt,
                            wicSource,
                            out wicConverter));

                    // dump the converted contents into a bitmap
                    HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource(
                            wicFactory,
                            wicConverter,
                            wicCache,
                            out wicConvertedSource));
                }
                else
                {
                    // Create the unmanaged resources
                    HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource(
                            wicFactory,
                            wicSource,
                            wicCache,
                            out wicConvertedSource));
                }

                wicConvertedSource.CalculateSize();
            }

            return wicConvertedSource;
        }
コード例 #34
0
 private static BitmapFrame Rotate(BitmapFrame photo, double angle, BitmapScalingMode mode)
 {
     TransformedBitmap target = new TransformedBitmap(
         photo,
         new RotateTransform(angle, photo.PixelWidth / 2, photo.PixelHeight / 2));
     BitmapFrame thumbnail = BitmapFrame.Create(target);
     BitmapFrame newPhoto = Resize(thumbnail, photo.PixelWidth, photo.PixelHeight, mode);
     return newPhoto;
 }
コード例 #35
0
        public static BitmapFrame GetBitmapFrame(BitmapFrame photo, int width, int height, BitmapScalingMode mode)
        {
            TransformedBitmap target = new TransformedBitmap(
                photo,
                new ScaleTransform(
                    width / photo.Width * 96 / photo.DpiX,
                    height / photo.Height * 96 / photo.DpiY,
                    0, 0));
            BitmapFrame thumbnail = BitmapFrame.Create(target);
            BitmapFrame newPhoto = Resize(thumbnail, width, height, mode);

            return newPhoto;
        }
コード例 #36
0
        public void Open(System.IO.Stream Source)
        {
            File iconFile = new File();

            iconFile.Read(Source);
            foreach (Frame iconFrame in iconFile.Frames)
            {
                System.Windows.Media.Imaging.BitmapFrame frame = null;
                if (iconFrame.type == FrameType.BITMAP)
                {
                    if (iconFrame.iconImage.icHeader.biBitCount == 32)
                    {
                        byte[] pixels = iconFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, iconFrame.Width, iconFrame.Height, iconFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(iconFrame.Width, iconFrame.Height, 96, 96, PixelFormats.Bgra32, null, pixels, iconFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else if (iconFrame.iconImage.icHeader.biBitCount == 24)
                    {
                        byte[] pixels = iconFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, iconFrame.Width, iconFrame.Height, iconFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(iconFrame.Width, iconFrame.Height, 96, 96, PixelFormats.Bgr24, null, pixels, iconFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else if (iconFrame.iconImage.icHeader.biBitCount == 8)
                    {
                        byte[] pixels = iconFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, iconFrame.Width, iconFrame.Height, iconFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(iconFrame.Width, iconFrame.Height, 96, 96, PixelFormats.Indexed8, GetPalette(iconFrame.iconImage.icColors, true), pixels, iconFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else if (iconFrame.iconImage.icHeader.biBitCount == 4)
                    {
                        byte[] pixels = iconFrame.iconImage.icXOR;
                        pixels = Utilities.FlipYBuffer(pixels, iconFrame.Width, iconFrame.Height, iconFrame.iconImage.XorStride);
                        BitmapSource bp = BitmapSource.Create(iconFrame.Width, iconFrame.Height, 96, 96, PixelFormats.Indexed4, GetPalette(iconFrame.iconImage.icColors, true), pixels, iconFrame.iconImage.XorStride);
                        frame = BitmapFrame.Create(bp);
                    }
                    else
                    {
                        try
                        {
                            byte[] pixels = iconFrame.iconImage.icXOR;
                            pixels = Utilities.FlipYBuffer(pixels, iconFrame.Width, iconFrame.Height, iconFrame.iconImage.XorStride);
                            BitmapSource bp = BitmapSource.Create(iconFrame.Width, iconFrame.Height, 96, 96, PixelFormats.Indexed1, GetPalette(iconFrame.iconImage.icColors, true), pixels, iconFrame.iconImage.XorStride);
                            frame = BitmapFrame.Create(bp);
                        }
                        catch { continue; }
                    }

                    if (iconFrame.iconImage.icAND?.Length > 0)
                    {
                        RGBQUAD[] palette = new RGBQUAD[2] {
                            RGBQUAD.FromRGBA(0, 0, 0, 0), RGBQUAD.FromRGBA(255, 255, 255, 255)
                        };
                        byte[] pixels = iconFrame.iconImage.icAND;
                        pixels = Utilities.FlipYBuffer(pixels, iconFrame.Width, iconFrame.Height, iconFrame.iconImage.AndStride);
                        BitmapSource AND = BitmapSource.Create(iconFrame.Width, iconFrame.Height,
                                                               96, 96, PixelFormats.Indexed1, GetPalette(palette, true), pixels, iconFrame.iconImage.AndStride);

                        EditableBitmapImage editableXOR = new EditableBitmapImage(frame);
                        EditableBitmapImage editableAND = new EditableBitmapImage(AND);
                        for (int x = 0; x < editableXOR.PixelWidth; x++)
                        {
                            for (int y = 0; y < editableXOR.PixelHeight; y++)
                            {
                                Color px = editableAND.GetPixel(x, y);
                                if (px == Colors.White)
                                {
                                    Color c = editableXOR.GetPixel(x, y);
                                    c.A = 0;
                                    editableXOR.SetPixel(x, y, c);
                                }
                            }
                        }
                        if (frame.Format.BitsPerPixel == 32)
                        {
                            // Do nothing
                        }
                        else if (frame.Format.BitsPerPixel == 24)
                        {
                            frame = BitmapFrame.Create(editableXOR);
                        }
                        else if (frame.Format.BitsPerPixel == 8)
                        {
                            BitmapSource s = Helpers.Get8BitImage(editableXOR);
                            frame = BitmapFrame.Create(s);
                        }
                        else if (frame.Format.BitsPerPixel == 4)
                        {
                            BitmapSource s = Helpers.Get4BitImage(editableXOR);
                            frame = BitmapFrame.Create(s);
                        }
                    }
                }
                else
                {
                    try
                    {
                        PngBitmapDecoder decoder = new PngBitmapDecoder(new System.IO.MemoryStream(iconFrame.pngBuffer), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        frame = decoder.Frames[0];
                    }
                    catch
                    {
                        frame = BitmapFrame.Create(CreateEmptyBitmap(iconFrame.Width));
                    }
                }
                _Frames.Add(frame);
            }
        }
コード例 #37
0
ファイル: MainMenu.xaml.cs プロジェクト: jessetinell/Imgu
 public void CreateImageObject(string img, string filename)
 {
     _fp = new FileProperties();
     _fs = new FileStream(img, FileMode.Open);
     _decoder = BitmapDecoder.Create(_fs, BitmapCreateOptions.None, BitmapCacheOption.Default);
     _frame = _decoder.Frames[0];
     _metadata = _frame.Metadata as BitmapMetadata;
     if (_metadata != null && _metadata.DateTaken != null)
     {
         _fp.DateTaken = DateTime.Parse(_metadata.DateTaken);
         _fp.FullImagePath = img;
     }
     else
     {
         _fp.FullImagePath = img;
     }
     _fp.FileName = filename;
     _fp.FolderPath = Path.GetDirectoryName(img);
     _theImages.Add(_fp);
     _fs.Close();
 }
コード例 #38
0
ファイル: MainWindow.xaml.cs プロジェクト: petrind/SRTesis2
        /// <summary> 
        /// Sends a new jpg through the websocket 
        /// </summary> 
        /// <param name="sender"> object that called the method </param> 
        /// <param name="e"> any additional arguments </param> 
        private void bitmapReady(object sender, EventArgs e) 
        {
            ss.BroadcastData("test");
            byte[] imageBytes=null;
            // check for websocket sessions if none exist nothing needs to be done 
            if (sessionList.Count > 0)  
            { 
                if (isCamInitialized && !isPictureUpdating) 
                { 
                    isPictureUpdating = true; // picture is being updated 
 
                    try // try to get a new image 
                    {
                        if (isNaoConnect)
                        {
                            try
                            {
                                imageBytes = naoCam.getImage(); // store an image in imageBytes 
                            }
                            catch (Exception ex)
                            {
                                // display error message and write exceptions to a file 
                                MessageBox.Show("Exception occurred getting image from Nao, error log in C:\\NAOserver\\exception.txt");
                                System.IO.File.WriteAllText(@"C:\\NAOserver\\exception.txt", ex.ToString());
                            }
                        }
                        else
                        {
                            imageBytes = null;
                        }
                        if (imageBytes != null) // if the image isnt empty create a bitmap and send via websocket 
                            imageBitmap = BitmapSource.Create(currentFormat.width, currentFormat.height, 96, 96, PixelFormats.Bgr24, BitmapPalettes.WebPalette, imageBytes, currentFormat.width * 3); 
                        else
                            imageBitmap = new BitmapImage(new Uri(String.Format("{0}/Petrus.jpg", curDir)));
                        frame = BitmapFrame.Create(imageBitmap); 
 
                        // converts bitmap frames to jpg 
                        JpegBitmapEncoder converter = new JpegBitmapEncoder(); 
 
                        converter.Frames.Add(frame); 
 
                        // memory stream to save jpg to byte array 
                        MemoryStream ms = new MemoryStream(); 
 
                        converter.Save(ms); 
 
                        ms.Close(); 
 
                        byte[] bytes = ms.ToArray(); 
                             
                        // since html can convert base64strings to images, convert the image to a base64 string 
                        imageString = Convert.ToBase64String(bytes); 
 
                        // send it to all connected sessions 
                        for (int x = 0; x < sessionList.Count; x++) 
                        { 
                            sessionList[x].Send(imageString); 
                        } 
                    }
                    catch (Exception e1) 
                    { 
                        // display error message and write exceptions to a file 
                        MessageBox.Show("Exception occurred in bitmap ready, error log in C:\\NAOserver\\exception.txt. Error: " + e1.ToString()); 
                        System.IO.File.WriteAllText(@"C:\\NAOserver\\exception.txt", e1.ToString()); 
                    } 
                } 
            } 
            isPictureUpdating = false; // picture is updated 
        } 
コード例 #39
0
ファイル: BitmapEncoder.cs プロジェクト: JianwenSun/cc
        private void SaveFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions, BitmapFrame frame)
        {
            SetupFrame(frameEncodeHandle, encoderOptions);

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeInitialized;

            // Set the size
            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetSize(
                frameEncodeHandle,
                frame.PixelWidth,
                frame.PixelHeight
                ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeSizeSet;

            // Set the resolution
            double dpiX = frame.DpiX;
            double dpiY = frame.DpiY;

            if (dpiX <= 0)
            {
                dpiX = 96;
            }
            if (dpiY <= 0)
            {
                dpiY = 96;
            }

            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetResolution(
                frameEncodeHandle,
                dpiX,
                dpiY
                ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeResolutionSet;

            if (_supportsFrameThumbnails)
            {
                // Set the thumbnail.
                BitmapSource thumbnail = frame.Thumbnail;

                if (thumbnail != null)
                {
                    SafeMILHandle thumbnailHandle = thumbnail.WicSourceHandle;

                    lock (thumbnail.SyncObject)
                    {
                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetThumbnail(
                            frameEncodeHandle,
                            thumbnailHandle
                            ));

                        // Helpful for debugging stress and remote dumps
                        _encodeState = EncodeState.FrameEncodeThumbnailSet;
                    }
                }
            }

            // if the source has been color corrected, we want to use a corresponding color profile
            if (frame._isColorCorrected)
            {
                ColorContext colorContext = new ColorContext(frame.Format);
                IntPtr[] colorContextPtrs = new IntPtr[1] { colorContext.ColorContextHandle.DangerousGetHandle() };

                int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                    frameEncodeHandle,
                    1,
                    colorContextPtrs
                    );

                // It's possible that some encoders may not support color contexts so don't check hr
                if (hr == HRESULT.S_OK)
                {
                    // Helpful for debugging stress and remote dumps
                    _encodeState = EncodeState.FrameEncodeColorContextsSet;
                }
            }
            // if the caller has explicitly provided color contexts, add them to the encoder
            else
            {
                IList<ColorContext> colorContexts = frame.ColorContexts;
                if (colorContexts != null && colorContexts.Count > 0)
                {             
                    int count = colorContexts.Count;

                    // Marshal can't convert SafeMILHandle[] so we must
                    {
                        IntPtr[] colorContextPtrs = new IntPtr[count];
                        for (int i = 0; i < count; ++i)
                        {
                            colorContextPtrs[i] = colorContexts[i].ColorContextHandle.DangerousGetHandle();
                        }

                        int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                            frameEncodeHandle,
                            (uint)count,
                            colorContextPtrs
                            );

                        // It's possible that some encoders may not support color contexts so don't check hr
                        if (hr == HRESULT.S_OK)
                        {
                            // Helpful for debugging stress and remote dumps
                            _encodeState = EncodeState.FrameEncodeColorContextsSet;
                        }
                    }
                }
            }

            // Set the pixel format and palette

            lock (frame.SyncObject)
            {
                SafeMILHandle outSourceHandle = new SafeMILHandle();
                SafeMILHandle bitmapSourceHandle = frame.WicSourceHandle;
                SafeMILHandle paletteHandle = new SafeMILHandle();

                // Set the pixel format and palette of the bitmap.
                // This could (but hopefully won't) introduce a format converter.
                HRESULT.Check(UnsafeNativeMethods.WICCodec.WICSetEncoderFormat(
                    bitmapSourceHandle,
                    paletteHandle,
                    frameEncodeHandle,
                    out outSourceHandle
                    ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeFormatSet;
                _writeSourceHandles.Add(outSourceHandle);

                // Set the metadata
                if (_supportsFrameMetadata)
                {
                    BitmapMetadata metadata = frame.Metadata as BitmapMetadata;

                    // If the frame has metadata associated with a different container format, then we ignore it.
                    if (metadata != null && metadata.GuidFormat == ContainerFormat)
                    {
                        SafeMILHandle /* IWICMetadataQueryWriter */ metadataHandle = new SafeMILHandle();

                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.GetMetadataQueryWriter(
                            frameEncodeHandle,
                            out metadataHandle
                            ));

                        PROPVARIANT propVar = new PROPVARIANT();

                        try
                        {
                            propVar.Init(metadata);

                            lock (metadata.SyncObject)
                            {
                                HRESULT.Check(UnsafeNativeMethods.WICMetadataQueryWriter.SetMetadataByName(
                                    metadataHandle,
                                    "/",
                                    ref propVar
                                    ));

                                // Helpful for debugging stress and remote dumps
                                _encodeState = EncodeState.FrameEncodeMetadataSet;
                            }
                        }
                        finally
                        {
                            propVar.Clear();
                        }
                    }
                }

                Int32Rect r = new Int32Rect();
                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.WriteSource(
                    frameEncodeHandle,
                    outSourceHandle,
                    ref r
                    ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeSourceWritten;

                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.Commit(
                    frameEncodeHandle
                    ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeCommitted;
            }
        }
コード例 #40
0
        ///
        /// We're copying the algorithm Windows uses to pick icons.
        /// The comments and implementation are based on core\ntuser\client\clres.c
        ///
        /// MatchImage
        /// 
        /// This function takes LPINTs for width & height in case of "real size".
        /// For this option, we use dimensions of 1st icon in resdir as size to
        /// load, instead of system metrics.
        /// Returns a number that measures how "far away" the given image is
        /// from a desired one.  The value is 0 for an exact match.  Note that our
        /// formula has the following properties:
        ///     (1) Differences in width/height count much more than differences in
        ///             color format.
        ///     (2) Bigger images are better than smaller, since shrinking produces
        ///             better results than stretching.
        ///     (3) Color matching is done by the difference in bit depth.  No
        ///             preference is given to having a candidate equally different
        ///             above and below the target.
        ///
        /// The formula is the sum of the following terms:
        ///     abs(bppCandidate - bppTarget)
        ///     abs(cxCandidate - cxTarget), times 2 if the image is
        ///        narrower than what we'd like.  This is because we will get a
        ///        better result when consolidating more information into a smaller
        ///        space, than when extrapolating from less information to more.
        ///     abs(cxCandidate - cxTarget), times 2 if the image is
        ///        shorter than what we'd like.  This is for the same reason as
        ///        the width.
        ///
        /// Let's step through an example.  Suppose we want a 4bpp (16 color),
        /// 32x32 image.  We would choose the various candidates in the following order:
        ///
        /// Candidate     Score   Formula
        /// 
        /// 32x32x4bpp  = 0       abs(32-32)*1 + abs(32-32)*1 + 2*abs(4-4)*1
        /// 32x32x2bpp  = 4
        /// 32x32x8bpp  = 8
        /// 32x32x16bpp = 24
        /// 48x48x4bpp  = 32
        /// 48x48x2bpp  = 36
        /// 48x48x8bpp  = 40
        /// 32x32x32bpp = 56
        /// 48x48x16bpp = 56      abs(48-32)*1 + abs(48-32)*1 + 2*abs(16-4)*1
        /// 16x16x4bpp  = 64
        /// 16x16x2bpp  = 68      abs(16-32)*2 + abs(16-32)*2 + 2*abs(2-4)*1
        /// 16x16x8bpp  = 72
        /// 48x48x32bpp = 88      abs(48-32)*1 + abs(48-32)*1 + 2*abs(32-4)*1
        /// 16x16x16bpp = 88
        /// 16x16x32bpp = 104
        private static int MatchImage(BitmapFrame frame, Size size, int bpp)
        {
            /*
             * Here are the rules for our "match" formula:
             *      (1) A close size match is much preferable to a color match
             *      (2) Bigger icons are better than smaller
             *      (3) The smaller the difference in bit depths the better
             */
            int score = 2 * MyAbs(bpp, s_systemBitDepth, false) +
                    MyAbs(frame.PixelWidth, (int)size.Width, true) +
                    MyAbs(frame.PixelHeight, (int)size.Height, true);

            return score;
        }
コード例 #41
0
        private static NativeMethods.IconHandle CreateIconHandleFromBitmapFrame(BitmapFrame sourceBitmapFrame)
        {
            Invariant.Assert(sourceBitmapFrame != null, "sourceBitmapFrame cannot be null here");

            BitmapSource bitmapSource = sourceBitmapFrame;
            
            if (bitmapSource.Format != PixelFormats.Bgra32 && bitmapSource.Format != PixelFormats.Pbgra32)
            {
                bitmapSource = new FormatConvertedBitmap(bitmapSource, PixelFormats.Bgra32, null, 0.0);
            }
            
            // data used by CopyPixels
            int w = bitmapSource.PixelWidth;
            int h = bitmapSource.PixelHeight;
            int bpp = bitmapSource.Format.BitsPerPixel;
            // ensuring it is in 4 byte increments since we're dealing
            // with ARGB fromat
            int stride = (bpp * w + 31) / 32 * 4;
            int sizeCopyPixels = stride * h;
            byte[] xor = new byte[sizeCopyPixels];
            bitmapSource.CopyPixels(xor, stride, 0);

            return CreateIconCursor(xor, w, h, 0, 0, true);
        }
コード例 #42
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                String url        = Page.Request.QueryString["url"];
                String fromMemory = Page.Request.QueryString["memory"];
                if (url != null)
                {
                    try
                    {
                        lblError.Text = "";
                        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                        request.UseDefaultCredentials = true;

                        System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                        System.IO.Stream responseStream = response.GetResponseStream();

                        string fileName = Path.GetRandomFileName();

                        //new System.Drawing.Bitmap(responseStream).Save(@"C:\Digitas\" + fileName + ".tif", System.Drawing.Imaging.ImageFormat.Tiff);

                        //System.IO.Stream tbStream = File.OpenRead(@"C:\Digitas\" + fileName + ".tif");

                        decoder = new TiffBitmapDecoder(responseStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        int pagecount = decoder.Frames.Count;


                        //lblError.Text = pagecount.ToString();
                        TiffBitmapEncoder encoderFile = new TiffBitmapEncoder();
                        images = new List <System.Drawing.Image>();

                        for (int i = 0; i < decoder.Frames.Count; i++)
                        {
                            MemoryStream      ms      = new MemoryStream();
                            TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                            //ddlPaginas.Items.Add("Página " + (i + 1));
                            encoder.Frames.Add(decoder.Frames[i]);
                            encoder.Save(ms);
                            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                            images.Add(img);

                            MemoryStream ms3 = new MemoryStream();
                            images[i].Save(ms3, System.Drawing.Imaging.ImageFormat.Tiff);
                            System.Windows.Media.Imaging.BitmapFrame bmFrame = System.Windows.Media.Imaging.BitmapFrame.Create(ms3);
                            encoderFile.Frames.Add(bmFrame);
                        }
                        Session["images"] = images;
                        System.IO.FileStream fsTemp = new System.IO.FileStream(@"C:\Digitas\" + fileName + ".tif", FileMode.Create);
                        encoderFile.Save(fsTemp);
                        fsTemp.Close();

                        //Response.ContentType = "image/jpeg";
                        //new System.Drawing.Bitmap(responseStream).Save(@"C:\Digitas\Temp_Tiff.tif", System.Drawing.Imaging.ImageFormat.Tiff);


                        iTextSharp.text.Document      document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 5, 5, 5, 5);
                        iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Digitas\" + fileName + ".pdf", System.IO.FileMode.Create));

                        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Digitas\" + fileName + ".tif");
                        int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

                        document.Open();

                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                        for (int k = 0; k < total; ++k)
                        {
                            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
                            // scale the image to fit in the page
                            img.ScaleAbsolute(600, 800);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }
                        document.Close();
                        Response.ContentType = "Application/pdf";
                        Response.TransmitFile(@"C:\Digitas\" + fileName + ".pdf");

                        /*
                         * System.Drawing.Image img = System.Drawing.Image.FromStream(responseStream);
                         *
                         * Tiff image = Tiff.ClientOpen("memory", "r", responseStream, new TiffStream());
                         *
                         * if (img == null)
                         * {
                         *  lblError.Text = "Null image s";
                         * }
                         * else
                         * {
                         *  img.Save(@"C:\Digitas\digit.tif");
                         * }
                         *
                         * if (image == null)
                         * {
                         *  lblError.Text = "Null image tiff";
                         * }
                         * else
                         * {
                         *  var num = image.NumberOfDirectories();
                         *  lblError.Text = num.ToString();
                         * }
                         */



                        /*
                         * MemoryStream ms2 = new MemoryStream();
                         * images[0].Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                         * //BinaryReader br = new BinaryReader(ms2);
                         * //Byte[] bytes = br.ReadBytes((Int32)ms2.Length);
                         * byte[] bytes = ms2.ToArray();
                         * //string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                         * string base64String = Convert.ToBase64String(bytes);
                         * //string base64String = Convert.ToBase64String((byte[])img);
                         * Image1.ImageUrl = "data:image/jpg;base64," + base64String;
                         */
                        /*
                         * Session["images"] = images;
                         *
                         *
                         * var document = new Document(PageSize.LETTER, 5, 5, 5, 5);
                         *
                         * // Create a new PdfWriter object, specifying the output stream
                         * var output = new MemoryStream();
                         * var writer = PdfWriter.GetInstance(document, output);
                         *
                         * document.Open();
                         *
                         * for (int i = 0; i < images.Count; i++)
                         * {
                         *  var image = iTextSharp.text.Image.GetInstance(images[i], iTextSharp.text.BaseColor.WHITE);
                         *  image.ScaleAbsolute(600, 800);
                         *  document.Add(image);
                         *  document.NewPage();
                         * }
                         *
                         * document.Close();
                         *
                         * Response.ContentType = "application/pdf";
                         * //Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Receipt-{0}.pdf", txtOrderID.Text));
                         * Response.BinaryWrite(output.ToArray());
                         *
                         *
                         * // Open the Document for writing
                         *
                         * //img.Save(@"C:\Digitas\digit2.jpg");
                         *
                         * //Response.ContentType = "image/jpeg";
                         * //new System.Drawing.Bitmap(ms).Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                         *
                         * //HttpContext.Current.Response.Flush();
                         * //HttpContext.Current.Response.SuppressContent = true;
                         * //HttpContext.Current.ApplicationInstance.CompleteRequest();
                         *
                         * /*HttpContext.Current.Response.Flush();
                         * HttpContext.Current.Response.SuppressContent = true;
                         * HttpContext.Current.ApplicationInstance.CompleteRequest();
                         *
                         * /*FileWebRequest request = (FileWebRequest)WebRequest.Create(url);
                         *
                         * request.UseDefaultCredentials = true;
                         *
                         * System.Net.FileWebResponse response = (System.Net.FileWebResponse)request.GetResponse();*/

                        //System.IO.Stream responseStream = response.GetResponseStream();

                        /*System.IO.StreamReader reader = new StreamReader(responseStream);
                         *
                         * if (reader == null)
                         * {
                         *  lblError.Text = "Null";
                         * }
                         * else
                         * {
                         *  MemoryStream ms = new MemoryStream();
                         *  responseStream.CopyTo(ms);
                         *  /*responseStream.Close();
                         *  reader.Close();
                         *
                         *  Tiff image = Tiff.ClientOpen("memory", "r", ms, new TiffStream());
                         *
                         *  if (image == null)
                         *  {
                         *      lblError.Text = "Null image";
                         *  }
                         *  lblError.Text = ms.Length.ToString();
                         *  using (FileStream file = new FileStream(@"C:\Digitas\digit.tif", FileMode.Create, System.IO.FileAccess.Write))
                         *  {
                         *      byte[] bytes = new byte[ms.Length];
                         *      ms.Read(bytes, 0, (int)ms.Length);
                         *      file.Write(bytes, 0, bytes.Length);
                         *      //ms.Close();
                         *      //file.Close();
                         *  }
                         *
                         *  Tiff image = Tiff.Open(@"C:\Digitas\digit.tif", "r");
                         *  if (image == null)
                         *  {
                         *      lblError.Text = "Null image";
                         *  }
                         *  else
                         *  {
                         *      var num = image.NumberOfDirectories();
                         *      lblError.Text = num.ToString();
                         *  }
                         *
                         *
                         * }*/
                    }
                    catch (System.Exception ex)
                    {
                        lblError.Text = lblError.Text + " 0.- " + ex.Message;
                    }
                }
                else if (fromMemory == null)
                {
                    try
                    {
                        RPPMain.SharepointLibrary spLibrary = new RPPMain.SharepointLibrary("http://servidors04/sitios/digitalizacion", "Seccion Primera", "autostore", "Rpp1234");
                        //RPPMain.SharepointLibrary spLibrary = new RPPMain.SharepointLibrary("http://servidors04/sitios/digitalizacion", "Seccion Primera", "administrador", "Zmy45r1");

                        //int documentoID = int.Parse(Page.Request.QueryString["documentoID"]);

                        String reg_act_tomo     = Page.Request.QueryString["tomo"];
                        String reg_act_semestre = Page.Request.QueryString["semestre"];
                        String reg_act_año      = Page.Request.QueryString["anio"];
                        String reg_act_seccion  = Page.Request.QueryString["seccion"];
                        String reg_act_serie    = Page.Request.QueryString["serie"];
                        String reg_act_partida  = Page.Request.QueryString["partida"];
                        String reg_act_libro    = Page.Request.QueryString["libro"];

                        bool   firstParameter  = true;
                        bool   secondParameter = false;
                        bool   nextParameter   = false;
                        string query           = "";

                        if (reg_act_tomo.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_semestre.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_año.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_seccion.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_serie.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_partida.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq></And>";
                                }
                            }
                        }

                        if (reg_act_libro.Length > 0)
                        {
                            if (firstParameter)
                            {
                                query           = query + "<And><Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq>";
                                firstParameter  = false;
                                secondParameter = true;
                            }
                            else
                            {
                                if (secondParameter)
                                {
                                    query           = query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq></And>";
                                    secondParameter = false;
                                    nextParameter   = true;
                                }
                                else
                                {
                                    query = "<And>" + query + "<Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq></And>";
                                }
                            }
                        }

                        query = "<View><Query><Where>" + query + "</Where></Query></View>";

                        query = string.Format(@"<View>
                                                <Query>
                                                    <Where>
                                                        <And>
                                                            <And>
                                                                <And>
                                                                    <And>
                                                                        <And>
                                                                            <And>
                                                                                <Eq><FieldRef Name='Fec_Reg_Tomo' /><Value Type='Text'>{0}</Value></Eq>
                                                                                <Eq><FieldRef Name='Fec_Reg_Semestre' /><Value Type='Text'>{1}</Value></Eq>
                                                                            </And>
                                                                            <Eq><FieldRef Name='Fec_Reg_A_x00f1_o_x0020_Semestre' /><Value Type='Text'>{2}</Value></Eq>
                                                                        </And>
                                                                        <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{3}</Value></Eq>
                                                                    </And>
                                                                    <Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{4}</Value></Eq>
                                                                </And>
                                                                <Eq><FieldRef Name='Partida' /><Value Type='Text'>{5}</Value></Eq>
                                                            </And>
                                                            <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{6}</Value></Eq>                                                            
                                                        </And>
                                                    </Where>
                                                </Query>
                                            </View>",
                                              reg_act_tomo,
                                              reg_act_semestre,
                                              reg_act_año,
                                              reg_act_seccion,
                                              reg_act_serie,
                                              reg_act_partida,
                                              reg_act_libro);


                        /*query = string.Format(@query,
                         *          reg_act_tomo,
                         *          reg_act_semestre,
                         *          reg_act_año,
                         *          reg_act_seccion,
                         *          reg_act_serie,
                         *          reg_act_partida,
                         *          reg_act_libro);*/

                        /*string query = string.Format(@"<View>
                         *                             <Query>
                         *                                 <Where>
                         *                                     <And>
                         *                                     <And>
                         *                                     <And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Libro' /><Value Type='Text'>{0}</Value></Eq>
                         *                                         <Eq><FieldRef Name='Partida' /><Value Type='Text'>{1}</Value></Eq>
                         *                                     </And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Seccion' /><Value Type='Text'>{2}</Value></Eq>
                         *                                     </And>
                         *                                         <Eq><FieldRef Name='Fec_Reg_Partida' /><Value Type='Text'>{3}</Value></Eq>
                         *                                     </And>
                         *                                 </Where>
                         *                             </Query>
                         *                         </View>",
                         *     2384,
                         *     1,
                         *     1,
                         *     "A");*/

                        System.Collections.ArrayList arlRows = spLibrary.GetLibraryItem(query);

                        if (arlRows.Count > 0)
                        {
                            lblError.Text = "";

                            Microsoft.SharePoint.Client.ListItem      itemRepositorio = (Microsoft.SharePoint.Client.ListItem)arlRows[0];
                            Dictionary <string, object>               dc   = (Dictionary <string, object>)itemRepositorio.FieldValues;
                            Microsoft.SharePoint.Client.FieldUrlValue fURl = (Microsoft.SharePoint.Client.FieldUrlValue)dc["Pagina"];

                            try
                            {
                                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(fURl.Url);
                                request.UseDefaultCredentials = true;

                                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                                System.IO.Stream responseStream = response.GetResponseStream();

                                /*Response.ContentType = "image/jpeg";
                                 * new System.Drawing.Bitmap(responseStream).Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                 *
                                 * HttpContext.Current.Response.Flush();
                                 * HttpContext.Current.Response.SuppressContent = true;
                                 * HttpContext.Current.ApplicationInstance.CompleteRequest();*/
                            }
                            catch (System.Exception ex)
                            {
                                lblError.Text = lblError.Text + " 1.- " + ex.Message;
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        lblError.Text = lblError.Text + " 2.- " + ex.Message;
                    }
                }
                else if (fromMemory != null)
                {
                    try
                    {
                        images = new List <System.Drawing.Image>();
                        images = (List <System.Drawing.Image>)Session["images"];

                        TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                        MemoryStream      ms3     = new MemoryStream();

                        for (int i = 0; i < images.Count; i++)
                        {
                            //ddlPaginas.Items.Add("Página " + (i + 1));
                            ms3 = new MemoryStream();
                            images[i].Save(ms3, System.Drawing.Imaging.ImageFormat.Tiff);
                            System.Windows.Media.Imaging.BitmapFrame bmFrame = System.Windows.Media.Imaging.BitmapFrame.Create(ms3);
                            encoder.Frames.Add(bmFrame);
                        }

                        /*
                         * MemoryStream ms2 = new MemoryStream();
                         * images[0].Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
                         * byte[] bytes = ms2.ToArray();
                         * string base64String = Convert.ToBase64String(bytes);
                         * Image1.ImageUrl = "data:image/jpg;base64," + base64String;
                         *
                         * /*string fileName = Path.GetTempFileName();
                         *
                         * lblError.Text = fileName;
                         *
                         * Session["tempFileName"] = fileName;*/

                        string fileName = Path.GetRandomFileName();

                        Session["tempFileName"] = fileName + ".tif";

                        System.IO.FileStream fsTemp = new System.IO.FileStream(@"C:\Digitas\" + fileName + ".tif", FileMode.Create);
                        encoder.Save(fsTemp);
                        fsTemp.Close();



                        iTextSharp.text.Document      document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 5, 5, 5, 5);
                        iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Digitas\" + fileName + ".pdf", System.IO.FileMode.Create));

                        System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Digitas\" + fileName + ".tif");
                        int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

                        document.Open();
                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                        for (int k = 0; k < total; ++k)
                        {
                            bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
                            // scale the image to fit in the page
                            img.ScaleAbsolute(600, 800);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }
                        document.Close();

                        Response.ContentType = "Application/pdf";
                        Response.TransmitFile(@"C:\Digitas\" + fileName + ".pdf");
                    }
                    catch (Exception exc)
                    {
                        lblError.Text = exc.Message;
                    }
                }
            }
            else
            {
                //decoder = (TiffBitmapDecoder)Session["decoder"];
                images = new List <System.Drawing.Image>();
                images = (List <System.Drawing.Image>)Session["images"];
            }
        }