Example #1
1
        /// <summary>
        /// Creates a WPF bitmap source from an GDI image.
        /// </summary>
        public static BitmapSource CreateBitmapSource(Image image)
        {
            MemoryStream stream = new MemoryStream();
            //int width = image.Width;
            //int height = image.Height;
            //double dpiX = image.HorizontalResolution;
            //double dpiY = image.VerticalResolution;
            //System.Windows.Media.PixelFormat pixelformat = PixelFormats.Default;
            BitmapSource bitmapSource = null;

            try
            {
                string guid = image.RawFormat.Guid.ToString("B").ToUpper();
                switch (guid)
                {
                    case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}":  // memoryBMP
                    case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}":  // bmp
                        image.Save(stream, ImageFormat.Bmp);
                        stream.Position = 0;
                        BmpBitmapDecoder bmpDecoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        bitmapSource = bmpDecoder.Frames[0];
                        break;

                    case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}":  // png
                        image.Save(stream, ImageFormat.Png);
                        stream.Position = 0;
                        PngBitmapDecoder pngDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        bitmapSource = pngDecoder.Frames[0];
                        break;

                    case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}":  // jpeg
                        image.Save(stream, ImageFormat.Jpeg);
                        JpegBitmapDecoder jpegDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        stream.Position = 0;
                        bitmapSource = jpegDecoder.Frames[0];
                        break;

                    case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}":  // gif
                        image.Save(stream, ImageFormat.Gif);
                        GifBitmapDecoder gifDecoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        stream.Position = 0;
                        bitmapSource = gifDecoder.Frames[0];
                        break;

                    case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}":  // tiff
                        image.Save(stream, ImageFormat.Tiff);
                        TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        stream.Position = 0;
                        bitmapSource = tiffDecoder.Frames[0];
                        break;

                    case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}":  // icon
                        image.Save(stream, ImageFormat.Icon);
                        IconBitmapDecoder iconDecoder = new IconBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        stream.Position = 0;
                        bitmapSource = iconDecoder.Frames[0];
                        break;

                    case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}":  // emf
                    case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}":  // wmf
                    case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}":  // exif
                    case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}":  // photoCD
                    case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}":  // flashPIX

                    default:
                        throw new InvalidOperationException("Unsupported image format.");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ImageHelper.CreateBitmapSource failed:" + ex.Message);
            }
            finally
            {
                //if (stream != null)
                //  stream.Close();
            }
            return bitmapSource;
        }
