Ejemplo n.º 1
0
        /// ------------------------------------------------------------------------------------
        public ImageViewerViewModel(string pathToImage, int[] clickZoomPercentages)
        {
            try
            {
                Image = null;
                const double max = 2048;

                // Do this instead of using the Image.Load method because Load keeps a lock on the file.

                /***************************************************************************************
                * SP-910: Out of memory error with larger images.
                *
                * The WinForms Bitmap apparently requires a contiguous block of free video memory to
                * load an image. Larger images (number of pixels) consistently cause out of memory
                * errors.  The WPF BitmapDecoder does not appear to have this limitation.
                *
                * This implementation uses the WPF BitmapDecoder to load the image and determine its
                * size.  If either of the dimensions is greater than 2048, the image is shrunk before
                * being converted to a WinForms Bitmap so it can be displayed.
                *
                ***************************************************************************************/

                using (var fs = new FileStream(pathToImage, FileMode.Open, FileAccess.Read))
                {
                    var          bd  = BitmapDecoder.Create(fs, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                    BitmapSource src = bd.Frames[0];

                    // check the size
                    if ((src.PixelHeight > max) || (src.PixelWidth > max))
                    {
                        // resize
                        double scale;
                        if (src.PixelHeight > src.PixelWidth)
                        {
                            scale = max / src.PixelHeight;
                        }
                        else
                        {
                            scale = max / src.PixelWidth;
                        }

                        TransformedBitmap tbm = new TransformedBitmap(src, new ScaleTransform(scale, scale));
                        src = BitmapFrame.Create(tbm);
                    }

                    // convert from WPF bitmap to WinForms bitmap
                    var be = new BmpBitmapEncoder();
                    be.Frames.Add(src as BitmapFrame);

                    using (var ms = new MemoryStream())
                    {
                        be.Save(ms);
                        Image = new Bitmap(ms);
                    }

                    fs.Close();
                }
            }
            catch (OutOfMemoryException oomex)
            {
                var msg = LocalizationManager.GetString("CommonToMultipleViews.ImageViewer.OpeningPictureFileTooLargeMsg",
                                                        "Could not open that picture. The image size is too large for SayMore to open.");
                SIL.Reporting.ErrorReport.NotifyUserOfProblem(oomex, msg);
            }
            catch (Exception e)
            {
                /***************************************************************************************
                * While debugging, showing the Palaso error report dialog causes an error in the
                * EnhancedPanel user control, which causes it to show the red X box.  No exception is
                * being thrown.  The only way to get rid of the red X box is to restart the entire
                * program.
                ***************************************************************************************/
                var msg = LocalizationManager.GetString("CommonToMultipleViews.ImageViewer.OpeningPictureFileErrorMsg",
                                                        "Could not open that picture.");
                SIL.Reporting.ErrorReport.NotifyUserOfProblem(e, msg);
            }
            finally
            {
                if (Image == null)
                {
                    Image = new Bitmap(100, 100);
                }
            }

            ClickZoomPercentages = clickZoomPercentages;
        }
Ejemplo n.º 2
0
        public WriteableBitmap LoadImage(FileItem fileItem, bool fullres, bool showfocuspoints)
        {
            if (fileItem == null)
            {
                return(null);
            }
            if (!File.Exists(fileItem.LargeThumb) && !fullres)
            {
                return(null);
            }
            if (File.Exists(fileItem.InfoFile))
            {
                fileItem.LoadInfo();
            }
            if (fileItem.FileInfo == null)
            {
                fileItem.FileInfo = new FileInfo();
            }

            try
            {
                BitmapDecoder bmpDec = null;
                if (fullres && fileItem.IsRaw)
                {
                    try
                    {
                        string dcraw_exe = Path.Combine(Settings.ApplicationFolder, "dcraw.exe");
                        if (File.Exists(dcraw_exe))
                        {
                            string thumb = Path.Combine(Settings.ApplicationTempFolder, Path.GetFileNameWithoutExtension(fileItem.FileName) + ".thumb.jpg");
                            PhotoUtils.RunAndWait(dcraw_exe,
                                                  string.Format(" -e -O \"{0}\" \"{1}\"", thumb, fileItem.FileName));
                            if (File.Exists(thumb))
                            {
                                bmpDec = BitmapDecoder.Create(new Uri(thumb), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                File.Delete(thumb);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Log.Error("Error get dcraw thumb", exception);
                    }
                }

                PhotoUtils.WaitForFile(fullres ? fileItem.FileName : fileItem.LargeThumb);
                if (bmpDec == null)
                {
                    bmpDec = BitmapDecoder.Create(new Uri(fullres ? fileItem.FileName : fileItem.LargeThumb),
                                                  BitmapCreateOptions.None,
                                                  BitmapCacheOption.OnLoad);
                }
                // if no future processing required
                if (!showfocuspoints && ServiceProvider.Settings.RotateIndex == 0 && !ServiceProvider.Settings.FlipPreview)
                {
                    fileItem.Loading = false;
                    var b = new WriteableBitmap(bmpDec.Frames[0]);
                    b.Freeze();
                    return(b);
                }

                var bitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames[0]);

                if (showfocuspoints && !fileItem.Transformed)
                {
                    DrawFocusPoints(fileItem, bitmap);
                }


                if (ServiceProvider.Settings.RotateIndex != 0)
                {
                    switch (ServiceProvider.Settings.RotateIndex)
                    {
                    case 1:
                        bitmap = bitmap.Rotate(90);
                        break;

                    case 2:
                        bitmap = bitmap.Rotate(180);
                        break;

                    case 3:
                        bitmap = bitmap.Rotate(270);
                        break;
                    }
                }

                if (ServiceProvider.Settings.FlipPreview)
                {
                    bitmap = bitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                }

                bitmap.Freeze();
                return(bitmap);
            }
            catch (Exception exception)
            {
                Log.Error("Error loading image", exception);
                if (exception.GetType() == typeof(OutOfMemoryException) && fullres)
                {
                    return(LoadImage(fileItem, false));
                }
            }
            return(null);
        }
Ejemplo n.º 3
0
        public void Execute()
        {
            string path;

            using (var inputStream = _fileSystem.File.OpenRead(_file))
            {
                var decoder = BitmapDecoder.Create(
                    inputStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

                var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat);
                if (!encoder.CanEncode())
                {
                    encoder = BitmapEncoder.Create(_settings.FallbackEncoder);
                }

                ConfigureEncoder(encoder);

                if (decoder.Metadata != null)
                {
                    try
                    {
                        encoder.Metadata = decoder.Metadata;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                if (decoder.Palette != null)
                {
                    encoder.Palette = decoder.Palette;
                }

                foreach (var originalFrame in decoder.Frames)
                {
                    BitmapMetadata metadata = (BitmapMetadata)originalFrame.Metadata;
                    if (metadata != null)
                    {
                        try
                        {
#if DEBUG
                            Debug.WriteLine($"### Processing metadata of file {_file}");
                            metadata.PrintsAllMetadataToDebugOutput();
#endif

                            // read all metadata and build up metadata object from the scratch. Discard invalid (unreadable/unwritable) metadata.
                            var newMetadata    = new BitmapMetadata(metadata.Format);
                            var listOfMetadata = metadata.GetListOfMetadata();
                            foreach (var(metadataPath, value) in listOfMetadata)
                            {
                                if (value is BitmapMetadata bitmapMetadata)
                                {
                                    var innerMetadata = new BitmapMetadata(bitmapMetadata.Format);
                                    newMetadata.SetQuerySafe(metadataPath, innerMetadata);
                                }
                                else
                                {
                                    newMetadata.SetQuerySafe(metadataPath, value);
                                }
                            }

                            if (newMetadata.IsMetadataObjectValid())
                            {
                                metadata = newMetadata;
                            }
                            else
                            {
                                // Seems like we build an invalid metadata object. ImageResizer will fail when trying to write the image to disk. We discard all metadata to be able to save the image.
                                metadata = null;
                            }
                        }
                        catch (ArgumentException ex)
                        {
                            metadata = null;

                            Debug.WriteLine(ex);
                        }
                    }

                    if (_settings.RemoveMetadata && metadata != null)
                    {
                        // strip any metadata that doesn't affect rendering
                        var newMetadata = new BitmapMetadata(metadata.Format);

                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Photo.Orientation");
                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Image.ColorSpace");

                        metadata = newMetadata;
                    }

                    encoder.Frames.Add(
                        BitmapFrame.Create(
                            Transform(originalFrame),
                            thumbnail: null, /* should be null, see #15413 */
                            metadata,
                            colorContexts: null /* should be null, see #14866 */));
                }

                path = GetDestinationPath(encoder);
                _fileSystem.Directory.CreateDirectory(_fileSystem.Path.GetDirectoryName(path));
                using (var outputStream = _fileSystem.File.Open(path, FileMode.CreateNew, FileAccess.Write))
                {
                    encoder.Save(outputStream);
                }
            }

            if (_settings.KeepDateModified)
            {
                _fileSystem.File.SetLastWriteTimeUtc(path, _fileSystem.File.GetLastWriteTimeUtc(_file));
            }

            if (_settings.Replace)
            {
                var backup = GetBackupPath();
                _fileSystem.File.Replace(path, _file, backup, ignoreMetadataErrors: true);
                FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
            }
        }
Ejemplo n.º 4
0
        public void WriteMetadataAndCheckForImageLoss()
        {
            // File that will be changed
            JpgPhoto beforePhoto = new JpgPhoto(TestPhotos.UnitTestTemp6);
            JpgPhoto afterPhoto  = new JpgPhoto(TestPhotos.UnitTestTemp7);

            // Get a copy of a file
            File.Copy(this.jpgPhotoOne.FileFullName, beforePhoto.FileFullName, true);
            File.Copy(this.jpgPhotoOne.FileFullName, afterPhoto.FileFullName, true);

            // Change some metadata
            afterPhoto.Metadata.Description = "Test Description" + DateTime.Now.ToString();
            afterPhoto.Metadata.Comment     = "Test Comment" + DateTime.Now.ToString();
            afterPhoto.Metadata.Copyright   = "Test Copyright" + DateTime.Now.ToString();
            afterPhoto.Metadata.Subject     = "Subject Copyright" + DateTime.Now.ToString();

            // Save as temp file
            afterPhoto.WriteMetadata();

            // Open Original File
            using (Stream beforeStream = File.Open(beforePhoto.FileFullName, FileMode.Open, FileAccess.Read))
            {
                // Open the Saved File
                using (Stream afterStream = File.Open(afterPhoto.FileFullName, FileMode.Open, FileAccess.Read))
                {
                    // Compare every pixel to ensure it has changed
                    BitmapSource beforeBitmap = BitmapDecoder.Create(beforeStream, BitmapCreateOptions.None, BitmapCacheOption.OnDemand).Frames[0];
                    BitmapSource afterBitmap  = BitmapDecoder.Create(afterStream, BitmapCreateOptions.None, BitmapCacheOption.OnDemand).Frames[0];

                    PixelFormat pf = PixelFormats.Bgra32;

                    FormatConvertedBitmap fcbOne = new FormatConvertedBitmap(beforeBitmap, pf, null, 0);
                    FormatConvertedBitmap fcbTwo = new FormatConvertedBitmap(afterBitmap, pf, null, 0);

                    GC.AddMemoryPressure(((fcbOne.Format.BitsPerPixel * (fcbOne.PixelWidth + 7)) / 8) * fcbOne.PixelHeight);
                    GC.AddMemoryPressure(((fcbTwo.Format.BitsPerPixel * (fcbTwo.PixelWidth + 7)) / 8) * fcbTwo.PixelHeight);

                    int width  = fcbOne.PixelWidth;
                    int height = fcbOne.PixelHeight;

                    int bpp    = pf.BitsPerPixel;
                    int stride = (bpp * (width + 7)) / 8;

                    byte[] scanline0 = new byte[stride];
                    byte[] scanline1 = new byte[stride];

                    Int32Rect lineRect = new Int32Rect(0, 0, width, 1);

                    // Loop through each row
                    for (int y = 0; y < height; y++)
                    {
                        lineRect.Y = y;

                        fcbOne.CopyPixels(lineRect, scanline0, stride, 0);
                        fcbTwo.CopyPixels(lineRect, scanline1, stride, 0);

                        // Loop through each column
                        for (int b = 0; b < stride; b++)
                        {
                            if (Math.Abs(scanline0[b] - scanline1[b]) > 0)
                            {
                                Assert.Fail("Saved file was not solved losslessly");
                            }
                        }
                    }
                }
            }

            // Tidy UP
            File.Delete(beforePhoto.FileFullName);
            File.Delete(afterPhoto.FileFullName);
        }
Ejemplo n.º 5
0
        private void Dodaj_Tip(object sender, RoutedEventArgs e)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(idTipa.Text, "[^0-9]") || Tipovi.Any(x => x.Id.ToString() == idTipa.Text) || idTipa.Text.Equals("") || imeTipa.Text.Equals("") || Ikonica.Source == null)
            {
                lab1.Foreground = new SolidColorBrush(Colors.White);
                lab1.Content    = "Id: ";
                lab2.Foreground = new SolidColorBrush(Colors.White);
                lab2.Content    = "Ime: ";
                lab4.Foreground = new SolidColorBrush(Colors.White);
                lab4.Content    = "Ikonica: ";

                if (idTipa.Text.Equals(""))
                {
                    lab1.Foreground = new SolidColorBrush(Colors.Red);
                    lab1.Content    = ">>> Id: ";
                }

                if (Ikonica.Source == null)
                {
                    lab4.Foreground = new SolidColorBrush(Colors.Red);
                    lab4.Content    = ">>> Ikonica: ";
                }

                if (imeTipa.Text.Equals(""))
                {
                    lab2.Foreground = new SolidColorBrush(Colors.Red);
                    lab2.Content    = ">>> Ime: ";
                }

                if (Tipovi.Any(x => x.Id.ToString() == idTipa.Text))
                {
                    lab1.Foreground = new SolidColorBrush(Colors.Red);
                    lab1.Content    = ">>> Id već postoji: ";
                }

                if (System.Text.RegularExpressions.Regex.IsMatch(idTipa.Text, "[^0-9]"))
                {
                    lab1.Foreground = new SolidColorBrush(Colors.Red);
                    lab1.Content    = ">>> Id: ";
                }

                return;
            }

            lab1.Foreground = new SolidColorBrush(Colors.White);
            lab1.Content    = "Id: ";
            lab2.Foreground = new SolidColorBrush(Colors.White);
            lab2.Content    = "Ime: ";
            lab4.Foreground = new SolidColorBrush(Colors.White);
            lab4.Content    = "Ikonica: ";

            Uri           myUri        = new Uri(Ikonica.Source.ToString(), UriKind.RelativeOrAbsolute);
            BitmapDecoder decoder      = BitmapDecoder.Create(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource  bitmapSource = decoder.Frames[0];


            Tipovi.Add(new Model.Tip {
                Id = idTipa.Text, Ime = imeTipa.Text, Opis = opisTipa.Text, Image = bitmapSource
            });
            TipZivotinje.ItemsSource = Tipovi;
            idTipa.Text         = "";
            imeTipa.Text        = "";
            opisTipa.Text       = "";
            PanelTip.Visibility = Visibility.Hidden;
        }
Ejemplo n.º 6
0
 private static BitmapDecoder NewDecoder(Stream downscaledImage)
 {
     return(BitmapDecoder.Create(downscaledImage, BitmapCreateOptions.None, BitmapCacheOption.None));
 }
Ejemplo n.º 7
0
        public string Execute(FileItem fileItem, string infile, string dest, ValuePairEnumerator configData)
        {
            var  conf       = new ResizeTransformViewModel(configData);
            bool deleteFile = false;
            var  filename   = infile;

            if (fileItem.IsRaw)
            {
                string s = Path.Combine(Path.GetDirectoryName(fileItem.FileName),
                                        Path.GetFileNameWithoutExtension(fileItem.FileName) + ".jpg");
                if (File.Exists(s))
                {
                    filename = s;
                }
                else
                {
                    string dcraw_exe = Path.Combine(Settings.ApplicationFolder, "dcraw.exe");
                    if (File.Exists(dcraw_exe))
                    {
                        PhotoUtils.RunAndWait(dcraw_exe, string.Format(" -e {0}", fileItem.FileName));
                        string thumb = Path.Combine(Path.GetDirectoryName(fileItem.FileName),
                                                    Path.GetFileNameWithoutExtension(fileItem.FileName) + ".thumb.jpg");
                        if (File.Exists(thumb))
                        {
                            deleteFile = true;
                            filename   = thumb;
                        }
                    }
                }
                dest = Path.Combine(Path.GetDirectoryName(dest), Path.GetFileNameWithoutExtension(dest) + ".jpg");
            }
            using (MemoryStream fileStream = new MemoryStream(File.ReadAllBytes(filename)))
            {
                BitmapDecoder bmpDec = BitmapDecoder.Create(fileStream,
                                                            BitmapCreateOptions.PreservePixelFormat,
                                                            BitmapCacheOption.OnLoad);
                WriteableBitmap writeableBitmap;
                if (conf.KeepAspect)
                {
                    double dw = (double)conf.Width / bmpDec.Frames[0].PixelWidth;
                    writeableBitmap =
                        BitmapFactory.ConvertToPbgra32Format(BitmapLoader.GetBitmapFrame(bmpDec.Frames[0],
                                                                                         (int)(bmpDec.Frames[0].PixelWidth * dw),
                                                                                         (int)(bmpDec.Frames[0].PixelHeight * dw),
                                                                                         BitmapScalingMode.Linear));
                }
                else
                {
                    writeableBitmap =
                        BitmapFactory.ConvertToPbgra32Format(BitmapLoader.GetBitmapFrame(bmpDec.Frames[0], conf.Width, conf.Height, BitmapScalingMode.Linear));
                }

                BitmapLoader.Save2Jpg(writeableBitmap, dest);

                // remove temporally file created by dcraw
                if (deleteFile)
                {
                    File.Delete(filename);
                }
            }
            return(dest);
        }
Ejemplo n.º 8
0
        private static BitmapFrame ReadBitmapFrame(MemoryStream photoStream)
        {
            var photoDecoder = BitmapDecoder.Create(photoStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            return(photoDecoder.Frames[0]);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 해당 폴더의 JPEG 이미지 파일을 PictureListBox 목록에 추가
        /// </summary>
        /// <remarks>
        ///   + BitmapFrame 에 연결된 썸네일이미지가 있으면 해당 이미지 사용
        /// </remarks>
        /// <param name="folderPath"></param>
        private void AddPhotosListBox(string folderPath)
        {
            try
            {
                Photo          photo;
                ListBoxItem    item;
                TransformGroup tfg;
                Image          img, imgTooltip;
                Uri            uri;
                BitmapDecoder  decoder;
                TextBlock      tbkFileName, tbkFileDate;
                StackPanel     pnlTooltip;
                BitmapImage    bmp;

                foreach (string fileName in Directory.GetFiles(folderPath, "*.jpg"))
                {
                    photo = new Photo(fileName);
                    PhotoList.Add(photo);

                    item                   = new ListBoxItem();
                    item.Padding           = new Thickness(3, 8, 3, 8);
                    item.MouseDoubleClick += delegate { ShowPhoto(true); };
                    tfg = new TransformGroup();
                    tfg.Children.Add(m_3XScale);
                    tfg.Children.Add(new RotateTransform());// 회전각도 초기화
                    item.LayoutTransform = tfg;
                    item.Tag             = fileName;

                    img        = new Image();
                    img.Height = 35;

                    uri        = new Uri(fileName);
                    pnlTooltip = new StackPanel();

                    //decoder = BitmapDecoder.Create(uri, BitmapCreateOptions.DelayCreation, BitmapCacheOption.Default);
                    // 프로그램에서 이미지의 경로를 직접 사용하는 경우 이름변경이 안되므로, Cache옵션을 설정해 해결
                    decoder = BitmapDecoder.Create(uri, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);

                    if (decoder.Frames[0] != null && decoder.Frames[0].Thumbnail != null)
                    {
                        // BitmapFrame 에 연결된 축소판 이미지가 있는 경우,
                        img.Source = decoder.Frames[0].Thumbnail;

                        imgTooltip        = new Image();
                        imgTooltip.Source = decoder.Frames[0].Thumbnail;
                        pnlTooltip.Children.Add(imgTooltip);
                    }
                    else
                    {
                        // BitmapFrame 에 연결된 축소판 이미지가 없는 경우,
                        // 프로그램에서 이미지의 경로를 직접 사용하는 경우 이름변경이 안되므로, Cache옵션을 설정해 해결
                        bmp = GetBitmapImage(uri);

                        img.Source = bmp;// new BitmapImage(uri);
                        imgTooltip = null;
                    }

                    tbkFileName      = new TextBlock();
                    tbkFileName.Text = System.IO.Path.GetFileName(fileName);
                    tbkFileDate      = new TextBlock();
                    tbkFileDate.Text = photo.RegDate.ToString();

                    pnlTooltip.Children.Add(tbkFileName);
                    pnlTooltip.Children.Add(tbkFileDate);

                    item.ToolTip = pnlTooltip;
                    item.Content = img;

                    lbxPicture.Items.Add(item);
                }
            }
            catch (UnauthorizedAccessException) { }
            catch (IOException) { }
        }
Ejemplo n.º 10
0
 public static ImageProperties GetImageProperties(string imagePath)
 {
     return(GetImageProperties(BitmapDecoder.Create(new Uri(imagePath), BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default)));
 }
Ejemplo n.º 11
0
 public static ImageProperties GetImageProperties(Stream imageStream)
 {
     return(GetImageProperties(BitmapDecoder.Create(imageStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default)));
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Look for the previous valid image
        /// </summary>
        /// <param name="setImage">whether to set the previous valid image as the background</param>
        public async void GotoPreviousImage(bool setImage)
        {
            // re-entrant protection
            if (this.BeginTransaction())
            {
                return;
            }

            // if the image also needs to be set then show balloon tooltip as it can be a lengthy process
            if (setImage)
            {
                this.trayIcon.SetLoadingText();
            }

            bool           listUpdated = false;
            WallpaperEntry newEntry    = null;

            c_filelist.SelectedIndex = -1;

            // we will keep looping till we find a valid image
            while (true)
            {
                await Task.Delay(1);

                // get the index of the previous image
                if (this.imageStack.Count == 0)
                {
                    newEntry = null;
                }
                else
                {
                    this.imageStack.Pop();
                    if (this.imageStack.Count > 0)
                    {
                        newEntry = this.imageStack.First();
                    }
                }

                if (this.imageStack.Count > 1)
                {
                    c_imageprevious.IsEnabled = true;
                }
                else
                {
                    c_imageprevious.IsEnabled = false;
                }

                // if no previous entry, break the loop
                if (newEntry == null)
                {
                    break;
                }

                // try to load the thumbnail
                try
                {
                    string        filePath  = this.GetLocalCopyOfImage(newEntry, true);
                    BitmapDecoder uriBitmap = BitmapDecoder.Create(new Uri(filePath), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                }
                catch (Exception)
                {
                    // in case of an exception remove the entry from the list
                    this.activeList.RemoveFile(newEntry.FilePath, true);
                    listUpdated = true;

                    // try a different image
                    continue;
                }

                if (setImage)
                {
                    // try to set the background
                    try
                    {
                        this.SetBackgroundImage(newEntry);
                    }
                    catch (Exception)
                    {
                        // in case of an exception remove the entry from the list
                        this.activeList.RemoveFile(newEntry.FilePath, true);
                        listUpdated = true;

                        // try a different image
                        continue;
                    }
                }

                // if the current selection succeeded to load, end the loop
                break;
            }

            if (listUpdated)
            {
                if (this.activeList.Count > 0)
                {
                    c_imagenext.IsEnabled = true;
                }
                else
                {
                    c_imagenext.IsEnabled = false;
                }

                try
                {
                    this.activeList.SaveToFile();
                }
                catch (Exception)
                {
                    // nothing to do here
                }
            }

            this.EndTransaction();

            // set the appropriate image as current
            if (newEntry == null)
            {
                c_filelist.SelectedIndex = -1;
            }
            else
            {
                c_filelist.SelectedItem = newEntry;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Look for the next valid image
        /// </summary>
        /// <param name="setImage">whether to set the next valid image as the background</param>
        /// <param name="startIndex">the index to start the scan from, if this is null use the current index</param>
        public async void GotoNextImage(bool setImage, int?startIndex = null)
        {
            // re-entrant protection
            if (this.BeginTransaction())
            {
                return;
            }

            // if the image also needs to be set then show balloon tooltip as it can be a lengthy process
            if (setImage)
            {
                this.trayIcon.SetLoadingText();
            }

            bool listUpdated  = false;
            int  currentIndex = (startIndex.HasValue) ? startIndex.Value : c_filelist.SelectedIndex;

            c_filelist.SelectedIndex = -1;
            int newIndex = -1;

            // we will keep looping till we find a valid image
            while (true)
            {
                await Task.Delay(1);

                // get the index of the next image
                if (this.activeList.Count == 0)
                {
                    newIndex = -1;
                    break;
                }
                else if (Settings.Instance.ChangeRandomly)
                {
                    Random rand = new Random();
                    while (true)
                    {
                        int index = rand.Next(this.activeList.Count);
                        if (index != currentIndex)
                        {
                            newIndex = index;
                            break;
                        }
                    }
                }
                else
                {
                    if (currentIndex == -1)
                    {
                        newIndex = 0;
                    }
                    else if (currentIndex >= (this.activeList.Count - 1))
                    {
                        newIndex = 0;
                    }
                    else
                    {
                        newIndex = currentIndex + 1;
                    }
                }

                // get the entry corresponding to the index
                WallpaperEntry newEntry = this.activeList.List[newIndex];

                // try to load the thumbnail
                try
                {
                    string        filePath  = this.GetLocalCopyOfImage(newEntry, true);
                    BitmapDecoder uriBitmap = BitmapDecoder.Create(new Uri(filePath), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                }
                catch (Exception)
                {
                    // in case of an exception remove the entry from the list
                    this.activeList.RemoveFile(newEntry.FilePath, true);
                    listUpdated = true;

                    // try a different image
                    continue;
                }

                if (setImage)
                {
                    // try to set the background
                    try
                    {
                        this.SetBackgroundImage(newEntry);
                    }
                    catch (Exception)
                    {
                        // in case of an exception remove the entry from the list
                        this.activeList.RemoveFile(newEntry.FilePath, true);
                        listUpdated = true;

                        // try a different image
                        continue;
                    }
                }

                // if the current selection succeeded to load, end the loop
                break;
            }

            if (listUpdated)
            {
                if (this.activeList.Count > 0)
                {
                    c_imagenext.IsEnabled = true;
                }
                else
                {
                    c_imagenext.IsEnabled = false;
                }

                try
                {
                    this.activeList.SaveToFile();
                }
                catch (Exception)
                {
                    // nothing to do here
                }
            }

            this.EndTransaction();

            // set the appropriate image as current
            c_filelist.SelectedIndex = newIndex;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Set the UI properties based on the current image
        /// </summary>
        public async void GotoCurrentImage()
        {
            WallpaperEntry currentItem = c_filelist.SelectedItem as WallpaperEntry;

            if (currentItem == null)
            {
                // if no current entry found, clear out the UI

                c_imageset.IsEnabled   = false;
                c_previewimage.Source  = null;
                c_imageresolution.Text = string.Empty;
                c_imageformat.Text     = string.Empty;
                c_imagefilesize.Text   = string.Empty;

                if (this.imageStack.Count > 1)
                {
                    c_imageprevious.IsEnabled = true;
                }
                else
                {
                    c_imageprevious.IsEnabled = false;
                }

                c_filelist.ScrollIntoView(c_filelist.SelectedItem);
            }
            else
            {
                // try setting the UI properties based on current selection
                if (this.BeginTransaction())
                {
                    return;
                }

                c_imageset.IsEnabled = true;

                try
                {
                    // download the file to the cache if required
                    string filePath = this.GetLocalCopyOfImage(currentItem, true);

                    // load the image in memory
                    BitmapDecoder uriBitmap = BitmapDecoder.Create(new Uri(filePath), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

                    // set the image in UI
                    c_previewimage.Source = uriBitmap.Frames[0];

                    // update the image info
                    c_imageformat.Text = uriBitmap.CodecInfo.FriendlyName;

                    if (String.IsNullOrEmpty(currentItem.Dimensions))
                    {
                        currentItem.Dimensions = uriBitmap.Frames[0].PixelWidth.ToString() + "x" + uriBitmap.Frames[0].PixelHeight.ToString();
                    }

                    c_imageresolution.Text = currentItem.Dimensions;

                    FileInfo info = new FileInfo(filePath);
                    c_imagefilesize.Text = info.Length.ToString() + " bytes";

                    // push the current image in the stack
                    if ((this.imageStack.Count == 0) || (currentItem != this.imageStack.First()))
                    {
                        this.imageStack.Push(currentItem);
                    }

                    // enable the 'previous' button if there is something in the stack
                    if (this.imageStack.Count > 1)
                    {
                        c_imageprevious.IsEnabled = true;
                    }
                    else
                    {
                        c_imageprevious.IsEnabled = false;
                    }

                    // scroll the selection into view
                    c_filelist.ScrollIntoView(c_filelist.SelectedItem);

                    this.EndTransaction();

                    // completed processed current selection
                    return;
                }
                catch (Exception)
                {
                    // nothing to do here
                }

                // we should come here only if something went wrong in processing current selection
                // in that case store the current index and eset the position
                int currentIndex = c_filelist.SelectedIndex;
                c_filelist.SelectedIndex = -1;

                // remove the bad entry from the list
                this.activeList.RemoveFile(currentItem.FilePath, true);

                if (this.activeList.Count > 0)
                {
                    c_imagenext.IsEnabled = true;
                }
                else
                {
                    c_imagenext.IsEnabled = false;
                }

                try
                {
                    this.activeList.SaveToFile();
                }
                catch (Exception)
                {
                    // nothing to do here
                }

                this.EndTransaction();

                // now look for the next best alternative
                await Task.Delay(1);

                this.GotoNextImage(false, currentIndex - 1);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Method to initialize Picture Meta Data informations.
        /// </summary>
        /// <exception cref="ArgumentNullException">Occurs when invalid argument Picture file name is passed. Filename must be not null or empty or whitespace.</exception>
        /// <exception cref="FileFormatException">Occurs when loading meta data failed.</exception>
        private void Initialize()
        {
            if (Filename.IsNullOrWhiteSpace())
            {
                ArgumentNullException e = new ArgumentNullException($"Invalid argument Picture file name [{Filename}]. Filename must be not null or empty or whitespace.");
                log.Error(e.Output(), e);
                throw e;
            }

            Data.Filename  = Filename;
            Data.Comment   = "";
            Data.Copyright = "";
            Data.DateTaken = "";
            Data.Rating    = 0;
            Data.Title     = "";

            Data.Format      = new System.Windows.Media.PixelFormat();
            Data.Height      = 0;
            Data.Width       = 0;
            Data.PixelHeight = 0;
            Data.PixelWidth  = 0;
            Data.Length      = 0;

            try
            {
                // open a filestream for the file we wish to look at
                using (Stream fs = File.Open(Filename, FileMode.Open, FileAccess.ReadWrite))
                {
                    Data.Length = fs.Length;

                    // create a decoder to parse the file
                    BitmapDecoder decoder = BitmapDecoder.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.Default);

                    if (decoder == null || decoder.Frames.Count == 0)
                    {
                        log.Error("Creating bipmap decoder : failed ! ");
                        return;
                    }

                    // grab the bitmap frame, which contains the metadata
                    BitmapFrame frame = decoder.Frames[0];

                    if (frame == null)
                    {
                        log.Error("Getting bipmap decoder frame : failed ! ");
                        return;
                    }

                    Data.Format      = frame.Format;
                    Data.Height      = frame.Height;
                    Data.Width       = frame.Width;
                    Data.PixelHeight = frame.PixelHeight;
                    Data.PixelWidth  = frame.PixelWidth;

                    // get the metadata as BitmapMetadata
                    BitmapMetadata bmp = frame.Metadata as BitmapMetadata;

                    if (bmp == null)
                    {
                        log.Error("Getting bipmap metadata : failed ! ");
                        Data.DateTaken = new FileInfo(Filename).CreationTime.ToString();
                        return;
                    }

                    Data.Title     = bmp.Title ?? Path.GetFileName(Filename);
                    Data.DateTaken = bmp.DateTaken;
                    Data.Copyright = bmp.Copyright;
                    Data.Comment   = bmp.Comment;
                    Data.Rating    = bmp.Rating;
                }
            }
            catch (Exception e)
            {
                throw new FileFormatException("initializing picture meta data informations : failed !", e);
            }
        }
        private void LoadImage(string filename)
        {
            FullScreenImage.RenderTransform = null;
            FullScreenImage.Visibility      = Visibility.Visible;
            FullScreenMedia.Visibility      = Visibility.Collapsed;
            try
            {
                // This code is based on http://blogs.msdn.com/b/rwlodarc/archive/2007/07/18/using-wpf-s-inplacebitmapmetadatawriter.aspx
                BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
                using (Stream originalFile = File.Open(filename, FileMode.Open, FileAccess.Read))
                {
                    // Notice the BitmapCreateOptions and BitmapCacheOption. Using these options in the manner here
                    // will inform the JPEG decoder and encoder that we're doing a lossless transcode operation. If the
                    // encoder is anything but a JPEG encoder, then this no longer is a lossless operation.
                    // ( Details: Basically BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile
                    //   tell the decoder to use the original image bits and BitmapCacheOption.None tells the decoder to wait
                    //   with decoding. So, at the time of encoding the JPEG encoder understands that the input was a JPEG
                    //   and just copies over the image bits without decompressing and recompressing them. Hence, this is a
                    //   lossless operation. )
                    BitmapDecoder original = BitmapDecoder.Create(originalFile, createOptions, BitmapCacheOption.None);

                    if (!original.CodecInfo.FileExtensions.Contains("jpg"))
                    {
                        Console.WriteLine("The file you passed in is not a JPEG.");
                        return;
                    }

                    JpegBitmapEncoder output = new JpegBitmapEncoder();

                    if (imageRotationAngle == 90)
                    {
                        // If you're just interested in doing a lossless transcode without adding metadata, just do this:
                        //output.Frames = original.Frames;

                        // If you want to add metadata to the image (or could use the InPlaceBitmapMetadataWriter with added padding)
                        if (original.Frames[0] != null && original.Frames[0].Metadata != null)
                        {
                            // The BitmapMetadata object is frozen. So, you need to clone the BitmapMetadata and then
                            // set the padding on it. Lastly, you need to create a "new" frame with the updated metadata.
                            BitmapMetadata metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata;

                            // Of the metadata handlers that we ship in WIC, padding can only exist in IFD, EXIF, and XMP.
                            // Third parties implementing their own metadata handler may wish to support IWICFastMetadataEncoder
                            // and hence support padding as well.

                            /*
                             * metadata.SetQuery("/app1/ifd/PaddingSchema:Padding", paddingAmount);
                             * metadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", paddingAmount);
                             * metadata.SetQuery("/xmp/PaddingSchema:Padding", paddingAmount);
                             *
                             * // Since you're already adding metadata now, you can go ahead and add metadata up front.
                             * metadata.SetQuery("/app1/ifd/{uint=897}", "hello there");
                             * metadata.SetQuery("/app1/ifd/{uint=898}", "this is a test");
                             * metadata.Title = "This is a title";
                             */

                            // Create a new frame identical to the one from the original image, except the metadata changes.
                            // Essentially we want to keep this as close as possible to:
                            //     output.Frames = original.Frames;
                            output.Frames.Add(BitmapFrame.Create(original.Frames[0], original.Frames[0].Thumbnail, metadata, null));
                        }

                        using (Stream outputFile = File.Open(filename + "_out.jpg", FileMode.Create, FileAccess.ReadWrite))
                        {
                            output.Save(outputFile);
                        }
                    }
                }
            }
            catch
            {
                Overlay.Text = "";
            }

            try
            {
                using (
                    var imgStream = File.Open(filename, FileMode.Open, FileAccess.Read,
                                              FileShare.Delete | FileShare.Read))
                {
                    var img = new BitmapImage();
                    img.BeginInit();
                    img.CacheOption = BitmapCacheOption.OnLoad;

                    img.StreamSource = imgStream; // load image from stream instead of file
                    img.EndInit();

                    // Rotate Image if necessary
                    TransformedBitmap transformBmp = new TransformedBitmap();
                    transformBmp.BeginInit();
                    transformBmp.Source = img;
                    RotateTransform transform = new RotateTransform(imageRotationAngle);
                    transformBmp.Transform = transform;
                    transformBmp.EndInit();
                    FullScreenImage.Source = transformBmp;
                    // Initialize rotation variable for next image
                    imageRotationAngle = 0;

                    imageTimer.Start();

                    //if we failed to get exif data set some basic info
                    if (String.IsNullOrWhiteSpace(Overlay.Text))
                    {
                        Overlay.Text = filename + "\n" + img.Width + "x" + img.Height;
                    }
                }
            }
            catch
            {
                FullScreenImage.Source = null;
                ShowError("Can not load " + filename + " ! Screensaver paused, press P to unpause.");
            }
        }
Ejemplo n.º 17
0
        public static void ResizeJpg(string src, string dest, int px, bool withMetadata, bool withThumbnail, int quality)
        {
            int GreatestCommonDivisor(int a, int b)
            {
                while (a != 0 && b != 0)
                {
                    if (a > b)
                    {
                        a %= b;
                    }
                    else
                    {
                        b %= a;
                    }
                }

                return(a == 0 ? b : a);
            }

            void SetIfContainsQuery(BitmapMetadata bm, string query, object value)
            {
                if (bm.ContainsQuery(query))
                {
                    bm.SetQuery(query, value);
                }
            }

            var srcFile  = new FileInfo(src);
            var destFile = new FileInfo(dest);

            using Stream srcFileStream = File.Open(srcFile.FullName, FileMode.Open, FileAccess.Read);
            var decoder = BitmapDecoder.Create(srcFileStream, BitmapCreateOptions.None, BitmapCacheOption.None);

            if (decoder.CodecInfo?.FileExtensions.Contains("jpg") != true || decoder.Frames[0] == null)
            {
                return;
            }

            var firstFrame = decoder.Frames[0];

            var pxw = firstFrame.PixelWidth;             // image width
            var pxh = firstFrame.PixelHeight;            // image height
            var gcd = GreatestCommonDivisor(pxw, pxh);
            var rw  = pxw / gcd;                         // image ratio
            var rh  = pxh / gcd;                         // image ratio
            var q   = Math.Sqrt((double)px / (rw * rh)); // Bulgarian constant
            var stw = q * rw / pxw;                      // scale transform X
            var sth = q * rh / pxh;                      // scale transform Y

            var resized   = new TransformedBitmap(firstFrame, new ScaleTransform(stw, sth, 0, 0));
            var metadata  = withMetadata ? firstFrame.Metadata?.Clone() as BitmapMetadata : new BitmapMetadata("jpg");
            var thumbnail = withThumbnail ? firstFrame.Thumbnail : null;

            if (!withMetadata)
            {
                // even when withMetadata == false, set orientation
                var orientation = ((BitmapMetadata)firstFrame.Metadata)?.GetQuery("System.Photo.Orientation") ?? (ushort)1;
                metadata.SetQuery("System.Photo.Orientation", orientation);
            }

            // ifd ImageWidth a ImageHeight
            SetIfContainsQuery(metadata, "/app1/ifd/{ushort=256}", resized.PixelWidth);
            SetIfContainsQuery(metadata, "/app1/ifd/{ushort=257}", resized.PixelHeight);
            // exif ExifImageWidth a ExifImageHeight
            SetIfContainsQuery(metadata, "/app1/ifd/exif/{ushort=40962}", resized.PixelWidth);
            SetIfContainsQuery(metadata, "/app1/ifd/exif/{ushort=40963}", resized.PixelHeight);

            var encoder = new JpegBitmapEncoder {
                QualityLevel = quality
            };

            encoder.Frames.Add(BitmapFrame.Create(resized, thumbnail, metadata, firstFrame.ColorContexts));
            using (Stream destFileStream = File.Open(destFile.FullName, FileMode.Create, FileAccess.ReadWrite))
                encoder.Save(destFileStream);

            // set LastWriteTime to destination file as DateTaken so it can be correctly sorted in mobile apps
            var date = DateTime.MinValue;

            // try to first get dateTaken from file name
            var match = Regex.Match(srcFile.Name, "[0-9]{8}_[0-9]{6}");

            if (match.Success)
            {
                DateTime.TryParseExact(match.Value, "yyyyMMdd_HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
            }

            // try to get dateTaken from metadata
            if (date == DateTime.MinValue)
            {
                var dateTaken = ((BitmapMetadata)firstFrame.Metadata)?.DateTaken;
                DateTime.TryParse(dateTaken, out date);
            }

            if (date != DateTime.MinValue)
            {
                destFile.LastWriteTime = date;
            }
        }
Ejemplo n.º 18
0
        public void GenerateCache(FileItem fileItem)
        {
            bool deleteFile = false;

            if (fileItem == null)
            {
                return;
            }
            if (!File.Exists(fileItem.FileName))
            {
                return;
            }

            if ((File.Exists(fileItem.LargeThumb) && File.Exists(fileItem.SmallThumb)) && File.Exists(fileItem.InfoFile))
            {
                return;
            }

            string filename = fileItem.FileName;

            if (fileItem.IsRaw)
            {
                try
                {
                    string dcraw_exe = Path.Combine(Settings.ApplicationFolder, "dcraw.exe");
                    if (File.Exists(dcraw_exe))
                    {
                        PhotoUtils.RunAndWait(dcraw_exe, string.Format(" -e \"{0}\"", fileItem.FileName));
                        string thumb = Path.Combine(Path.GetDirectoryName(fileItem.FileName),
                                                    Path.GetFileNameWithoutExtension(fileItem.FileName) + ".thumb.jpg");
                        if (File.Exists(thumb))
                        {
                            deleteFile = true;
                            filename   = thumb;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Log.Error("Error get dcraw thumb", exception);
                }
            }


            GetMetadata(fileItem);
            try
            {
                using (MemoryStream fileStream = new MemoryStream(File.ReadAllBytes(filename)))
                {
                    BitmapDecoder bmpDec = BitmapDecoder.Create(fileStream,
                                                                BitmapCreateOptions.PreservePixelFormat,
                                                                BitmapCacheOption.OnLoad);

                    bmpDec.DownloadProgress += (o, args) => StaticHelper.Instance.LoadingProgress = args.Progress;

                    fileItem.FileInfo.Width  = bmpDec.Frames[0].PixelWidth;
                    fileItem.FileInfo.Height = bmpDec.Frames[0].PixelHeight;

                    double          dw = (double)LargeThumbSize / bmpDec.Frames[0].PixelWidth;
                    WriteableBitmap writeableBitmap =
                        BitmapFactory.ConvertToPbgra32Format(GetBitmapFrame(bmpDec.Frames[0],
                                                                            (int)(bmpDec.Frames[0].PixelWidth * dw),
                                                                            (int)(bmpDec.Frames[0].PixelHeight * dw),
                                                                            BitmapScalingMode.Linear));

                    LoadHistogram(fileItem, writeableBitmap);
                    Save2Jpg(writeableBitmap, fileItem.LargeThumb);

                    dw = (double)SmallThumbSize / writeableBitmap.PixelWidth;
                    writeableBitmap = writeableBitmap.Resize((int)(writeableBitmap.PixelWidth * dw),
                                                             (int)(writeableBitmap.PixelHeight * dw),
                                                             WriteableBitmapExtensions.Interpolation.Bilinear);

                    if (fileItem.FileInfo.ExifTags.ContainName("Exif.Image.Orientation"))
                    {
                        if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "bottom, right")
                        {
                            writeableBitmap = writeableBitmap.Rotate(180);
                        }

                        //if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "top, left")
                        //    writeableBitmap = writeableBitmap.Rotate(180);

                        if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "right, top")
                        {
                            writeableBitmap = writeableBitmap.Rotate(90);
                        }

                        if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "left, bottom")
                        {
                            writeableBitmap = writeableBitmap.Rotate(270);
                        }
                    }

                    Save2Jpg(writeableBitmap, fileItem.SmallThumb);
                    fileItem.Thumbnail = LoadSmallImage(fileItem);
                    fileItem.IsLoaded  = true;
                    fileItem.SaveInfo();
                    if (deleteFile)
                    {
                        File.Delete(filename);
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("Error generating cache " + fileItem.FileName, exception);
            }
        }
Ejemplo n.º 19
0
        private static async Task <(BitmapDecoder decoder, GifFile gifFile)> GetDecoder(BitmapSource image)
        {
            GifFile       gif           = null;
            BitmapDecoder decoder       = null;
            Stream        stream        = null;
            Uri           uri           = null;
            var           createOptions = BitmapCreateOptions.None;

            var bmp = image as BitmapImage;

            if (bmp != null)
            {
                createOptions = bmp.CreateOptions;
                if (bmp.StreamSource != null)
                {
                    stream = bmp.StreamSource;
                }
                else if (bmp.UriSource != null)
                {
                    uri = bmp.UriSource;
                    if (bmp.BaseUri != null && !uri.IsAbsoluteUri)
                    {
                        uri = new Uri(bmp.BaseUri, uri);
                    }
                }
            }
            else
            {
                var frame = image as BitmapFrame;
                if (frame != null)
                {
                    decoder = frame.Decoder;
                    Uri.TryCreate(frame.BaseUri, frame.ToString(), out uri);
                }
            }

            if (decoder == null)
            {
                if (stream != null)
                {
                    stream.Position = 0;
                    decoder         = BitmapDecoder.Create(stream, createOptions, BitmapCacheOption.OnLoad);
                }
                else if (uri != null && uri.IsAbsoluteUri)
                {
                    decoder = BitmapDecoder.Create(uri, createOptions, BitmapCacheOption.OnLoad);
                }
            }

            if (decoder is GifBitmapDecoder && !CanReadNativeMetadata(decoder))
            {
                if (stream != null)
                {
                    stream.Position = 0;
                    gif             = GifFile.ReadGifFile(stream, true);
                }
                else if (uri != null)
                {
                    gif = await DecodeGifFile(uri);
                }
                else
                {
                    throw new InvalidOperationException(
                              "Can't get URI or Stream from the source. AnimatedSource should be either a BitmapImage, or a BitmapFrame constructed from a URI.");
                }
            }
            if (decoder == null)
            {
                throw new InvalidOperationException(
                          "Can't get a decoder from the source. AnimatedSource should be either a BitmapImage or a BitmapFrame.");
            }
            return(decoder, gif);
        }
Ejemplo n.º 20
0
        public WriteableBitmap LoadImage(FileItem fileItem, bool fullres, bool showfocuspoints)
        {
            if (fileItem == null)
            {
                return(null);
            }
            if (!File.Exists(fileItem.LargeThumb) && !fullres)
            {
                return(null);
            }

            if (File.Exists(fileItem.InfoFile))
            {
                fileItem.LoadInfo();
            }
            else
            {
                fileItem.FileInfo = new FileInfo();
            }

            try
            {
                BitmapDecoder bmpDec = null;
                if (fullres && fileItem.IsRaw)
                {
                    try
                    {
                        string dcraw_exe = Path.Combine(Settings.ApplicationFolder, "dcraw.exe");
                        if (File.Exists(dcraw_exe))
                        {
                            PhotoUtils.RunAndWait(dcraw_exe, string.Format(" -e \"{0}\"", fileItem.FileName));
                            string thumb = Path.Combine(Path.GetDirectoryName(fileItem.FileName),
                                                        Path.GetFileNameWithoutExtension(fileItem.FileName) + ".thumb.jpg");
                            if (File.Exists(thumb))
                            {
                                bmpDec = BitmapDecoder.Create(new Uri(thumb), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                                File.Delete(thumb);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Log.Error("Error get dcraw thumb", exception);
                    }
                }

                if (bmpDec == null)
                {
                    bmpDec = BitmapDecoder.Create(new Uri(fullres ? fileItem.FileName : fileItem.LargeThumb),
                                                  BitmapCreateOptions.None,
                                                  BitmapCacheOption.OnLoad);
                }

                double          dw = (double)MaxThumbSize / bmpDec.Frames[0].PixelWidth;
                WriteableBitmap bitmap;

                /*
                 * if (fullres)
                 *  bitmap =
                 *      BitmapFactory.ConvertToPbgra32Format(GetBitmapFrame(bmpDec.Frames[0],
                 *                                                          (int) (bmpDec.Frames[0].PixelWidth*dw),
                 *                                                          (int) (bmpDec.Frames[0].PixelHeight*dw),
                 *                                                          BitmapScalingMode.NearestNeighbor));
                 * else
                 *  bitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames[0]);
                 */
                bitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames[0]);

                if (showfocuspoints)
                {
                    DrawFocusPoints(fileItem, bitmap);
                }

                if (fileItem.FileInfo != null && fileItem.FileInfo.ExifTags.ContainName("Exif.Image.Orientation"))
                {
                    if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "bottom, right")
                    {
                        bitmap = bitmap.Rotate(180);
                    }

                    //if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "top, left")
                    //    bitmap = bitmap.Rotate(180);

                    if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "right, top")
                    {
                        bitmap = bitmap.Rotate(90);
                    }

                    if (fileItem.FileInfo.ExifTags["Exif.Image.Orientation"] == "left, bottom")
                    {
                        bitmap = bitmap.Rotate(270);
                    }
                }

                if (ServiceProvider.Settings.RotateIndex != 0)
                {
                    switch (ServiceProvider.Settings.RotateIndex)
                    {
                    case 1:
                        bitmap = bitmap.Rotate(90);
                        break;

                    case 2:
                        bitmap = bitmap.Rotate(180);
                        break;

                    case 3:
                        bitmap = bitmap.Rotate(270);
                        break;
                    }
                }

                if (ServiceProvider.Settings.FlipPreview)
                {
                    bitmap = bitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                }

                bitmap.Freeze();
                return(bitmap);
            }
            catch (Exception exception)
            {
                Log.Error("Error loading image", exception);
            }
            return(null);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Combines the images to one big image.
        /// </summary>
        /// <param name="infos">Tuple containing the image
        /// and text to stitch together.</param>
        /// <returns>Task.</returns>
        private async Task <PngBitmapEncoder> StitchImagesTogether(List <Tuple <Uri, string> > infos)
        {
            BitmapFrame[] frames = new BitmapFrame[infos.Count];
            for (int i = 0; i < frames.Length; i++)
            {
                frames[i] = BitmapDecoder.Create(infos[i].Item1 ?? (SelectedCollageType == CollageType.Albums ? new Uri("pack://application:,,,/Resources/noalbumimage.png") : new Uri("pack://application:,,,/Resources/noartistimage.png")), BitmapCreateOptions.None, BitmapCacheOption.OnDemand).Frames.First();
            }

            OnStatusUpdated("Downloading images...");
            while (frames.Any(f => f.IsDownloading))
            {
                await Task.Delay(100);
            }

            int imageWidth  = frames[0].PixelWidth;
            int imageHeight = frames[0].PixelHeight;

            int collageSize = 0;

            if (SelectedCollageSize == CollageSize.Custom)
            {
                collageSize = CustomCollageSize;
            }
            else
            {
                collageSize = (int)SelectedCollageSize;
            }

            DrawingVisual dv = new DrawingVisual();

            using (DrawingContext dc = dv.RenderOpen())
            {
                int cnt = 0;
                for (int y = 0; y < collageSize; y++)
                {
                    for (int x = 0; x < collageSize; x++)
                    {
                        dc.DrawImage(frames[cnt], new Rect(x * imageWidth, y * imageHeight, imageWidth, imageHeight));

                        if (!string.IsNullOrEmpty(infos[cnt].Item2))
                        {
                            // create text
                            FormattedText extraText = new FormattedText(infos[cnt].Item2, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 14, Brushes.Black)
                            {
                                MaxTextWidth  = imageWidth,
                                MaxTextHeight = imageHeight
                            };

                            dc.DrawText(extraText, new Point(x * imageWidth + 1, y * imageHeight + 1));
                            extraText.SetForegroundBrush(Brushes.White);
                            dc.DrawText(extraText, new Point(x * imageWidth, y * imageHeight));
                        }

                        cnt++;
                    }
                }
            }

            // Converts the Visual (DrawingVisual) into a BitmapSource
            RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth * collageSize, imageHeight * collageSize, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(dv);

            // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bmp));

            return(encoder);
        }
Ejemplo n.º 22
0
        public static void Convert(ConvertOptions options)
        {
            if (!File.Exists(options.InputFileName))
            {
                throw new FileNotFoundException("File does not exist!", options.InputFileName);
            }
            if (options.OutputFolder == null)
            {
                options.OutputFolder = Path.GetDirectoryName(options.InputFileName);
            }
            if (options.OutputType == ConvertOptions.Output.EndCake)
            {
                options.OutputFormat = TextureFormat.RGBA5551;
                options.ImageWidth   = 320;
                options.ImageHeight  = 240;
                options.TileWidth    = 64;
                options.TileHeight   = 32;
            }

            var filename = Path.GetFileNameWithoutExtension(options.InputFileName);

            var uri     = new Uri(options.InputFileName);
            var decoder = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

            if (!options.ImageWidth.HasValue)
            {
                options.ImageWidth = decoder.Frames[0].PixelWidth;
            }
            if (!options.ImageHeight.HasValue)
            {
                options.ImageHeight = decoder.Frames[0].PixelHeight;
            }

            var imagedata = SplitImage(decoder.Frames, options);
            var tiles     = GenerateTiles(options);

            if (options.OutputType == ConvertOptions.Output.ModelObj)
            {
                WriteObj(tiles, imagedata, options);
                return;
            }

            var textures = ToN64Textures(imagedata, options.OutputFormat);

            if (options.OutputType == ConvertOptions.Output.RawImage)
            {
                var outpath = Path.Combine(options.OutputFolder, filename + ".bin");
                var outfile = File.Create(outpath);
                outfile.Write(textures);
                outfile.Close();
                return;
            }

            if (options.OutputType == ConvertOptions.Output.EndCake)
            {
                WriteCake(tiles, textures, options);
                return;
            }

            throw new NotImplementedException();
        }
Ejemplo n.º 23
0
        // Dugmici za dodavanje, azuriranje i brisanje zivotinje iz liste
        private void Dodavanje_Zivotinje(object sender, RoutedEventArgs e)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(godPrihod.Text, "[^0-9]") || System.Text.RegularExpressions.Regex.IsMatch(IdZivotinje.Text, "[^0-9]") || Animals.Any(x => x.Id == IdZivotinje.Text) || pickDatum.SelectedDate == null || TipZivotinje.SelectedItem == null || StTurZivotinje.SelectedItem == null || StUgrZivotinje.SelectedItem == null ||
                IdZivotinje.Text.Equals("") || ImeZivotinje.Text.Equals("") || godPrihod.Text.Equals(""))
            {
                lDatum.Foreground     = new SolidColorBrush(Colors.White);
                lDatum.Content        = " Datum: ";
                lTip.Foreground       = new SolidColorBrush(Colors.White);
                lTip.Content          = " Tip: ";
                lStTur.Foreground     = new SolidColorBrush(Colors.White);
                lStTur.Content        = "Turistički Status: ";
                lStUgr.Foreground     = new SolidColorBrush(Colors.White);
                lStUgr.Content        = "Status Ugroženosti:";
                lId.Foreground        = new SolidColorBrush(Colors.White);
                lId.Content           = "Id: ";
                lIme.Foreground       = new SolidColorBrush(Colors.White);
                lIme.Content          = " Ime: ";
                lGodPrihod.Foreground = new SolidColorBrush(Colors.White);
                lGodPrihod.Content    = "Godišnji prihod: ";

                if (pickDatum.SelectedDate == null)
                {
                    lDatum.Foreground = new SolidColorBrush(Colors.Red);
                    lDatum.Content    = " >>> Datum: ";
                }

                if (TipZivotinje.SelectedItem == null)
                {
                    lTip.Foreground = new SolidColorBrush(Colors.Red);
                    lTip.Content    = " >>> Tip: ";
                }

                if (StTurZivotinje.SelectedItem == null)
                {
                    lStTur.Foreground = new SolidColorBrush(Colors.Red);
                    lStTur.Content    = ">>T. Status: ";
                }

                if (StUgrZivotinje.SelectedItem == null)
                {
                    lStUgr.Foreground = new SolidColorBrush(Colors.Red);
                    lStUgr.Content    = ">> Ugroženost: ";
                }

                if (IdZivotinje.Text.Equals(""))
                {
                    lId.Foreground = new SolidColorBrush(Colors.Red);
                    lId.Content    = " >>> Id: ";
                }

                if (ImeZivotinje.Text.Equals(""))
                {
                    lIme.Foreground = new SolidColorBrush(Colors.Red);
                    lIme.Content    = " >>> Ime: ";
                }

                if (godPrihod.Text.Equals("") || System.Text.RegularExpressions.Regex.IsMatch(godPrihod.Text, "[^0-9]"))
                {
                    lGodPrihod.Foreground = new SolidColorBrush(Colors.Red);
                    lGodPrihod.Content    = ">> Godišnji prihod: ";
                }

                if (Animals.Any(x => x.Id == IdZivotinje.Text))
                {
                    lId.Foreground = new SolidColorBrush(Colors.Red);
                    lId.Content    = ">>> Id već postoji: ";
                }

                if (System.Text.RegularExpressions.Regex.IsMatch(IdZivotinje.Text, "[^0-9]"))
                {
                    lId.Foreground = new SolidColorBrush(Colors.Red);
                    lId.Content    = " >>> Id: ";
                }

                return;
            }


            lDatum.Foreground     = new SolidColorBrush(Colors.White);
            lDatum.Content        = " Datum: ";
            lTip.Foreground       = new SolidColorBrush(Colors.White);
            lTip.Content          = " Tip: ";
            lStTur.Foreground     = new SolidColorBrush(Colors.White);
            lStTur.Content        = "Turistički Status: ";
            lStUgr.Foreground     = new SolidColorBrush(Colors.White);
            lStUgr.Content        = "Status Ugroženosti:";
            lId.Foreground        = new SolidColorBrush(Colors.White);
            lId.Content           = "Id: ";
            lIme.Foreground       = new SolidColorBrush(Colors.White);
            lIme.Content          = " Ime: ";
            lGodPrihod.Foreground = new SolidColorBrush(Colors.White);
            lGodPrihod.Content    = "Godišnji prihod: ";

            Animal.TuristickiStatus  st1 = (Animal.TuristickiStatus)Enum.Parse(typeof(Animal.TuristickiStatus), StTurZivotinje.Text);
            Animal.StatusUgrozenosti st2 = (Animal.StatusUgrozenosti)Enum.Parse(typeof(Animal.StatusUgrozenosti), StUgrZivotinje.Text);

            BitmapSource bitmapSource;

            if (SlikaZivotinje.Source != null)
            {
                Uri           myUri   = new Uri(SlikaZivotinje.Source.ToString(), UriKind.RelativeOrAbsolute);
                BitmapDecoder decoder = BitmapDecoder.Create(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                bitmapSource = decoder.Frames[0];
            }
            else
            {
                Tip t = (Tip)TipZivotinje.SelectedItem;
                bitmapSource = (BitmapSource)t.Image;
            }



            List <Etiketa> lista = new List <Etiketa>();

            for (int i = 0; i < EtiketeZivotinje.SelectedItems.Count; i++)
            {
                lista.Add((Etiketa)EtiketeZivotinje.SelectedItems[i]);
            }


            Animals.Add(new Animal {
                Id              = IdZivotinje.Text,
                Ime             = ImeZivotinje.Text,
                Opis            = OpisZivotinje.Text,
                StUgr           = st2,
                StTur           = st1,
                Opasna          = (bool)cbOpasna.IsChecked,
                NaseljeniRegion = (bool)cbNaseljeniRegion.IsChecked,
                CrvenaLista     = (bool)cbCrvenaLista.IsChecked,
                GodisnjiPrihod  = godPrihod.Text,
                Datum           = (DateTime)pickDatum.SelectedDate,
                Image           = bitmapSource,
                TipZiv          = (Tip)TipZivotinje.SelectedItem,
                EtiketeZiv      = lista,
                locationX       = "-",
                locationY       = "-"
            });

            RightRectangle.Visibility = Visibility.Hidden;
        }
Ejemplo n.º 24
0
        public void GetBitmap(BitmapFile bitmapFile)
        {
            if (_isworking)
            {
                _nextfile = bitmapFile;
                return;
            }
            _nextfile    = null;
            _isworking   = true;
            _currentfile = bitmapFile;
            _currentfile.RawCodecNeeded = false;
            if (!File.Exists(_currentfile.FileItem.FileName))
            {
                Log.Error("File not found " + _currentfile.FileItem.FileName);
                StaticHelper.Instance.SystemMessage = "File not found " + _currentfile.FileItem.FileName;
            }
            else
            {
                //Metadata.Clear();
                try
                {
                    if (_currentfile.FileItem.IsRaw)
                    {
                        WriteableBitmap writeableBitmap = null;
                        Log.Debug("Loading raw file.");
                        BitmapDecoder bmpDec = BitmapDecoder.Create(new Uri(_currentfile.FileItem.FileName),
                                                                    BitmapCreateOptions.None,
                                                                    BitmapCacheOption.Default);
                        if (bmpDec.CodecInfo != null)
                        {
                            Log.Debug("Raw codec: " + bmpDec.CodecInfo.FriendlyName);
                        }
                        if (bmpDec.Thumbnail != null)
                        {
                            WriteableBitmap bitmap = new WriteableBitmap(bmpDec.Thumbnail);
                            bitmap.Freeze();
                            bitmapFile.DisplayImage = bitmap;
                        }

                        if (ServiceProvider.Settings.LowMemoryUsage)
                        {
                            if (bmpDec.Thumbnail != null)
                            {
                                writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Thumbnail);
                            }
                            else
                            {
                                writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames[0]);
                                double dw = 2000 / writeableBitmap.Width;
                                writeableBitmap = writeableBitmap.Resize((int)(writeableBitmap.PixelWidth * dw),
                                                                         (int)(writeableBitmap.PixelHeight * dw),
                                                                         WriteableBitmapExtensions.Interpolation.Bilinear);
                            }
                            bmpDec = null;
                        }
                        else
                        {
                            writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames.Single());
                        }
                        GetMetadata(_currentfile, writeableBitmap);
                        Log.Debug("Loading raw file done.");
                    }
                    else
                    {
                        BitmapImage bi = new BitmapImage();
                        // BitmapImage.UriSource must be in a BeginInit/EndInit block.
                        bi.BeginInit();

                        if (ServiceProvider.Settings.LowMemoryUsage)
                        {
                            bi.DecodePixelWidth = 2000;
                        }

                        bi.UriSource = new Uri(_currentfile.FileItem.FileName);
                        bi.EndInit();
                        WriteableBitmap writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bi);
                        GetMetadata(_currentfile, writeableBitmap);
                        Log.Debug("Loading bitmap file done.");
                    }
                }
                catch (FileFormatException)
                {
                    _currentfile.RawCodecNeeded = true;
                    Log.Debug("Raw codec not installed or unknown file format");
                    StaticHelper.Instance.SystemMessage = "Raw codec not installed or unknown file format";
                }
                catch (Exception exception)
                {
                    Log.Error(exception);
                }
                if (_nextfile == null)
                {
                    Thread threadPhoto = new Thread(GetAdditionalData);
                    threadPhoto.Start(_currentfile);
                    _currentfile.OnBitmapLoaded();
                    _currentfile = null;
                    _isworking   = false;
                }
                else
                {
                    _isworking = false;
                    GetBitmap(_nextfile);
                }
            }
        }
Ejemplo n.º 25
0
        public void Execute()
        {
            string path;

            using (var inputStream = _fileSystem.File.OpenRead(_file))
            {
                var decoder = BitmapDecoder.Create(
                    inputStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

                var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat);
                if (!encoder.CanEncode())
                {
                    encoder = BitmapEncoder.Create(_settings.FallbackEncoder);
                }

                ConfigureEncoder(encoder);

                if (decoder.Metadata != null)
                {
                    try
                    {
                        encoder.Metadata = decoder.Metadata;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                if (decoder.Palette != null)
                {
                    encoder.Palette = decoder.Palette;
                }

                foreach (var originalFrame in decoder.Frames)
                {
                    BitmapMetadata metadata = (BitmapMetadata)originalFrame.Metadata;
                    if (metadata != null)
                    {
                        try
                        {
                            // Detect whether metadata can copied successfully
                            _ = metadata.Clone();
                        }
                        catch (ArgumentException)
                        {
                            metadata = null;
                        }
                    }

                    if (_settings.RemoveMetadata && metadata != null)
                    {
                        // strip any metadata that doesn't affect rendering
                        var newMetadata = new BitmapMetadata(metadata.Format);

                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Photo.Orientation");
                        metadata.CopyMetadataPropertyTo(newMetadata, "System.Image.ColorSpace");

                        metadata = newMetadata;
                    }

                    encoder.Frames.Add(
                        BitmapFrame.Create(
                            Transform(originalFrame),
                            thumbnail: null,
                            metadata,
                            colorContexts: null));
                }

                path = GetDestinationPath(encoder);
                _fileSystem.Directory.CreateDirectory(_fileSystem.Path.GetDirectoryName(path));
                using (var outputStream = _fileSystem.File.Open(path, FileMode.CreateNew, FileAccess.Write))
                {
                    encoder.Save(outputStream);
                }
            }

            if (_settings.KeepDateModified)
            {
                _fileSystem.File.SetLastWriteTimeUtc(path, _fileSystem.File.GetLastWriteTimeUtc(_file));
            }

            if (_settings.Replace)
            {
                var backup = GetBackupPath();
                _fileSystem.File.Replace(path, _file, backup, ignoreMetadataErrors: true);
                FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
            }
        }
Ejemplo n.º 26
0
        static public ICaptureProcessor createCaptureProcessor(string a_FilePath)
        {
            if (MainWindow.mCaptureManager == null)
            {
                return(null);
            }

            string lPresentationDescriptor = "<?xml version='1.0' encoding='UTF-8'?>" +
                                             "<PresentationDescriptor StreamCount='1'>" +
                                             "<PresentationDescriptor.Attributes Title='Attributes of Presentation'>" +
                                             "<Attribute Name='MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK' GUID='{58F0AAD8-22BF-4F8A-BB3D-D2C4978C6E2F}' Title='The symbolic link for a video capture driver.' Description='Contains the unique symbolic link for a video capture driver.'>" +
                                             "<SingleValue Value='ImageCaptureProcessor' />" +
                                             "</Attribute>" +
                                             "<Attribute Name='MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME' GUID='{60D0E559-52F8-4FA2-BBCE-ACDB34A8EC01}' Title='The display name for a device.' Description='The display name is a human-readable string, suitable for display in a user interface.'>" +
                                             "<SingleValue Value='Image Capture Processor' />" +
                                             "</Attribute>" +
                                             "</PresentationDescriptor.Attributes>" +
                                             "<StreamDescriptor Index='0' MajorType='MFMediaType_Video' MajorTypeGUID='{73646976-0000-0010-8000-00AA00389B71}'>" +
                                             "<MediaTypes TypeCount='1'>" +
                                             "<MediaType Index='0'>" +
                                             "<MediaTypeItem Name='MF_MT_FRAME_SIZE' GUID='{1652C33D-D6B2-4012-B834-72030849A37D}' Title='Width and height of the video frame.' Description='Width and height of a video frame, in pixels.'>" +
                                             "<Value.ValueParts>" +
                                             "<ValuePart Title='Width' Value='Temp_Width' />" +
                                             "<ValuePart Title='Height' Value='Temp_Height' />" +
                                             "</Value.ValueParts>" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_AVG_BITRATE' GUID='{20332624-FB0D-4D9E-BD0D-CBF6786C102E}' Title='Approximate data rate of the video stream.' Description='Approximate data rate of the video stream, in bits per second, for a video media type.'>" +
                                             "<SingleValue  Value='33570816' />" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_MAJOR_TYPE' GUID='{48EBA18E-F8C9-4687-BF11-0A74C9F96A8F}' Title='Major type GUID for a media type.' Description='The major type defines the overall category of the media data.'>" +
                                             "<SingleValue Value='MFMediaType_Video' GUID='{73646976-0000-0010-8000-00AA00389B71}' />" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_DEFAULT_STRIDE' GUID='{644B4E48-1E02-4516-B0EB-C01CA9D49AC6}' Title='Default surface stride.' Description='Default surface stride, for an uncompressed video media type. Stride is the number of bytes needed to go from one row of pixels to the next.'>" +
                                             "<SingleValue Value='Temp_Stride' />" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_FIXED_SIZE_SAMPLES' GUID='{B8EBEFAF-B718-4E04-B0A9-116775E3321B}' Title='The fixed size of samples in stream.' Description='Specifies for a media type whether the samples have a fixed size.'>" +
                                             "<SingleValue Value='True' />" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_FRAME_RATE' GUID='{C459A2E8-3D2C-4E44-B132-FEE5156C7BB0}' Title='Frame rate.' Description='Frame rate of a video media type, in frames per second.'>" +
                                             "<RatioValue Value='10.0'>" +
                                             "<Value.ValueParts>" +
                                             "<ValuePart Title='Numerator'  Value='10' />" +
                                             "<ValuePart Title='Denominator'  Value='1' />" +
                                             "</Value.ValueParts>" +
                                             "</RatioValue>" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_PIXEL_ASPECT_RATIO' GUID='{C6376A1E-8D0A-4027-BE45-6D9A0AD39BB6}' Title='Pixel aspect ratio.' Description='Pixel aspect ratio for a video media type.'>" +
                                             "<RatioValue  Value='1'>" +
                                             "<Value.ValueParts>" +
                                             "<ValuePart Title='Numerator'  Value='1' />" +
                                             "<ValuePart Title='Denominator'  Value='1' />" +
                                             "</Value.ValueParts>" +
                                             "</RatioValue>" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_ALL_SAMPLES_INDEPENDENT' GUID='{C9173739-5E56-461C-B713-46FB995CB95F}' Title='Independent of samples.' Description='Specifies for a media type whether each sample is independent of the other samples in the stream.'>" +
                                             "<SingleValue Value='True' />" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_SAMPLE_SIZE' GUID='{DAD3AB78-1990-408B-BCE2-EBA673DACC10}' Title='The fixed size of each sample in stream.' Description='Specifies the size of each sample, in bytes, in a media type.'>" +
                                             "<SingleValue Value='Temp_SampleSize' />" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_INTERLACE_MODE' GUID='{E2724BB8-E676-4806-B4B2-A8D6EFB44CCD}' Title='Describes how the frames are interlaced.' Description='Describes how the frames in a video media type are interlaced.'>" +
                                             "<SingleValue Value='MFVideoInterlace_Progressive' />" +
                                             "</MediaTypeItem>" +
                                             "<MediaTypeItem Name='MF_MT_SUBTYPE' GUID='{F7E34C9A-42E8-4714-B74B-CB29D72C35E5}' Title='Subtype GUID for a media type.' Description='The subtype GUID defines a specific media format type within a major type.'>" +
                                             "<SingleValue GUID='{Temp_SubTypeGUID}' />" +
                                             "</MediaTypeItem>" +
                                             "</MediaType>" +
                                             "</MediaTypes>" +
                                             "</StreamDescriptor>" +
                                             "</PresentationDescriptor>";

            ImageCaptureProcessor lICaptureProcessor = new ImageCaptureProcessor();


            using (var lImageStream = File.Open(a_FilePath, FileMode.Open))
            {
                if (lImageStream == null)
                {
                    return(null);
                }

                var lBitmap = BitmapDecoder.Create(lImageStream, BitmapCreateOptions.None, BitmapCacheOption.None);

                if (lBitmap == null)
                {
                    return(null);
                }

                if (lBitmap.Frames == null || lBitmap.Frames.Count == 0)
                {
                    return(null);
                }

                BitmapSource bitmapSource = lBitmap.Frames[0];

                int lStride = 0;

                Guid lMFVideoFormat_RGBFormat = MFVideoFormat_ARGB32;

                MainWindow.mCaptureManager.getStrideForBitmapInfoHeader(lMFVideoFormat_RGBFormat, (uint)bitmapSource.PixelWidth, out lStride);

                int width  = bitmapSource.PixelWidth;
                int height = bitmapSource.PixelHeight;
                int stride = (int)Math.Abs(lStride);



                lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Width", ((uint)bitmapSource.PixelWidth).ToString());

                lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Height", ((uint)bitmapSource.PixelHeight).ToString());

                lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_Stride", lStride.ToString());

                lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_SampleSize", ((uint)(Math.Abs(lStride) * bitmapSource.PixelHeight * 3)).ToString());

                lPresentationDescriptor = lPresentationDescriptor.Replace("Temp_SubTypeGUID", lMFVideoFormat_RGBFormat.ToString());

                lICaptureProcessor.mPresentationDescriptor = lPresentationDescriptor;


                foreach (var litem in lBitmap.Frames)
                {
                    bitmapSource = litem;

                    if (bitmapSource.Format != System.Windows.Media.PixelFormats.Bgra32)
                    {
                        FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

                        newFormatedBitmapSource.BeginInit();

                        newFormatedBitmapSource.Source = litem;

                        newFormatedBitmapSource.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;

                        newFormatedBitmapSource.EndInit();

                        bitmapSource = newFormatedBitmapSource;
                    }

                    byte[] lPixels = new byte[height * stride];

                    bitmapSource.CopyPixels(lPixels, stride, 0);

                    lICaptureProcessor.mRawDataFrames.Add(new RawDataFrame(lPixels));
                }
            }

            return(lICaptureProcessor);
        }
Ejemplo n.º 27
0
        public void Execute()
        {
            string path;

            using (var inputStream = File.OpenRead(_file))
            {
                var decoder = BitmapDecoder.Create(
                    inputStream,
                    BitmapCreateOptions.PreservePixelFormat,
                    BitmapCacheOption.None);

                var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat);
                if (!encoder.CanEncode())
                {
                    encoder = BitmapEncoder.Create(_settings.FallbackEncoder);
                }

                ConfigureEncoder(encoder);

                if (decoder.Metadata != null)
                {
                    try
                    {
                        encoder.Metadata = decoder.Metadata;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                if (decoder.Palette != null)
                {
                    encoder.Palette = decoder.Palette;
                }

                foreach (var originalFrame in decoder.Frames)
                {
                    encoder.Frames.Add(
                        BitmapFrame.Create(
                            Transform(originalFrame),
                            thumbnail: null,
                            // TODO: Add an option to strip any metadata that doesn't affect rendering (issue #3)
                            (BitmapMetadata)originalFrame.Metadata,
                            colorContexts: null));
                }

                path = GetDestinationPath(encoder);
                Directory.CreateDirectory(Path.GetDirectoryName(path));
                using (var outputStream = File.Open(path, FileMode.CreateNew, FileAccess.Write))
                    encoder.Save(outputStream);
            }

            if (_settings.KeepDateModified)
            {
                File.SetLastWriteTimeUtc(path, File.GetLastWriteTimeUtc(_file));
            }

            if (_settings.Replace)
            {
                var backup = GetBackupPath();
                File.Replace(path, _file, backup, ignoreMetadataErrors: true);
                FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        ///
        /// </summary>
        private async Task LoadImageAsync()
        {
            if (this.PreviewImageInfo == null || this.PreviewImageInfo.BitmapFilePath == null)
            {
                LOG.Warn("読み込む画像情報が未設定です。");
                return;
            }

            var sw = new Stopwatch();

            sw.Start();
            await Task.Factory.StartNew(() =>
            {
                // NOTE: 画像ファイルの読み込み

                // サンプルコード:読み込んでいるファイルは固定
                try
                {
                    string filePath = string.Format(this.PreviewImageInfo.BitmapFilePath);
                    using (Stream stream = new FileStream(
                               filePath,
                               FileMode.Open,
                               FileAccess.Read,
                               FileShare.ReadWrite | FileShare.Delete
                               ))
                    {
                        // ロックしないように指定したstreamを使用する。
                        BitmapDecoder decoder = BitmapDecoder.Create(
                            stream,
                            BitmapCreateOptions.None,                             // この辺のオプションは適宜
                            BitmapCacheOption.Default                             // これも
                            );
                        var srcBmp      = decoder.Frames[0];
                        int pixelHeight = srcBmp.PixelHeight;
                        int pixelWidth  = srcBmp.PixelWidth;

                        WriteableBitmap bmp = new WriteableBitmap(
                            srcBmp.PixelWidth,
                            srcBmp.PixelHeight,
                            96, 96,
                            srcBmp.Format,
                            srcBmp.Palette);

                        // Calculate stride of source
                        int stride = (srcBmp.PixelWidth *srcBmp.Format.BitsPerPixel + 7) / 8;

                        // Create data array to hold source pixel data
                        byte[] data = new byte[stride];

                        for (int i = 0; i < pixelHeight; i++)
                        {
                            srcBmp.CopyPixels(
                                new Int32Rect(0, i, pixelWidth, 1),
                                data,
                                stride,
                                0);


                            bmp.WritePixels(
                                new Int32Rect(0, 0, pixelWidth, 1),
                                data,
                                stride,
                                0,
                                i);
                        }
                        bmp.Freeze();

                        this.ImageBitmap = bmp;
                    }
                }
                catch (Exception exc)
                {
                    //MessageBox.Show(this, "[" + exc.Message + "]\n" + exc.StackTrace, this.Title);
                }
                // -- サンプルコード

                //var decorator = new ImageArtifactDecorator(this.Entity.ModelInstance, ImageArtifactDecorator.OperationType.LoadImage);
                //decorator.Operation();
                //this.ImageBitmap = decorator.Image;
            });

            sw.Stop();

            LOG.DebugFormat("画像表示までの時間:{0}", sw.ElapsedMilliseconds);


            // 画像サイズ調整
            if (this.EnabledImageFitMode)
            {
                FittingViewSize(this._ImageCanvasSize.Width, this._ImageCanvasSize.Height);
            }
            else
            {
                this.ImageStretch = Stretch.None;

                UpdateImageTransform();
            }
        }
    public static void SetImageMetadata(string imagesFolderPath)
    {
        string originalPath = @"C:\Users\test\Desktop\test.jpg";
        string outputPath   = Environment.CurrentDirectory + @"\output.jpg";
        string finalPath    = Environment.CurrentDirectory + @"\output_beforeInPlaceBitmapMetadataWriter.jpg";
        BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
        uint paddingAmount = 2048;     // 2Kb padding for this example, but really this can be any value.

        // Our recommendation is to keep this between 1Kb and 5Kb as most metadata updates are not large.
        // High level overview:
        //   1. Perform a lossles transcode on the JPEG
        //   2. Add appropriate padding
        //   3. Optionally add whatever metadata we need to add initially
        //   4. Save the file
        //   5. For sanity, we verify that we really did a lossless transcode
        //   6. Open the new file and add metadata in-place
        using (Stream originalFile = File.Open(originalPath, FileMode.Open, FileAccess.Read))
        {
            // Notice the BitmapCreateOptions and BitmapCacheOption. Using these options in the manner here
            // will inform the JPEG decoder and encoder that we're doing a lossless transcode operation. If the
            // encoder is anything but a JPEG encoder, then this no longer is a lossless operation.
            // ( Details: Basically BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile
            //   tell the decoder to use the original image bits and BitmapCacheOption.None tells the decoder to wait
            //   with decoding. So, at the time of encoding the JPEG encoder understands that the input was a JPEG
            //   and just copies over the image bits without decompressing and recompressing them. Hence, this is a
            //   lossless operation. )
            BitmapDecoder original = BitmapDecoder.Create(originalFile, createOptions, BitmapCacheOption.None);
            if (!original.CodecInfo.FileExtensions.Contains("jpg"))
            {
                Console.WriteLine("The file you passed in is not a JPEG.");
                return;
            }
            JpegBitmapEncoder output = new JpegBitmapEncoder();
            // If you're just interested in doing a lossless transcode without adding metadata, just do this:
            //output.Frames = original.Frames;
            // If you want to add metadata to the image using the InPlaceBitmapMetadataWriter, first add padding:
            if (original.Frames[0] != null && original.Frames[0].Metadata != null)
            {
                // Your gut feel may want you to do something like:
                //     output.Frames = original.Frames;
                //     BitmapMetadata metadata = output.Frames[0].Metadata as BitmapMetadata;
                //     if (metadata != null)
                //     {
                //         metadata.SetQuery("/app1/ifd/PaddingSchema:Padding", paddingAmount);
                //     }
                // However, the BitmapMetadata object is frozen. So, you need to clone the BitmapMetadata and then
                // set the padding on it. Lastly, you need to create a "new" frame with the updated metadata.
                BitmapMetadata metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata;
                // Of the metadata handlers that we ship in WIC, padding can only exist in IFD, EXIF, and XMP.
                // Third parties implementing their own metadata handler may wish to support IWICFastMetadataEncoder
                // and hence support padding as well.
                metadata.SetQuery("/app1/ifd/PaddingSchema:Padding", paddingAmount);
                metadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", paddingAmount);
                metadata.SetQuery("/xmp/PaddingSchema:Padding", paddingAmount);
                // Since you're already adding metadata now, you can go ahead and add metadata up front.
                metadata.SetQuery("/app1/ifd/{uint=897}", "hello there");
                metadata.SetQuery("/app1/ifd/{uint=898}", "this is a test");
                metadata.Title = "This is a title";
                // Create a new frame identical to the one from the original image, except the metadata will have padding.
                // Essentially we want to keep this as close as possible to:
                //     output.Frames = original.Frames;
                output.Frames.Add(BitmapFrame.Create(original.Frames[0], original.Frames[0].Thumbnail, metadata, original.Frames[0].ColorContexts));
            }
            using (Stream outputFile = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
            {
                output.Save(outputFile);
            }
        }
        // For sanity, let's verify that the original and the output contain image bits that are the same.
        using (Stream originalFile = File.Open(originalPath, FileMode.Open, FileAccess.Read))
        {
            BitmapDecoder original = BitmapDecoder.Create(originalFile, createOptions, BitmapCacheOption.None);
            using (Stream savedFile = File.Open(outputPath, FileMode.Open, FileAccess.Read))
            {
                BitmapDecoder output = BitmapDecoder.Create(savedFile, createOptions, BitmapCacheOption.None);
                Compare(original.Frames[0], output.Frames[0], 0, "foo", Console.Out);
            }
        }
        // Let's copy the file before we use the InPlaceBitmapMetadataWriter so that you can verify the metadata changes.
        File.Copy(outputPath, finalPath, true);
        Console.WriteLine();
        // Now let's use the InPlaceBitmapMetadataWriter.
        using (Stream savedFile = File.Open(outputPath, FileMode.Open, FileAccess.ReadWrite))
        {
            ConsoleColor  originalColor          = Console.ForegroundColor;
            BitmapDecoder output                 = BitmapDecoder.Create(savedFile, BitmapCreateOptions.None, BitmapCacheOption.Default);
            InPlaceBitmapMetadataWriter metadata = output.Frames[0].CreateInPlaceBitmapMetadataWriter();
            // Within the InPlaceBitmapMetadataWriter, you can add, update, or remove metadata.
            //metadata.SetQuery("/app1/ifd/{uint=899}", "this is a test of the InPlaceBitmapMetadataWriter");
            //metadata.RemoveQuery("/app1/ifd/{uint=898}");
            //metadata.SetQuery("/app1/ifd/{uint=897}", "Hello there!!");
            Console.WriteLine("#####################");
            Console.WriteLine(metadata.GetQuery(@"/app13/irb/8bimiptc/iptc/City"));
            Console.WriteLine("#####################");
            metadata.SetQuery(@"/app13/irb/8bimiptc/iptc/Headline", "TEst");
            metadata.SetQuery(@"/app13/irb/8bimiptc/iptc/City", "TEst");
            metadata.SetQuery(@"/app13/irb/8bimiptc/iptc/CountryPrimaryLocationName", "TEst");
            metadata.SetQuery(@"/app13/irb/8bimiptc/iptc/ByLine", "TEst");
            metadata.SetQuery(@"/app13/irb/8bimiptc/iptc/CaptionAbstract", "TEst");
            Console.WriteLine("#####################");
            Console.WriteLine(metadata.GetQuery(@"/app13/irb/8bimiptc/iptc/City"));
            Console.WriteLine("#####################");
            if (metadata.TrySave())
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("InPlaceMetadataWriter succeeded!");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("InPlaceMetadataWriter failed!");
            }
            Console.ForegroundColor = originalColor;
        }
        FileInfo originalInfo = new FileInfo(originalPath);
        FileInfo outputInfo   = new FileInfo(outputPath);
        FileInfo finalInfo    = new FileInfo(finalPath);

        Console.WriteLine(outputPath);
        Console.WriteLine();
        Console.WriteLine("Original File Size: \t\t\t{0}", originalInfo.Length);
        Console.WriteLine("After Padding File Size: \t\t{0}", outputInfo.Length);
        Console.WriteLine("After InPlaceBitmapWriter File Size: \t{0}", finalInfo.Length);
    }
Ejemplo n.º 30
0
 protected override void LoadInternal()
 {
     this.Image   = (BitmapSource)BitmapDecoder.Create((Stream) new MemoryStream(this.OriginalBuffer), BitmapCreateOptions.DelayCreation, BitmapCacheOption.Default).Frames[0];
     this.IsDirty = false;
 }