private static BitmapSource LoadImage(Stream stream, string filename, int dpi)
        {
            filename = filename.ToUpperInvariant();
            BitmapDecoder decoder = null;

            if (filename.EndsWith(".PNG"))
            {
                decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            }
            else if (filename.EndsWith(".JPG") || filename.EndsWith(".JPEG"))
            {
                decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            }

            if (dpi < 0)
            {
                return(decoder != null ? decoder.Frames[0] : null);
            }
            else
            {
                int    stride    = decoder.Frames[0].PixelWidth * 4;
                byte[] pixelData = new byte[stride * decoder.Frames[0].PixelHeight];
                decoder.Frames[0].CopyPixels(pixelData, stride, 0);
                return(BitmapSource.Create(decoder.Frames[0].PixelWidth, decoder.Frames[0].PixelHeight,
                                           dpi, dpi, PixelFormats.Bgra32, decoder.Frames[0].Palette, pixelData, stride));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Decodes the supplied encoded bitmap data into an array of pixels.
        /// For public use only.
        /// </summary>
        public async Task <byte[]> DecodeAsync(byte[] encodedBytes)
        {
#if NETFX_CORE
            using (var ras = new InMemoryRandomAccessStream())
            {
                await ras.AsStream().WriteAsync(encodedBytes, 0, encodedBytes.Length);

                ras.Seek(0);
                var dec = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, ras);

                var pixelDataProvider = await dec.GetPixelDataAsync();

                return(pixelDataProvider.DetachPixelData());
            }
#else
            using (var str = new MemoryStream())
            {
                str.Write(encodedBytes, 0, encodedBytes.Length);
                str.Position = 0;
                var dec   = new JpegBitmapDecoder(str, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                var frame = dec.Frames[0];
                this.PixelFormat = frame.Format;
                var bpp    = frame.Format.BitsPerPixel / 8;
                var stride = bpp * frame.PixelWidth;
                var size   = stride * frame.PixelHeight;
                var output = new byte[size];
                frame.CopyPixels(output, stride, 0);
                return(await Task.FromResult(output));
            }
#endif
        }
Esempio n. 3
0
        /// <summary>
        /// Converts the BLP to a <see cref="BitmapSource"/>.
        /// </summary>
        /// <param name="mipMapLevel">The desired MipMap-Level. If the given level is invalid, the smallest available level is chosen.</param>
        /// <returns>A new <see cref="BitmapSource"/> instance representing the BLP image.</returns>
        public BitmapSource GetBitmapSource(int mipMapLevel = 0)
        {
            byte[] pixelData;

            switch (_formatVersion)
            {
            case FileContent.JPG:
                // TODO: test whether or not using SkiaSharp to decode is faster
                var jpgData = GetJpegFileBytes(mipMapLevel);
                var decoder = new JpegBitmapDecoder(new MemoryStream(jpgData), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                // return decoder.Frames[0];

                var bitmap        = decoder.Frames[0];
                var bytesPerPixel = (bitmap.Format.BitsPerPixel + 7) / 8;
                var stride        = bitmap.PixelWidth * bytesPerPixel;

                pixelData = new byte[stride * bitmap.PixelHeight];
                bitmap.CopyPixels(pixelData, stride, 0);

                InvertChannelValues(pixelData);

                return(BitmapSource.Create(bitmap.PixelWidth, bitmap.PixelHeight, bitmap.DpiX, bitmap.DpiY, bitmap.Format, null, pixelData, stride));

            case FileContent.Direct:
                var bgra = _colorEncoding != 3;

                pixelData = GetPixelsDirect(mipMapLevel, out var width, out var height, bgra);

                return(BitmapSource.Create(width, height, 96d, 96d, bgra ? PixelFormats.Bgra32 : PixelFormats.Rgb24, null, pixelData, width * 4));

            default:
                throw new IndexOutOfRangeException();
            }
        }
Esempio n. 4
0
        private ImageData ReadJpeg(Stream file, SpdMetaData info)
        {
            file.Position = 0x18;
            var header = new byte[0x3C];

            if (header.Length != file.Read(header, 0, header.Length))
            {
                throw new EndOfStreamException();
            }
            unsafe
            {
                fixed(byte *raw = header)
                {
                    uint *dw = (uint *)raw;

                    for (int i = 0; i < 0xF; ++i)
                    {
                        dw[i] += 0xA8961EF1;
                    }
                }
            }
            using (var rest = new StreamRegion(file, file.Position, file.Length - file.Position, true))
                using (var jpeg = new PrefixStream(header, rest))
                {
                    var decoder = new JpegBitmapDecoder(jpeg,
                                                        BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                    var frame = decoder.Frames[0];
                    frame.Freeze();
                    return(new ImageData(frame, info));
                }
        }
Esempio n. 5
0
        private ImageSource GetImage()
        {
            try
            {
                JpegBitmapDecoder decoder;
                Stream            stream;
                WebResponse       resp;
                HttpWebRequest    req;

                req         = (HttpWebRequest)WebRequest.Create(string.Format("http://{0}/telecamera.php", server.Host));
                req.Timeout = 10000;

                // get response

                resp   = req.GetResponse();
                stream = resp.GetResponseStream();

                decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                return(decoder.Frames[0]);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                throw ex;
            }

            return(null);
        }
        public static ImageSource RetriveImage(string imagePath)
        {
            Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(imagePath);

            switch (imagePath.Substring(imagePath.Length - 3))
            {
            case "jpg":
            {
                JpegBitmapDecoder jpegBitmapDecoder = new JpegBitmapDecoder(manifestResourceStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(jpegBitmapDecoder.Frames[0]);
            }

            case "bmp":
            {
                BmpBitmapDecoder bmpBitmapDecoder = new BmpBitmapDecoder(manifestResourceStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(bmpBitmapDecoder.Frames[0]);
            }

            case "png":
            {
                PngBitmapDecoder pngBitmapDecoder = new PngBitmapDecoder(manifestResourceStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(pngBitmapDecoder.Frames[0]);
            }

            case "ico":
            {
                IconBitmapDecoder iconBitmapDecoder = new IconBitmapDecoder(manifestResourceStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                return(iconBitmapDecoder.Frames[0]);
            }

            default:
                return(null);
            }
        }
Esempio n. 7
0
 public Imagen(Stream stm, string ext)
 {
     InitializeComponent();
     this.ext     = ext;
     img          = new Image();
     mem          = (MemoryStream)stm;
     mem.Position = 0;
     if (ext == "JPG" || ext == "jpg")
     {
         JpegBitmapDecoder decoder = new JpegBitmapDecoder(mem, BitmapCreateOptions.None, BitmapCacheOption.Default);
         BitmapSource      bmpsrc  = decoder.Frames[0];
         img.Source  = bmpsrc;
         img.Stretch = Stretch.Fill;
     }
     else if (ext == "PNG" || ext == "png")
     {
         PngBitmapDecoder decoder = new PngBitmapDecoder(mem, BitmapCreateOptions.None, BitmapCacheOption.Default);
         BitmapSource     bmpsrc  = decoder.Frames[0];
         img.Source  = bmpsrc;
         img.Stretch = Stretch.Fill;
     }
     else if (ext == "BMP" || ext == "bmp")
     {
         BmpBitmapDecoder decoder = new BmpBitmapDecoder(mem, BitmapCreateOptions.None, BitmapCacheOption.Default);
         BitmapSource     bmpsrc  = decoder.Frames[0];
         img.Source  = bmpsrc;
         img.Stretch = Stretch.Fill;
     }
     exito = true;
 }
 /// <summary>
 /// Получение EXIF информации фото
 /// </summary>
 private BitmapMetadata GetImgEXIF(string PathImage, out BitmapDecoder decoder, ref FileStream Foto)
 {
     Foto    = File.Open(PathImage, FileMode.Open, FileAccess.Read);                                              // открыли файл по адресу s для чтения
     decoder = JpegBitmapDecoder.Create(Foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default); //"распаковали" снимок и создали объект decoder
     //
     return((BitmapMetadata)decoder.Frames[0].Metadata.Clone());                                                  //считали и сохранили метаданные
 }
Esempio n. 9
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog opd = new OpenFileDialog();

            opd.DefaultExt = ".ico";
            opd.Filter     = "JPG files (*.jpg)|*.jpg|PNG files(*.png)|*.png";
            Nullable <bool> dialogOk = opd.ShowDialog();

            if (dialogOk == true)
            {
                string filePath = opd.FileName;
                txtIcon.Text = filePath;

                FileInfo fi    = new FileInfo(filePath);
                string   extn  = fi.Extension;
                Uri      myUri = new Uri(filePath, UriKind.RelativeOrAbsolute);

                if (extn.Equals(".jpg"))
                {
                    JpegBitmapDecoder decoder2      = new JpegBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    BitmapSource      bitmapSource2 = decoder2.Frames[0];
                    imgIcon.Source = bitmapSource2;
                }
                else if (extn.Equals(".png"))
                {
                    PngBitmapDecoder decoder2      = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    BitmapSource     bitmapSource2 = decoder2.Frames[0];
                    imgIcon.Source = bitmapSource2;
                }
                else
                {
                    imgIcon.Source = null;
                }
            }
        }
Esempio n. 10
0
        ////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////
        // The following functions can be removed after testing


        public bool GetDecodedByteArray(string filename, out int width, out int height, out int depth, out byte[] data)
        {
            bool success = true;

            width  = 0;
            height = 0;
            depth  = 0;
            data   = null;

            if (File.Exists(filename))
            {
                // Open a Stream and decode a JPEG image
                Stream            imageStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
                JpegBitmapDecoder decoder           = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                BitmapSource      bitmapSource      = decoder.Frames[0];

                success = GetBytesFromBitmapSource(bitmapSource, out width, out height, out depth, out data);
            }
            else
            {
                success = false;
            }

            return(success);
        }
Esempio n. 11
0
        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            if (load == true)
            {
                //MessageBox.Show("Load Button works! \n Slider value is " + zoomValue);
                //textBox.Text = " " + zoomValue + " ," + x + " ," + y;

                try
                {
                    byte[]            buff     = m_tmData.LoadTile(zoomValue, x, y);
                    MemoryStream      m_Stream = new MemoryStream(buff);
                    JpegBitmapDecoder jbd      = new JpegBitmapDecoder(m_Stream, BitmapCreateOptions.None, BitmapCacheOption.None);
                    imgTile.Source = jbd.Frames[0];

                    if (buff == null && buff.Length > 0)
                    {
                        Console.WriteLine("Empty title\n");
                    }
                }

                catch (IOException IOe)
                {
                    MessageBox.Show("Failed to load image\n Error : " + IOe);
                }
            }
            else
            {
                MessageBox.Show("Out of range, please check your values");
            }
        }
Esempio n. 12
0
        public void postaviSliku(String putanja, Image ico)
        {
            PngBitmapDecoder  decoderPNG;
            JpegBitmapDecoder decoderJPG;
            BitmapSource      izvor = null;

            if (!putanja.Equals(""))
            {
                Uri    myUri  = new Uri(@putanja);
                int    idx    = putanja.LastIndexOf('.');
                string format = putanja.Substring(idx);


                if ((format.Equals(".png") || format.Equals(".PNG")))
                {
                    decoderPNG = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    izvor      = decoderPNG.Frames[0];
                }

                if (format.Equals(".jpg") || format.Equals(".jpeg") || format.Equals(".JPG") || format.Equals(".JPEG"))
                {
                    decoderJPG = new JpegBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    izvor      = decoderJPG.Frames[0];
                }

                ico.Source = izvor;
            }
        }
Esempio n. 13
0
        static List <string> GetMetaList(string file)
        {
            List <string> metaList = new List <string>();

            BitmapDecoder  decoder = new JpegBitmapDecoder(new FileStream(file, FileMode.Open), BitmapCreateOptions.None, BitmapCacheOption.None);
            BitmapMetadata meta    = (BitmapMetadata)decoder.Frames[0].Metadata;

            metaList.Add("Title: " + meta.Title.Replace("\r", ", "));
            metaList.Add("Author: " + meta.Author[0]);
            string keywords = "";

            foreach (string s in meta.Keywords)
            {
                keywords += s + ", ";
            }
            metaList.Add("Keywords: " + keywords);
            metaList.Add("Copyright: " + meta.Copyright.Replace("\r", ", "));
            metaList.Add("Date: " + meta.DateTaken);

            foreach (string s in metaList)
            {
                Console.WriteLine(s);
            }

            return(metaList);
        }
Esempio n. 14
0
        WriteableBitmap SetBrightness(byte[] buff, int brightness)
        {
            JpegBitmapDecoder decoder = new JpegBitmapDecoder(new MemoryStream(buff), BitmapCreateOptions.None, BitmapCacheOption.Default);
            BitmapSource      bs      = decoder.Frames[0];

            //var bs = new BitmapImage();
            //bs.BeginInit();
            //bs.StreamSource = new MemoryStream(buff);
            //bs.EndInit();

            brightness = brightness * 255 / 100;

            WriteableBitmap wb = new WriteableBitmap(bs);

            uint[] PixelData = new uint[wb.PixelWidth * wb.PixelHeight];
            wb.CopyPixels(PixelData, 4 * wb.PixelWidth, 0);
            for (uint y = 0; y < wb.PixelHeight; y++)
            {
                for (uint x = 0; x < wb.PixelWidth; x++)
                {
                    uint   pixel = PixelData[y * wb.PixelWidth + x];
                    byte[] dd    = BitConverter.GetBytes(pixel);
                    int    B     = (int)dd[0] + brightness;
                    int    G     = (int)dd[1] + brightness;
                    int    R     = (int)dd[2] + brightness;
                    if (B < 0)
                    {
                        B = 0;
                    }
                    if (B > 255)
                    {
                        B = 255;
                    }
                    if (G < 0)
                    {
                        G = 0;
                    }
                    if (G > 255)
                    {
                        G = 255;
                    }
                    if (R < 0)
                    {
                        R = 0;
                    }
                    if (R > 255)
                    {
                        R = 255;
                    }
                    dd[0] = (byte)B;
                    dd[1] = (byte)G;
                    dd[2] = (byte)R;
                    PixelData[y * wb.PixelWidth + x] = BitConverter.ToUInt32(dd, 0);
                }
            }
            wb.WritePixels(new Int32Rect(0, 0, wb.PixelWidth, wb.PixelHeight), PixelData, 4 * wb.PixelWidth, 0);

            return(wb);
        }
Esempio n. 15
0
        private void buttonAdjust_Click(object sender, RoutedEventArgs e)
        {
            int Year   = int.Parse(_textBoxYear.Text);
            int Month  = int.Parse(_textBoxMonth.Text);
            int Day    = int.Parse(_textBoxDay.Text);
            int Hour   = int.Parse(_textBoxHour.Text);
            int Minute = int.Parse(_textBoxMinute.Text);
            int Second = int.Parse(_textBoxSecond.Text);

            foreach (string fileName in selectedFiles)
            {
                FileStream Foto = File.Open(fileName, FileMode.Open, FileAccess.Read);
                // открыли файл по адресу s для чтения

                BitmapDecoder decoder = JpegBitmapDecoder.Create(Foto, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                //"распаковали" снимок и создали объект decoder

                BitmapMetadata TmpImgEXIF = (BitmapMetadata)decoder.Frames[0].Metadata.Clone();
                //считали и сохранили метаданные

                DateTime taken      = TmpImgEXIF.DateTaken == null ? DateTime.Now : Convert.ToDateTime(TmpImgEXIF.DateTaken);
                DateTime DateOfShot = taken.AddYears(Year).AddMonths(Month).AddDays(Day).AddHours(Hour).AddMinutes(Minute).AddSeconds(Second);
                if (DateOfShot <= new DateTime(2011, 12, 31, 23, 59, 59))
                {
                    DateOfShot = DateOfShot.AddHours(-1);
                }
                var news = DateOfShot.ToString("yyyy:MM:dd HH:mm:ss");
                TmpImgEXIF.SetQuery("/app1/ifd/exif/{ushort=36867}", news);
                TmpImgEXIF.SetQuery("/app13/irb/8bimiptc/iptc/date created", news);
                TmpImgEXIF.SetQuery("/xmp/xmp:CreateDate", news);
                TmpImgEXIF.SetQuery("/app1/ifd/exif/{ushort=36868}", news);
                TmpImgEXIF.SetQuery("/xmp/exif:DateTimeOriginal", news);

                JpegBitmapEncoder Encoder = new JpegBitmapEncoder();                                                                                 //создали новый энкодер для Jpeg
                Encoder.Frames.Add(BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, TmpImgEXIF, decoder.Frames[0].ColorContexts)); //добавили в энкодер новый кадр(он там всего один) с указанными параметрами
                string NewFileName = fileName + "+.jpg";                                                                                             //имя исходного файла +GeoTag.jpg
                using (Stream jpegStreamOut = File.Open(NewFileName, FileMode.Create, FileAccess.ReadWrite))                                         //создали новый файл
                {
                    Encoder.Save(jpegStreamOut);                                                                                                     //сохранили новый файл
                }
                Foto.Close();                                                                                                                        //и закрыли исходный файл

                if (File.Exists(fileName + "+.jpg"))
                {
                    if (!File.Exists(fileName + ".backup"))
                    {
                        File.Move(fileName, fileName + ".backup");
                    }
                    else
                    {
                        File.Delete(fileName);
                    }
                    File.Move(fileName + "+.jpg", fileName);
                    File.Delete(fileName + "+.jpg");
                }
                GC.Collect();
            }
            LoadFiles();
        }
        private void UploadImagesClick(object sender, RoutedEventArgs e)
        {
            Spinner.Visibility = Visibility.Visible;

            Logger.Info("MainWindow START - UploadImagesClick Action");

            try
            {
                OpenFileDialog openImageDialog = new OpenFileDialog()
                {
                    Title  = "Select a picture",
                    Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                             "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                             "Portable Network Graphic (*.png)|*.png",
                    Multiselect = true,
                };

                if (openImageDialog.ShowDialog() == true)
                {
                    ImagesList = new List <ImageModel>();

                    foreach (string currenFileName in openImageDialog?.FileNames)
                    {
                        ImageModel currentImage = new ImageModel()
                        {
                            Name       = currenFileName,
                            ImageData  = new BitmapImage(new Uri(currenFileName)),
                            IsSelected = false
                        };

                        using Stream fileStream = new FileStream(currenFileName, FileMode.Open, FileAccess.Read, FileShare.Read);

                        BitmapDecoder  decoder  = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                        var            frame    = decoder?.Frames[0];
                        BitmapMetadata metadata = (BitmapMetadata)frame.Metadata;

                        currentImage.Alt = string.IsNullOrEmpty(metadata?.Comment) ? "La imagen no tiene descripción." : metadata.Comment;

                        ImagesList.Add(currentImage);
                    }

                    ImageListBox.ItemsSource = ImagesList;

                    if (ImagesList.Count > 0)
                    {
                        LabelImageSelection.Visibility = Visibility.Visible;
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc, "MainWindow ERROR - UploadImagesClick Action");
            }
            finally
            {
                Logger.Info("MainWindow FINISH - UploadImagesClick Action");
                Spinner.Visibility = Visibility.Hidden;
            }
        }
Esempio n. 17
0
        public void GetDataFromImage(String path, string oldpath)
        {
            string  folderpath = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName;
            string  filename   = "document.json";
            JObject rss        = JObject.Parse(File.ReadAllText(Path.Combine(folderpath, filename)));
            JObject channel    = (JObject)rss["photolist"];
            JArray  or         = (JArray)channel["photoor"];

            for (int i = 0; i < or.Count; i++)
            {
                if (or[i].ToString() == ("file:\\" + path))
                {
                    return;
                }
            }
            try
            {
                using (var Foto1 = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Inheritable))
                {
                    BitmapDecoder  decoder     = JpegBitmapDecoder.Create(Foto1, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default); //"распаковали" снимок и создали объект decoder
                    BitmapMetadata TmpImgEXIF2 = (BitmapMetadata)decoder.Frames[0].Metadata.Clone();                                                 //считали и сохранили метаданные
                                                                                                                                                     //result = (String)TmpImgEXIF2.GetQuery("/app1/ifd/gps/{ushort=2}");
                    ulong[] a     = ((ulong[])(TmpImgEXIF2.GetQuery("/app1/ifd/gps/{ushort=2}")));
                    ulong[] b     = ((ulong[])(TmpImgEXIF2.GetQuery("/app1/ifd/gps/{ushort=4}")));
                    double  aa    = obr(a[0]) + obr(a[1]) / 60 + obr(a[2]) / 3600;
                    double  bb    = obr(b[0]) + obr(b[1]) / 60 + obr(b[2]) / 3600;
                    string  path2 = Path.Combine(folderpath, "photosm");
                    Image   im    = Image.FromStream(Foto1);
                    im    = ResizeImg(im, 60, 60 * im.Height / im.Width);
                    path2 = Path.Combine(path2, GetRightPartOfPath(path, Path.GetFileName(oldpath)));
                    Directory.CreateDirectory(path2);
                    //     im.Save(path2 + "\\" + Path.GetFileName(path) + "small.jpg");
                    Bitmap bitmap = new Bitmap(im);
                    using (Graphics g = Graphics.FromImage(bitmap))
                    {
                        g.DrawRectangle(new Pen(Brushes.Yellow, 3), new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
                    }
                    string fname = Path.GetFileName(path);
                    fname = fname.Substring(0, fname.Length - 4) + "_small.jpg";
                    bitmap.Save(path2 + "\\" + fname);
                    JArray sm   = (JArray)channel["photosm"];
                    JArray tag1 = (JArray)channel["geotag1"];
                    JArray tag2 = (JArray)channel["geotag2"];
                    JArray h    = (JArray)channel["height"];
                    JArray w    = (JArray)channel["width"];
                    or.Add("file:\\" + path);
                    sm.Add("file:\\" + path2 + "\\" + fname);
                    tag1.Add(aa);
                    tag2.Add(bb);
                    h.Add(650 * im.Height / im.Width);
                    w.Add(650);
                    File.WriteAllText((Path.Combine(folderpath, filename)), rss.ToString());
                }
            }

            catch (Exception ex)
            {
            }
        }
Esempio n. 18
0
 public static BitmapSource ToBitmapSource(byte[] bytes)
 {
     using (var stream = new System.IO.MemoryStream(bytes))
     {
         var decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
         return(decoder.Frames.First());
     }
 }
Esempio n. 19
0
        private BitmapSource LoadImageFromStream(Stream stream)
        {
            var          decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
            BitmapSource img     = decoder.Frames[0];

            img.Freeze();
            return(ResizeImage(img, 130));
        }
        // 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);
        }
Esempio n. 21
0
        private void OnImageReady(byte[] image, int count)
        {
            JpegBitmapDecoder decoder      = new JpegBitmapDecoder(new MemoryStream(image), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource      bitmapSource = decoder.Frames[0];

            CameraImage.Source = bitmapSource;
            CameraCount.Text   = count.ToString();
        }
Esempio n. 22
0
        public static BitmapSource GetBitmapSourceFromStream(Stream stream)
        {
            JpegBitmapDecoder decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
            BitmapSource      source  = decoder.Frames[0];

            source.Freeze();
            return(source);
        }
Esempio n. 23
0
        private void open_Clik(object sender, RoutedEventArgs e)
        {
            FileStream     op       = File.Open("z:/1.jpg", FileMode.Open);
            BitmapDecoder  decoder  = JpegBitmapDecoder.Create(op, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
            BitmapMetadata metadata = (BitmapMetadata)decoder.Frames[0].Metadata;

            name.Content = metadata.Title;
        }
Esempio n. 24
0
        byte[] UnpackJpeg()
        {
            Flipped = false;
            Input.ReadInt32();
            var  jpeg_size    = Input.ReadInt32();
            long next_section = InputStream.Position + jpeg_size;
            var  decoder      = new JpegBitmapDecoder(InputStream,
                                                      BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            var frame = decoder.Frames[0];

            if (frame.Format.BitsPerPixel < 24)
            {
                throw new NotSupportedException("Not supported HG-3 JPEG color depth");
            }
            int src_pixel_size = frame.Format.BitsPerPixel / 8;
            int stride         = (int)m_info.Width * src_pixel_size;
            var pixels         = new byte[stride * (int)m_info.Height];

            frame.CopyPixels(pixels, stride, 0);
            var  output = new byte[m_info.Width * m_info.Height * 4];
            uint total  = m_info.Width * m_info.Height;
            int  src    = 0;
            int  dst    = 0;

            for (uint i = 0; i < total; ++i)
            {
                output[dst++] = pixels[src];
                output[dst++] = pixels[src + 1];
                output[dst++] = pixels[src + 2];
                output[dst++] = 0xFF;
                src          += src_pixel_size;
            }

            InputStream.Position = next_section;
            var section_header = Input.ReadChars(8);

            if (!section_header.SequenceEqual("img_al\0\0"))
            {
                return(output);
            }
            InputStream.Seek(8, SeekOrigin.Current);
            int alpha_size = Input.ReadInt32();

            using (var alpha_in = new StreamRegion(InputStream, InputStream.Position + 4, alpha_size, true))
                using (var alpha = new ZLibStream(alpha_in, CompressionMode.Decompress))
                {
                    for (int i = 3; i < output.Length; i += 4)
                    {
                        int b = alpha.ReadByte();
                        if (-1 == b)
                        {
                            throw new EndOfStreamException();
                        }
                        output[i] = (byte)b;
                    }
                    return(output);
                }
        }
Esempio n. 25
0
        /// <summary>
        /// Creates a WinForms <see cref="Bitmap"/> from the <see cref="Image"/>.
        /// </summary>
        /// <param name="image">The <see cref="Image"/> to convert into a <see cref="Bitmap"/>.</param>
        /// <returns>A <see cref="Bitmap"/> that references the data in <see cref="Image"/>.</returns>
        public static System.Drawing.Image CreateBitmap(this Image image)
        {
            if (image is null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            System.Drawing.Imaging.PixelFormat pixelFormat;

            // Take a new reference on the image to ensure that the object
            // cannot be disposed by another thread while we have a copy of its Buffer
            using (Image reference = image.DuplicateReference())
            {
                unsafe
                {
                    switch (reference.Format)
                    {
                    case ImageFormat.ColorBgra32:
                        pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
                        break;

                    case ImageFormat.Depth16:
                    case ImageFormat.IR16:
                        pixelFormat = System.Drawing.Imaging.PixelFormat.Format16bppGrayScale;
                        break;

                    case ImageFormat.ColorMjpg:
                        Byte[] buffer = new byte[image.SizeBytes];
                        System.Runtime.InteropServices.Marshal.Copy(image.Buffer, buffer, 0, image.SizeBytes);
                        JpegBitmapDecoder decoder    = new JpegBitmapDecoder(new MemoryStream(buffer), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                        BitmapFrame       frame      = decoder.Frames[0];
                        Bitmap            lbmpBitmap = new Bitmap(frame.PixelWidth, frame.PixelHeight);
                        Rectangle         lrRect     = new Rectangle(0, 0, lbmpBitmap.Width, lbmpBitmap.Height);
                        BitmapData        lbdData    = lbmpBitmap.LockBits(lrRect, ImageLockMode.WriteOnly, (frame.Format.BitsPerPixel == 24 ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb));
                        frame.CopyPixels(System.Windows.Int32Rect.Empty, lbdData.Scan0, lbdData.Height * lbdData.Stride, lbdData.Stride);
                        lbmpBitmap.UnlockBits(lbdData);
                        return(lbmpBitmap);

                    // pixelFormat = System.Drawing.Imaging.PixelFormat.;
                    // MjpegProcessor.MjpegDecoder()
                    //break;
                    default:
                        throw new Exception($"Pixel format {reference.Format} cannot be converted to a BitmapSource");
                    }

                    using (image)
                    {
                        return(new Bitmap(
                                   image.WidthPixels,
                                   image.HeightPixels,
                                   image.StrideBytes,
                                   pixelFormat,
                                   image.Buffer));
                    }
                }
            }
        }
Esempio n. 26
0
        private static BitmapSource BitmapSourceFromStream(Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            BitmapDecoder decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

            BitmapSource bmp = decoder.Frames[0];

            return(bmp);
        }
Esempio n. 27
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));
        }
Esempio n. 28
0
        private BitmapSource getBitmap(byte[] jpeg)
        {
            JpegBitmapDecoder decoder = new JpegBitmapDecoder(
                new MemoryStream(jpeg),
                BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);

            return(decoder.Frames[0]);
        }
        public Novi_tip_prozor()
        {
            InitializeComponent();
            Uri myUri = new Uri("question-mark.jpg", UriKind.RelativeOrAbsolute);
            JpegBitmapDecoder decoder2      = new JpegBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource      bitmapSource2 = decoder2.Frames[0];

            image.Source = bitmapSource2;
        }
        private void Wallpaper_DownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            MemoryStream      stream     = new MemoryStream(e.Result);
            JpegBitmapDecoder jpgDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            Wallpaper = jpgDecoder.Frames[0];

            IsLoading = false;
        }