Example #2
0
        public JpegHelper(string path)
        {            
            jpegPath = path;
            
            using (Stream jpegStreamIn = File.Open(jpegPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            {
                JpegBitmapDecoder decoder = null;
                // The orginial decoder method will cause problem
                // if decorder create by delay, it will fast the read speed, but can hardly write
                // if decoder created by Preserve, it will be slow
                try
                {
                    decoder = new JpegBitmapDecoder(jpegStreamIn, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand);
                }
                catch(Exception e)
                {
                    Image x = Image.FromStream(jpegStreamIn);
                    if (x.RawFormat != ImageFormat.Jpeg)
                        throw new FormatException();

                    throw e;
                }

                var bitmapFrame = decoder.Frames[0];
                //bitmapFrameCopy = BitmapFrame.Create(decoder.Frames[0]);
                
                var orgMetadata = (BitmapMetadata)bitmapFrame.Metadata;

                Keywords = orgMetadata.Keywords == null ? new List<string>() : new List<string>(orgMetadata.Keywords);    
            }
                      
        }
Example #3
0
        private static ImageSource RetriveImage(string imagePath)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(imagePath);

            switch (imagePath.Substring(imagePath.Length - 3))
            {
            case "jpg":
                var jpgDecoder = new System.Windows.Media.Imaging.JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(jpgDecoder.Frames[0]);

            case "bmp":
                var bmpDecoder = new System.Windows.Media.Imaging.BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(bmpDecoder.Frames[0]);

            case "png":
                var pngDecoder = new System.Windows.Media.Imaging.PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(pngDecoder.Frames[0]);

            case "ico":
                var icoDecoder = new System.Windows.Media.Imaging.IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(icoDecoder.Frames[0]);

            default:
                return(null);
            }
        }
Example #4
0
        //This method takes in a list of imagedata found in the database, creates a new gifbitmapencoder and puts the images into the newly formed gif.
        public GifBitmapEncoder Create(IEnumerable<ImageData> listOFImages, int frameRate = 2)
        {
            JpegBitmapDecoder decoder;
            BitmapSource convertToBmp;
            GifBitmapEncoder newGif = new GifBitmapEncoder();

            //Run through the list of ImageData from the database
            foreach (BlueMarble.Data.ImageData indImage in listOFImages)
            {
                //Get the image based off of the url found on the data of the image
                var request = WebRequest.Create(indImage.Lowresurl);

                using (var response = request.GetResponse())
                using (var webstream = response.GetResponseStream())
                {
                    decoder = new JpegBitmapDecoder(webstream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    convertToBmp = decoder.Frames[0];

                    //The amount of times you store the image in the in the gif, the slower it appears to transition, default for this speed is 2
                    for (int x = 0; x < frameRate; x++)
                    {
                        newGif.Frames.Add(BitmapFrame.Create(convertToBmp));
                    }
                }

            }

            return newGif;
        }
Example #5
0
        public static Color CalculateAverageColorFor(Uri image)
        {
            var jpgImage = new JpegBitmapDecoder(image, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
            int width = jpgImage.Frames[0].PixelWidth;
            int height = jpgImage.Frames[0].PixelHeight;
            var imgBytes = new byte[width * 4 * height];
            jpgImage.Frames[0].CopyPixels(imgBytes, width * 4, 0);
            long sumB = 0, sumG = 0, sumR = 0;
            for (int x = 0; x < height * width; x++)
            {

                int p = x * 4;
                byte b = imgBytes[p + 0];
                byte g = imgBytes[p + 1];
                byte r = imgBytes[p + 2];
                sumB += b;
                sumG += g;
                sumR += r;

            }

            long avgb = sumB / (width * height);
            long avgg = sumG / (width * height);
            long avgr = sumR / (width * height);
            return Color.FromArgb(0, (int)avgr, (int)avgg, (int)avgb);
        }
Example #6
0
 // converts only JPG image to byte[]
 public static byte[] ImageToByteArray(string filename)
 {
     JpegBitmapDecoder myImage = new JpegBitmapDecoder(new Uri(filename, UriKind.RelativeOrAbsolute), BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
     byte[] myImageBytes = new byte[myImage.Frames[0].PixelWidth * 4 * myImage.Frames[0].PixelHeight];
     myImage.Frames[0].CopyPixels(myImageBytes, myImage.Frames[0].PixelWidth * 4, 0);
     return myImageBytes;
 }
		private IEnumerable<ClaudiaImage> ExtractImages(Stream stream)
		{
			using (var zipReader = ZipReader.Open(stream))
			{
				while (zipReader.MoveToNextEntry() == true)
				{
					using (var imageStream = zipReader.OpenEntryStream())
					{
						var fileName = zipReader.Entry.Key;
						if (fileName.EndsWith(".jpg") == true)
						{
							var decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
							var imageSource = decoder.Frames[0];
							imageSource.Freeze();

							yield return new ClaudiaImage
							{
								Title = fileName,
								Image = imageSource
							};
						}
						else
						{
							imageStream.SkipEntry();
						}
					}
				}
			}
		}
Example #8
0
        public void Preprocess()
        {
            JpegBitmapDecoder d = new JpegBitmapDecoder(new Uri(FileData.FullName), BitmapCreateOptions.None, BitmapCacheOption.Default);
            BitmapFrame bf = d.Frames[0];

            if (bf.Metadata != null)
            {
                BitmapMetadata bm = bf.Metadata as BitmapMetadata;
                if (bm != null)
                {
                    string taken = bm.DateTaken;
                    if (taken != null)
                    {
                        DateTime.TryParse(taken, out ImageTaken);
                    }
                }
            }
            if(bf.Thumbnail != null)
            {
                Thumbnail = bf.Thumbnail;
            }
            else
            {

                double scale = 100/bf.PixelHeight;
                Transform tf = new ScaleTransform(scale,scale);
                TransformedBitmap tb = new TransformedBitmap(bf, tf);
                Thumbnail = new WriteableBitmap(tb);
            }
            Interlocked.Increment(ref Parent.PreprocessedCount);
        }
Example #9
0
 public static void WriteMetadata(string filename, string description) {
     using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) {
         var bitmapDecoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         var bitmapFrame = bitmapDecoder.Frames[0];
         var metadataWriter = bitmapFrame.CreateInPlaceBitmapMetadataWriter();
         metadataWriter.SetQuery("/app13/irb/8bimiptc/iptc/description", description);
     }
 }
Example #10
0
 public override ImageData Read(Stream file, ImageMetaData info)
 {
     var decoder = new JpegBitmapDecoder (file,
         BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
     var frame = decoder.Frames[0];
     frame.Freeze();
     return new ImageData (frame, info);
 }
Example #11
0
 private void updateImage()
 {
     
     this.Dispatcher.BeginInvoke(new Action(() =>
     {
         this.jpegDec = new JpegBitmapDecoder(this.receivedData, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         this.bitmapsorce = this.jpegDec.Frames[0];
         this.TestImage.Source = this.bitmapsorce;
     }));
 }
Example #12
0
 public override void Show(System.Windows.Controls.ContentControl contentControl, object writer)
 {
     FileStream imageStreamSource = new FileStream(this.FullFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     Image image = new Image();
     JpegBitmapDecoder jpgDecoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     for (int i = 0; i < jpgDecoder.Frames.Count; i++)
     {
         BitmapSource bitMapSource = jpgDecoder.Frames[i];
         image.Source = bitMapSource;
     }
     contentControl.Content = image;
 }
Example #13
0
 private void btn_Click(object sender, RoutedEventArgs e)
 {
     FileStream stream = new FileStream("../../Images/FirstStarbucks.jpg", FileMode.Open);
     JpegBitmapDecoder decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     BitmapSource bitmapSource = decoder.Frames[0];
     mImage.Source = bitmapSource;
     BitmapFrame bmf = BitmapFrame.Create(bitmapSource);
     BitmapMetadata mMetadata = bmf.Metadata as BitmapMetadata;
     mCamera.Content = "照相機: " + mMetadata.CameraModel;
     mData.Content = "拍攝時間: " + mMetadata.DateTaken;
     mISO.Content = "ISO速度: " + mMetadata.GetQuery("/app1/ifd/exif/subifd:{uint=34855}").ToString();
     
 }
Example #14
0
        //BlueMarble.Data.MarbleDataBase dataBase;
        public void InitiateVideo(int rollNum, int frameRate)
        {
            FileStream stream = new FileStream("new.gif", FileMode.Create);

            Stream imageStream = new FileStream("images.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);
            JpegBitmapDecoder decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource image = decoder.Frames[0];
            GifBitmapEncoder newGif = new GifBitmapEncoder();

            for (int x = 0; x < 10; x++)
            {
                newGif.Frames.Add(BitmapFrame.Create(image));
            }
            bool duration = newGif.Frames[0].HasAnimatedProperties;

            imageStream = new FileStream("images2.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);
            decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            image = decoder.Frames[0];

            for (int x = 0; x < 10; x++)
            {
                newGif.Frames.Add(BitmapFrame.Create(image));
            }

            imageStream = new FileStream("images3.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);
            decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            image = decoder.Frames[0];
            for (int x = 0; x < 10; x++)
            {
                newGif.Frames.Add(BitmapFrame.Create(image));
            }

            var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");

            using (var response = request.GetResponse())
            using (var webstream = response.GetResponseStream())
            {
                decoder = new JpegBitmapDecoder(webstream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                //imageStream = Bitmap.FromStream(webstream);
            }
            //decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            image = decoder.Frames[0];
            for (int x = 0; x < 10; x++)
            {
                newGif.Frames.Add(BitmapFrame.Create(image));
            }

            newGif.Save(stream);
        }
		private async Task<ImageSource> FetchImageAsync()
		{
			using (var httpClient = new HttpClient())
			{
				using (var stream = await httpClient.GetStreamAsync(
					"http://msdn.microsoft.com/ja-jp/hh561749.claudia_wp_01(l=ja-jp).jpg").
					ConfigureAwait(false))
				{
					var decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
					var imageSource = decoder.Frames[0];
					imageSource.Freeze();

					return imageSource;
				}
			}
		}
Example #16
0
        public bool Save()
        {
            try
            {
                using (var jpegStream = new FileStream(_filePath, FileMode.Open, FileAccess.ReadWrite))
                {
                    var jpgDecoder = new JpegBitmapDecoder(jpegStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    var jpegFrames = jpgDecoder.Frames[0];
                    var jpgInplace = jpegFrames.CreateInPlaceBitmapMetadataWriter();

                    jpgInplace.Title = Title;
                    jpgInplace.Subject = Subject;
                    jpgInplace.Rating = Rating;
                    jpgInplace.Keywords = new ReadOnlyCollection<string>(Keywords);
                    jpgInplace.Comment = Comments;

                    _saved = false;

                    if (jpgInplace.TrySave())
                    {
                        jpegStream.Close();
                        _saved = true;
                    }
                    else
                    {
                        jpegStream.Close();

                        var start = new ThreadStart(padAndSave);
                        var myThread = new Thread(start);

                        myThread.SetApartmentState(ApartmentState.STA);
                        myThread.Start();

                        while (myThread.IsAlive)
                        {

                        }
                    }
                }
            }
            catch
            {
                _saved = false;
            }

            return _saved;
        }
Example #17
0
        ImageSource FromStream(Stream stream)
        {
            ImageSource ret = null;
             if(stream != null)
             {
            {
               // try png decoder
               try
               {
                  JpegBitmapDecoder bitmapDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                  ImageSource m = bitmapDecoder.Frames[0];

                  if(m != null)
                  {
                     ret = m;
                  }
               }
               catch
               {
                  ret = null;
               }

               // try jpeg decoder
               if(ret == null)
               {
                  try
                  {
                     stream.Seek(0, SeekOrigin.Begin);

                     PngBitmapDecoder bitmapDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                     ImageSource m = bitmapDecoder.Frames[0];

                     if(m != null)
                     {
                        ret = m;
                     }
                  }
                  catch
                  {
                     ret = null;
                  }
               }
            }
             }
             return ret;
        }
Example #18
0
        /// <summary>
        /// Get image basic information for further rendering usage
        /// </summary>
        /// <param name="imageFilePath">Path to the image file</param>
        /// <returns>Image width and height</returns>
        public static Tuple<int, int> GetImageInfoForRendering(string imageFilePath)
        {
            try
            {
                using (var s = File.OpenRead(imageFilePath))
                {
                    JpegBitmapDecoder decoder = new JpegBitmapDecoder(s, BitmapCreateOptions.None, BitmapCacheOption.None);
                    var frame = decoder.Frames.First();

                    // Store image width and height for following rendering
                    return new Tuple<int, int>(frame.PixelWidth, frame.PixelHeight);
                }
            }
            catch
            {
                return new Tuple<int, int>(0, 0);
            }
        }
Example #19
0
        public static BitmapSource ToImage(byte[] arg, TypeImagen tipo) {
            BitmapSource temporigen = null;
            if(arg != null){
                System.IO.MemoryStream ms = new System.IO.MemoryStream(arg);

                switch (tipo)
                {
                    case TypeImagen.BMP:

                        BmpBitmapDecoder bmpdeco = new BmpBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        temporigen = bmpdeco.Frames[0];
                        break;
                    case TypeImagen.JPG:
                        
                        JpegBitmapDecoder jpgdeco = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        temporigen = jpgdeco.Frames[0];
                        break;
                }
            }
            return temporigen;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="fileName"></param>
 /// <exception cref="AgrumentException">Can't open file</exception>
 public EXIFFileWorker(string pathToFile)
     : this()
 {
     m_pathToFile = pathToFile;
     if (String.IsNullOrEmpty(pathToFile))
         throw new ArgumentNullException("pathToFile");
     if (!m_FileManager.Exists(pathToFile))
         throw new ArgumentException("File not found", "pathToFile");
     try
     {
         if (m_jpegStreamIn  != null)
             m_jpegStreamIn .Close();
         m_jpegStreamIn  = m_FileManager.Open(pathToFile, FileMode.Open, FileAccess.Read);
     }
     catch (Exception e)
     {
         throw new ArgumentException("Can't open file", "pathToFile", e);
     }
     // unpack photo and make decoder
     m_Decoder = new JpegBitmapDecoder(m_jpegStreamIn, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
     m_Exif = (BitmapMetadata)m_Decoder.Frames[0].Metadata.Clone();
 }
Example #21
0
 public PictogramType(piktogramy pikt)
 {
     Name = pikt.name;
     try
     {
         Categories = new CategoryType(pikt.category.name);
     }
     catch (Exception e)
     {
     }
     using (var stream = new MemoryStream(pikt.image))
     {
         JpegBitmapDecoder decoder = new JpegBitmapDecoder(stream,
                                         BitmapCreateOptions.PreservePixelFormat,
                                         BitmapCacheOption.OnLoad);
         BitmapSource bitmapSource = decoder.Frames[0];
         bitmapSource.Freeze();
         Image = bitmapSource;
     }
     Medium = System.Text.Encoding.ASCII.GetString(pikt.medium.@object);
     MediumType = (MediaTypeEnum)pikt.media_id;
 }
 /// <summary>
 /// Завантаження зображення в масив байтів
 /// </summary>
 /// <param name="path">шлях до файлу</param>
 /// <returns></returns>
 public static byte[,] LoadImage(string path)
 {
     Uri myUri = new Uri(path, UriKind.RelativeOrAbsolute);
     JpegBitmapDecoder decoder = new JpegBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
     BitmapSource bs = decoder.Frames[0];
     //Конвертуємо зображення в шкалі сірого
     FormatConvertedBitmap fcb = new FormatConvertedBitmap(bs, PixelFormats.Gray8, BitmapPalettes.BlackAndWhite, 1);
     bs = fcb;
     byte[] arr = new byte[(int)(bs.Width * bs.Height)];
     //Отримуємо пікселі
     bs.CopyPixels(arr, (int)(8 * bs.Width) / 8, 0);
     int count = 0;
     byte[,] img = new byte[(int)bs.Height, (int)bs.Width];
     //Формуємо двувимірний масив
     for (int i = 0; i < bs.Height; ++i)
     {
         for (int j = 0; j < bs.Width; ++j)
         {
             img[i, j] = arr[count++];
         }
     }
     return img;
 }
Example #23
0
        /// <summary>
        /// 从资源中恢复图像(png、ico、jpeg、bmp)
        /// </summary>
        /// <param name="nomImage"></param>
        /// <returns></returns>
        public static ImageSource ImageSource(string nomImage)
        {
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(nomImage);

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".png")) // Cas png
            {
                PngBitmapDecoder img = new System.Windows.Media.Imaging.PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".bmp")) // Cas bmp
            {
                BmpBitmapDecoder img = new System.Windows.Media.Imaging.BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".jpg")) // Cas jpg
            {
                JpegBitmapDecoder img = new System.Windows.Media.Imaging.JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().EndsWith(".tiff")) // Cas tiff
            {
                TiffBitmapDecoder img = new System.Windows.Media.Imaging.TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            if (Path.GetExtension(nomImage).ToLower().Contains(".ico")) // Cas  ico
            {
                IconBitmapDecoder img = new System.Windows.Media.Imaging.IconBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(img.Frames[0]);
            }

            return(null);
        }
Example #24
0
        //metadataCopy.SetQuery("/app13/irb/8bimiptc/iptc/keywords", string.Format("{0}",String.Join(",", Keywords.ToArray()),Hash));            
        public void Save(string path)
        {            
            var klist = new List<string>(Keywords);
            //klist.Add(string.Format("#HASH:{0}", Hash));            

            JpegBitmapDecoder decoder = null;
            using (Stream jpegStreamIn = File.Open(jpegPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            {
                // The orginial decoder method will cause problem
                // if decorder create by delay, it will fast the read speed, but can hardly write
                // if decoder created by Preserve, it will be slow
                try
                {
                    decoder = new JpegBitmapDecoder(jpegStreamIn, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                }
                catch
                {
                    Image x = Image.FromStream(jpegStreamIn);
                    if (x.RawFormat != ImageFormat.Jpeg)
                        throw new FormatException();

                    else throw new Exception();
                }
            }

            var encoder = new JpegBitmapEncoder();
            var Frame = BitmapFrame.Create(decoder.Frames[0]);
            ((BitmapMetadata)Frame.Metadata).Keywords = new System.Collections.ObjectModel.ReadOnlyCollection<string>(klist);
                
            //var xx = BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, metadata, decoder.Frames[0].ColorContexts);            
            encoder.Frames.Add(Frame);
            using (Stream jpegStreamOut = File.Open(path, FileMode.Create))
            {
                encoder.Save(jpegStreamOut);
            }            
        }
        private static WriteableBitmap _Get(string name)
        {
            lock(_lock)
            {
                if (name != _loadedName)
                {
                    ManagedBitmap managedBitmap;

                    using (var stream = new System.IO.FileStream(name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        var frame = decoder.Frames[0];
                        managedBitmap = new ManagedBitmap(frame);
                    }

                    using(var lockedBitmap = managedBitmap.Lock())
                    {
                        int height = lockedBitmap.Height;
                        int width = lockedBitmap.Width;
                        for(int y=0; y<height; y++)
                        {
                            for(int x=0; x<width; x++)
                            {
                                var color = lockedBitmap[x, y];
                                if (color.Red < 10 && color.Green < 10 && color.Blue < 10)
                                    lockedBitmap[x, y] = new Argb();
                            }
                        }
                    }

                    _bitmap = managedBitmap.WriteableBitmap;
                    _loadedName = name;
                }

                return _bitmap;
            }
        }
        internal static BitmapSource ToImageSource(string ext, Stream s)
        {
            ext = ext.ToLower();

            if (ext.EndsWith(".png"))
            {
                var bitmapDecoder = new PngBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                return bitmapDecoder.Frames[0];
            }

            if (ext.EndsWith(".gif"))
            {
                var bitmapDecoder = new GifBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                return bitmapDecoder.Frames[0];
            }

            if (ext.EndsWith(".jpg"))
            {
                var bitmapDecoder = new JpegBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                return bitmapDecoder.Frames[0];
            }

            // http://stackoverflow.com/questions/2835502/rotating-cursor-according-to-rotated-textbox
            // http://stackoverflow.com/questions/46805/custom-cursor-in-wpf
            // http://stackoverflow.com/questions/2284353/is-there-a-good-way-to-convert-between-bitmapsource-and-bitmap
            // http://www.gdgsoft.com/anituner/help/aniformat.htm



            // http://msdn.microsoft.com/en-us/library/ms608877.aspx
            throw new NotSupportedException(ext);
        }
Example #27
0
        private static Stream AddImageComment(Stream jpegStreamIn, string propValue, int propId)
        {
            //string jpegDirectory = Path.GetDirectoryName(imageFlePath);
            //string jpegFileName = Path.GetFileNameWithoutExtension(imageFlePath);


            var decoder = new JpegBitmapDecoder(jpegStreamIn, BitmapCreateOptions.PreservePixelFormat,
                                                BitmapCacheOption.OnLoad);
            var bitmapFrame = decoder.Frames[0];

            var metaData = (BitmapMetadata)bitmapFrame.Metadata.Clone();

            // modify the metadata   
            metaData.SetQuery("/app1/ifd/exif:{uint=" + propId.ToString(CultureInfo.InvariantCulture) + "}", propValue);

            // get an encoder to create a new jpg file with the new metadata.      
            var encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metaData,
                                                  bitmapFrame.ColorContexts));

            // Save the new image 
            var ms = new MemoryStream();

            encoder.Save(ms);
            return ms;
        }
Example #28
0
        void _timer_Tick(object sender, EventArgs e)
        {
            NikonDevice device = _object as NikonDevice;
            Debug.Assert(device != null);

            NikonLiveViewImage liveViewImage = null;

            try
            {
                liveViewImage = device.GetLiveViewImage();
            }
            catch (NikonException ex)
            {
                Log.GetInstance().WriteLine("Failed to get live view image: " + ex.ToString());
            }

            if (liveViewImage == null)
            {
                _timer.Stop();
                return;
            }

            // Note: Decode the live view jpeg image on a seperate thread to keep the UI responsive

            ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
            {
                Debug.Assert(liveViewImage != null);

                JpegBitmapDecoder decoder = new JpegBitmapDecoder(
                    new MemoryStream(liveViewImage.JpegBuffer),
                    BitmapCreateOptions.None,
                    BitmapCacheOption.OnLoad);

                Debug.Assert(decoder.Frames.Count > 0);
                BitmapFrame frame = decoder.Frames[0];

                Dispatcher.CurrentDispatcher.Invoke((Action)(() =>
                {
                    SetLiveViewImage(frame);
                }));
            }));
        }
Example #29
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {Title = "WDP Imaging Sample"};
            var mySv = new ScrollViewer();

            var width = 128;
            var height = width;
            var stride = width/8;
            var pixels = new byte[height*stride];

            // Define the image palette
            var myPalette = BitmapPalettes.WebPalette;

            // Creates a new empty image with the pre-defined palette

            var image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed1,
                myPalette,
                pixels,
                stride);

            var stream = new FileStream("new.wdp", FileMode.Create);
            var encoder = new WmpBitmapEncoder();
            var myTextBlock = new TextBlock {Text = "Codec Author is: " + encoder.CodecInfo.Author};
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);


            // Open a Stream and decode a WDP image
            Stream imageStreamSource = new FileStream("tulipfarm.wdp", FileMode.Open, FileAccess.Read, FileShare.Read);
            var decoder = new WmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];

            // Draw the Image
            var myImage = new Image
            {
                Source = bitmapSource,
                Stretch = Stretch.None,
                Margin = new Thickness(20)
            };


            // Open a Uri and decode a WDP image
            var myUri = new Uri("tulipfarm.wdp", UriKind.RelativeOrAbsolute);
            var decoder3 = new WmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);
            BitmapSource bitmapSource3 = decoder3.Frames[0];

            // Draw the Image
            var myImage2 = new Image
            {
                Source = bitmapSource3,
                Stretch = Stretch.None,
                Margin = new Thickness(20)
            };

            var stream2 = new FileStream("tulipfarm.jpg", FileMode.Open);
            var decoder2 = new JpegBitmapDecoder(stream2, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);
            BitmapSource bitmapSource2 = decoder2.Frames[0];
            var stream3 = new FileStream("new2.wdp", FileMode.Create);
            var encoder2 = new WmpBitmapEncoder();
            encoder2.Frames.Add(BitmapFrame.Create(bitmapSource2));
            encoder2.Save(stream3);

            // Define a StackPanel to host the decoded WDP images
            var myStackPanel = new StackPanel
            {
                Orientation = Orientation.Vertical,
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch
            };

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            mySv.Content = myStackPanel;
            _mainWindow.Content = mySv;
            _mainWindow.Show();
        }
        internal static BitmapDecoder CreateFromUriOrStream(
            Uri baseUri,
            Uri uri,
            Stream stream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            RequestCachePolicy uriCachePolicy,
            bool insertInDecoderCache
            )
        {
            Guid clsId = Guid.Empty;
            bool isOriginalWritable = false;
            SafeMILHandle decoderHandle = null;
            BitmapDecoder cachedDecoder = null;
            Uri finalUri = null;
            Stream uriStream = null;
            UnmanagedMemoryStream unmanagedMemoryStream = null;
            SafeFileHandle safeFilehandle = null;

            // check to ensure that images are allowed in partial trust
            DemandIfImageBlocked();

            if (uri != null)
            {
                finalUri = (baseUri != null) ?
                               System.Windows.Navigation.BaseUriHelper.GetResolvedUri(baseUri, uri) :
                               uri;

                if (insertInDecoderCache)
                {
                    if ((createOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
                    {
                        ImagingCache.RemoveFromDecoderCache(finalUri);
                    }

                    cachedDecoder = CheckCache(
                        finalUri,
                        out clsId
                        );
                }
            }

            // try to retrieve the cached decoder
            if (cachedDecoder != null)
            {
                decoderHandle = cachedDecoder.InternalDecoder;
            }
            else if ((finalUri != null) && (finalUri.IsAbsoluteUri) && (stream == null) &&
                     ((finalUri.Scheme == Uri.UriSchemeHttp) ||
                      (finalUri.Scheme == Uri.UriSchemeHttps)))
            {
                return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy);
            }
            else if ((stream != null) && (!stream.CanSeek))
            {
                return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy);
            }
            else
            {
                // Create an unmanaged decoder
                decoderHandle = BitmapDecoder.SetupDecoderFromUriOrStream(
                    finalUri,
                    stream,
                    cacheOption,
                    out clsId,
                    out isOriginalWritable,
                    out uriStream,
                    out unmanagedMemoryStream,
                    out safeFilehandle
                    );
            }

            BitmapDecoder decoder = null;

            // Find out the decoder type and wrap it appropriately and return that
            if (MILGuidData.GUID_ContainerFormatBmp == clsId)
            {
                decoder = new BmpBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatGif == clsId)
            {
                decoder = new GifBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatIco == clsId)
            {
                decoder = new IconBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatJpeg == clsId)
            {
                decoder = new JpegBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatPng == clsId)
            {
                decoder = new PngBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatTiff == clsId)
            {
                decoder = new TiffBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatWmp == clsId)
            {
                decoder = new WmpBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else
            {
                decoder = new UnknownBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }

            return decoder;
        }
        public void Load()
        {
            try
            {
                // If we have a loading function, use that to get the url we want to load
                if (loading != null)
                    this.url = loading();

                // We explicitly use the WebClient here because we need access to the system-wide browser cache and cookies collection
                var client = new WebClient { CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable) };

                var stream = new MemoryStream();

                using (var istream = client.OpenRead(url))
                {
                    // Read stream into our own byte buffer on the background thread
                    istream.CopyTo(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                }

                var headers = client.ResponseHeaders;

                Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
                    {
                        try
                        {
                            // Create imagesource on the foreground thread
                            string extension = Path.GetExtension(url).ToLower();
                            BitmapDecoder decoder = null;

                            if (extension == ".gif")
                                decoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            else if (extension == ".png")
                                decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            else if (extension == ".jpg" || extension == ".jpeg")
                                decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            else if (extension == ".bmp")
                                decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            else
                            {
                                // We are not sure what extension we are looking at, lets see if there is a content-type available
                                if (headers["Content-Type"] != null)
                                {
                                    var type = headers["Content-Type"];

                                    if (type.IndexOf("gif", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                    else if (type.IndexOf("png", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                    else if (type.IndexOf("jpg", StringComparison.InvariantCultureIgnoreCase) > -1 || type.IndexOf("jpeg", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                    else if (type.IndexOf("bmp", StringComparison.InvariantCultureIgnoreCase) > -1)
                                        decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                }
                            }

                            if (decoder == null)
                            {
                                Logger.Error("Unable to determine type of image to decode. url = {0}", LogSource.BackgroundTask, url);
                                return;
                            }

                            _asyncSource = decoder.Frames[0];
                            _asyncSource.Freeze();

                            if (PropertyChanged != null)
                                PropertyChanged(this, new PropertyChangedEventArgs("AsyncSource"));

                            if (loaded != null)
                                loaded();
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("An error has occured while trying to download an AsyncHttpImage. Url = {0} Exception = {1}", LogSource.BackgroundTask, url, ex);
                        }
                        finally
                        {
                            stream.Dispose();
                        }
                    });

            }
            catch (Exception ex)
            {
                Logger.Error("An error has occured while trying to download an AsyncHttpImage. Url = {0} Exception = {1}", LogSource.BackgroundTask, url, ex);
            }
        }
        /// <summary>
        /// Parse the MJPG stream. This should only return in the case of an 
        /// exception accuring.
        /// </summary>
        /// <exception cref="System.ApplicationException">Thrown when
        /// there is a problem with the handling of the stream. See the
        /// string description for more information.</exception>
        //private void getFrames()
        private void getFrames(object sender, DoWorkEventArgs ev)
        {
            BackgroundWorker bw = sender as BackgroundWorker;

             string strHeader = "--myboundary\r\nContent-Type: image/jpeg\r\nContent-Length: ";

             byte[] headerBuffer = new byte[strHeader.Length];
             string strHeaderBuffer = "";

             int bytesRead = 0;

             // Set the URL to request
             //string strRequest = this.camParams.MjpgParameterString();
             string strRequest = AxisParameters.MjpgParameterString(this.cameraConfig);
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strRequest);

             // set the username and password
             if (this.cameraConfig.User != null && this.cameraConfig.Password != null)
             {
            request.Credentials = new NetworkCredential(
                                      this.cameraConfig.User,
                                      this.cameraConfig.Password
                                      );
             }

             this.doInfo(this, new ScallopInfoEventArgs("Trying Axis camera with URL " + request.RequestUri.ToString()));

             HttpWebResponse streamResponse = (HttpWebResponse)request.GetResponse();
             this.doInfo(this, new ScallopInfoEventArgs("Server responded with : " + streamResponse.StatusDescription));

             using (BufferedStream mjpgStream = new BufferedStream(streamResponse.GetResponseStream()))
             {
            this.streaming = true;
            this.doOpened(this, EventArgs.Empty);
            while (true)
            {
               int contentLen = 0;
               string aLine = "";
               if (bw.CancellationPending == true)
               {
                  mjpgStream.Close();
                  ev.Cancel = true;
                  return;
               }

               /*
               HTTP/1.0 200 OK\r\n
               Content-Type: multipart/x-mixed-replace;boundary=myboundary\r\n
               \r\n
               --myboundary\r\n
               Content-Type: image/jpeg\r\n
               Content-Length: 15656\r\n
               \r\n
               <JPEG image data>\r\n
               --myboundary\r\n
               Content-Type: image/jpeg\r\n
               Content-Length: 14978\r\n
               \r\n
               <JPEG image data>\r\n
               --myboundary\r\n
               Content-Type: image/jpeg\r\n
               Content-Length: 15136\r\n
               \r\n
               <JPEG image data>\r\n
               --myboundary\r\n
                .
                .
                .*/

              bytesRead = 0;

               // Read --myboundary and Content-Type
              while ((bytesRead += mjpgStream.Read(headerBuffer,
                                    bytesRead,
                                    headerBuffer.Length - bytesRead)) < headerBuffer.Length)
               {
                  // No op
               }

               strHeaderBuffer = System.Text.Encoding.UTF8.GetString(headerBuffer);

               if (!strHeaderBuffer.Equals(strHeader))
                  throw new ScallopException("MJPEG header not found");

               aLine = readMjpgLine(mjpgStream);
               contentLen = int.Parse(aLine);

               aLine = readMjpgLine(mjpgStream);
               if (!String.IsNullOrEmpty(aLine)) // empty line
                  throw new ScallopException("Blank line not found");

               // buffer for MJPG frame data
               byte[] frameBuffer = new byte[contentLen];
               bytesRead = 0;

               // read up to contentLen of data to frameBuffer
               while ((bytesRead += mjpgStream.Read(frameBuffer,
                                              bytesRead,
                                              contentLen - bytesRead)) < contentLen)
               {
                  // No op
               }

               aLine = readMjpgLine(mjpgStream);

               switch (this.cameraConfig.FrameFormat)
               {
                  case AxisCameraConfigTypeFrameFormat.Jpeg:
                     this.doData(this, new ScallopSensorDataEventArgs(frameBuffer, "New frame"));
                     break;

                  case AxisCameraConfigTypeFrameFormat.SystemDrawingBitmap:
                     using (MemoryStream pixelStream = new MemoryStream(frameBuffer))
                     {
                        Bitmap streamBitmap = new Bitmap(pixelStream);
                        Bitmap bmp = streamBitmap.Clone() as Bitmap;
                        if (bmp != null)
                           this.doData(this, new ScallopSensorDataEventArgs(bmp, "New frame"));
                        streamBitmap.Dispose();
                     }
                     break;

                  case AxisCameraConfigTypeFrameFormat.SystemWindowsMediaImagingBitmapSource:
                     JpegBitmapDecoder decoder = new JpegBitmapDecoder(new MemoryStream(frameBuffer), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                     if (decoder.Frames[0] != null)
                        this.doData(this, new ScallopSensorDataEventArgs(decoder.Frames[0] as BitmapSource, "New frame"));
                     break;
               }
            }
             }
        }