コード例 #1
0
        protected void DeleteImageFromDiskCache(ImageProperties imageProperties, string filePath)
        {
            if (!imageProperties.IsImagePresent)
                return;

            if (File.Exists(filePath))
                File.Delete(filePath);
        }
 void AssignImageProperties(ASPxImage image, ImageProperties imageProperties)
 {
     image.ImageUrl = EmptyImageProperties.GetGlobalEmptyImage(this.Page).Url;
     image.CssClass = imageProperties.SpriteProperties.CssClass;
     image.Width = imageProperties.Width;
     image.Height = imageProperties.Height;
     image.SpriteLeft = imageProperties.SpriteProperties.Left;
     image.SpriteTop = imageProperties.SpriteProperties.Top;
 }
コード例 #3
0
 public static void downloadPhoto(string url, string fileName, string description)
 {
     WebClient wc = new WebClient();
     try
     {
         StreamWriter sw = new StreamWriter(@"errors.txt", true);
         wc.DownloadFile(url, fileName);
         ImageProcessor processor = new ImageProcessor(fileName);
         ImageProperties properties = new ImageProperties();
         properties.Comments = description;
         if (!processor.TryWrite(properties))
             sw.WriteLine("couldn't write properties to image: " + fileName);
         sw.Flush();
         sw.Close();
     }
     catch (WebException e)
     {
         string shortenedFilename = fileName.Substring(0, 252);
         shortenedFilename += ".jpg";
         wc.DownloadFile(url, shortenedFilename);
     }
 }
コード例 #4
0
        public void SetImageProperties_FullFileNamePathContainsSpacesAndHebrew_SetTitleAndDate_ValuesMatch()
        {
            const string subFolder    = "20080328 מרפסת ותפלץ\\20080328";
            string       copyToFolder = Path.Combine(Environment.CurrentDirectory, subFolder);

            if (!Directory.Exists(copyToFolder))
            {
                Directory.CreateDirectory(copyToFolder);
            }

            string imageFileName = Path.Combine(copyToFolder, TestingImagesNames.LeahOnShip1957);

            File.Copy(TestingImagesNames.LeahOnShip1957, imageFileName);

            var          runExifTool       = new RunExifTool(imageFileName, false);
            const string testHadSetTitle   = "דפנה לולו";
            DateTime     expectedDateTaken = new DateTime(1980, 12, 12);

            runExifTool.SetDateAndTitle(testHadSetTitle, expectedDateTaken);
            var imageProperties = new ImageProperties(imageFileName);

            Assert.AreEqual(testHadSetTitle, imageProperties.ExTitle);
            Assert.AreEqual(expectedDateTaken, imageProperties.DateTaken);
        }
コード例 #5
0
        public new GridViewCommandColumnButtonControl CreateCommandButtonControl(GridViewCommandColumnButton button, int visibleIndex, bool postponeClick, bool visibleByDefault)
        {
            if (!visibleByDefault && !button._GetIsVisible())
            {
                return(null);
            }

            var commandButtonSettings = GetCommandButtonSettings(button.ButtonType);
            var buttonType            = GetButtonType(commandButtonSettings, button._Column().ButtonType);

            var text = !string.IsNullOrEmpty(button.Text) ? button.Text : commandButtonSettings.Text;

            if (string.IsNullOrEmpty(text))
            {
                text = Grid.SettingsText.GetCommandButtonText(button.ButtonType);
            }

            var image = new ImageProperties();

            image.CopyFrom(commandButtonSettings.Image);
            image.CopyFrom(button.Image);

            return(CreateCommandButtonControl(button._Column(), button.ButtonType, buttonType, text, image, visibleIndex, postponeClick));
        }
コード例 #6
0
ファイル: GifView.xaml.cs プロジェクト: brookshi/DuDuRiBao
            public async Task <ImageSource> InitializeAsync(IRandomAccessStream streamSource)
            {
                var bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, streamSource);

                var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);

                var frameProperties = new List <FrameProperties>();

                for (var i = 0u; i < bitmapDecoder.FrameCount; i++)
                {
                    var bitmapFrame = await bitmapDecoder.GetFrameAsync(i);

                    frameProperties.Add(await RetrieveFramePropertiesAsync(bitmapFrame));
                }

                _frameProperties = frameProperties;
                _bitmapDecoder   = bitmapDecoder;
                _imageProperties = imageProperties;

                CreateCanvasResources();

                _isInitialized = true;
                return(_canvasImageSource);
            }
コード例 #7
0
        public override async Task GetBitmapImageAsync(FileInfoM fileInfo)
        {
            if (fileInfo == null || fileInfo.StorageFile == null)
            {
                return;
            }

            var workFile = (StorageFile)fileInfo.StorageFile;

            var bitmapImage = new BitmapImage();

            using (IRandomAccessStream fileStream = await workFile.OpenAsync(FileAccessMode.Read))
            {
                // Set the image source to the selected bitmap
                ImageProperties property = await workFile.Properties.GetImagePropertiesAsync();

                bitmapImage.DecodePixelHeight = (int)property.Height;
                bitmapImage.DecodePixelWidth  = (int)property.Width;

                await bitmapImage.SetSourceAsync(fileStream);

                fileInfo.Data = bitmapImage;
            }
        }
コード例 #8
0
        /// <summary>
        /// Clear all of the state that is stored in memory and in the UI.
        /// </summary>
        private async void ResetSessionState()
        {
            m_imageProperties = null;
            m_fileToken       = null;

            CloseButton.IsEnabled = false;
            ApplyButton.IsEnabled = false;

            StorageFile placeholderImage = await Package.Current.InstalledLocation.GetFileAsync("Assets\\placeholder-sdk.png");

            BitmapImage bitmapImage = new BitmapImage();

            using (IRandomAccessStream stream = await placeholderImage.OpenAsync(FileAccessMode.Read))
            {
                await bitmapImage.SetSourceAsync(stream);
            }
            Image1.Source = bitmapImage;
            AutomationProperties.SetName(Image1, "A placeholder image");

            TitleTextbox.Text         = "";
            KeywordsTextbox.Text      = "";
            DateTakenTextblock.Text   = "";
            MakeTextblock.Text        = "";
            ModelTextblock.Text       = "";
            OrientationTextblock.Text = "";
            LatDegTextbox.Text        = "";
            LatMinTextbox.Text        = "";
            LatSecTextbox.Text        = "";
            LatRefTextbox.Text        = "";
            LongDegTextbox.Text       = "";
            LongMinTextbox.Text       = "";
            LongSecTextbox.Text       = "";
            LongRefTextbox.Text       = "";
            ExposureTextblock.Text    = "";
            FNumberTextblock.Text     = "";
        }
コード例 #9
0
 public static uint GetHeight(this ImageProperties props)
 {
     return(props.Height);
     //return props.Orientation == PhotoOrientation.Rotate180 ? props.Height : props.Width;
 }
コード例 #10
0
        private static void GetImageProperties(ICollection <StorageFileProperty> results, ImageProperties props)
        {
            var title     = props.Title;
            var dateTaken = props.DateTaken.ToString("G");

            var manufacturer = props.CameraManufacturer;
            var model        = props.CameraModel;

            var height = props.Height;
            var width  = props.Width;

            var latitude  = props.Latitude.ToString();
            var longitude = props.Longitude.ToString();

            if (!title.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "Title") == null)
                {
                    results.Add(new StorageFileProperty("Title", title));
                }
            }

            if (!dateTaken.IsEmpty())
            {
                if (dateTaken.IsValidDate())
                {
                    if (results.FirstOrDefault(x => x.Name == "Date Taken") == null)
                    {
                        results.Add(new StorageFileProperty("Date Taken", dateTaken));
                    }
                }
            }

            if (!manufacturer.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "Manufacturer") == null)
                {
                    results.Add(new StorageFileProperty("Manufacturer", manufacturer));
                }
            }

            if (!model.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "Model") == null)
                {
                    results.Add(new StorageFileProperty("Model", model));
                }
            }

            if (height != 0 || width != 0)
            {
                if (results.FirstOrDefault(x => x.Name == "Height") == null)
                {
                    results.Add(new StorageFileProperty("Height", height));
                }

                if (results.FirstOrDefault(x => x.Name == "Width") == null)
                {
                    results.Add(new StorageFileProperty("Width", width));
                }
            }


            if (!latitude.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "GPS latitude") == null)
                {
                    results.Add(new StorageFileProperty("GPS latitude", latitude));
                }
            }

            if (!longitude.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "GPS longitude") == null)
                {
                    results.Add(new StorageFileProperty("GPS longitude", longitude));
                }
            }
        }
コード例 #11
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Tot.Text = "";
            Vot.Text = "";
            Button button = sender as Button;

            button.IsEnabled = false;
            StorageFolder vere = imagefolder;
            StorageFolder hore = imagefolder;

            if (imgfiles == null)
            {
                return;
            }
            //Tot.Text = imagefile.Path;
            Tot.Text = imagefile.FileType;
            //若存在则获取,不存在则新建
            if (null == await imagefolder.TryGetItemAsync("Hor"))
            {
                hore = await imagefolder.CreateFolderAsync("Hor");
            }
            hore = await imagefolder.GetFolderAsync("Hor");

            if (await imagefolder.TryGetItemAsync("Ver") == null)
            {
                vere = await imagefolder.CreateFolderAsync("Ver");
            }
            vere = await imagefolder.GetFolderAsync("Ver");

            int    a = 0;
            int    b = 0;
            float  t = 0;
            float  p = 0;
            double c = 0;

            Tot.Text = a.ToString();
            Vot.Text = b.ToString();
            //Windows.Storage.StorageFolder imgfld = await imagefile.GetParentAsync();
            StorageApplicationPermissions.FutureAccessList.Add(imagefolder);
            IReadOnlyList <StorageFile> filelist = await imagefolder.GetFilesAsync();

            foreach (StorageFile file  in filelist)
            {
                progrb.Visibility = Visibility.Visible;
                p = filelist.Count;
                if (file.FileType == ".jpg" || file.FileType == ".png" || file.FileType == ".bmp")
                {
                    var varfil = await file.GetBasicPropertiesAsync();

                    if (varfil.Size == 0)
                    {
                        continue;
                    }
                    filename    = file.Name;
                    filename    = varfil.Size.ToString();
                    errtag.Text = filename;
                    ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();

                    if (imageProperties.Width >= imageProperties.Height)
                    {
                        if (await hore.TryGetItemAsync(file.Name) != null)
                        {
                            continue;
                        }
                        inputstream = await file.OpenReadAsync();

                        await horbitmap.SetSourceAsync(inputstream);

                        HorImagePlace.Source = horbitmap;
                        await file.CopyAsync(hore);

                        a++;
                    }
                    else
                    {
                        if (await vere.TryGetItemAsync(file.Name) != null)
                        {
                            continue;
                        }
                        inputstream = await file.OpenReadAsync();

                        await verbitmap.SetSourceAsync(inputstream);

                        VerImagePlace.Visibility = Visibility.Visible;
                        VerImagePlace.Source     = verbitmap;
                        await file.CopyAsync(vere);

                        b++;
                    }
                    Tot.Text = a.ToString();
                    Vot.Text = b.ToString();
                }
                Tot.Text        += " Hor Pictures Copyed";
                Vot.Text        += " Ver Pictures Copyed";
                button.IsEnabled = true;
                btnOpn.IsEnabled = true;
                t++;
                c            = t / p;
                progrb.Value = c * 100;
            }
            StorageApplicationPermissions.FutureAccessList.Clear();
        }
コード例 #12
0
ファイル: Picture.cs プロジェクト: mevellea/GlobeTrotter
        public async Task <Boolean> UpdateMetadata(GpsLocation _position)
        {
            Position        = _position;
            PositionPresent = true;

            GpsLocationDec _locationDec = new GpsLocationDec(_position);
            StorageFile    _file;

            try
            {
                _file = await StorageFile.GetFileFromPathAsync(GetPath());
            }
            catch (FileNotFoundException)
            {
                PositionPresent    = false;
                Position.Latitude  = 0;
                Position.Longitude = 0;
                Date = _fileHandler.DateCreated.DateTime;
                return(false);
            }

            ImageProperties m_imageProperties = await _file.Properties.GetImagePropertiesAsync();

            PropertySet propertiesToSave = new PropertySet();

            // The Latitude and Longitude properties are read-only. Instead,
            // write to System.GPS.LatitudeNumerator, LatitudeDenominator, etc.
            // These are length 3 arrays of integers. For simplicity, the
            // seconds data is rounded to the nearest 10000th.
            uint[] latitudeNumerator =
            {
                (uint)_locationDec.Latitude.Deg,
                (uint)_locationDec.Latitude.Min,
                (uint)(_locationDec.Latitude.Sec * 10000)
            };

            uint[] longitudeNumerator =
            {
                (uint)_locationDec.Longitude.Deg,
                (uint)_locationDec.Longitude.Min,
                (uint)(_locationDec.Longitude.Sec * 10000)
            };

            // LatitudeDenominator and LongitudeDenominator share the same values.
            uint[] denominator =
            {
                1,
                1,
                10000
            };

            propertiesToSave.Add("System.GPS.LatitudeRef", _locationDec.Latitude.Ref);
            propertiesToSave.Add("System.GPS.LongitudeRef", _locationDec.Longitude.Ref);

            propertiesToSave.Add("System.GPS.LatitudeNumerator", latitudeNumerator);
            propertiesToSave.Add("System.GPS.LatitudeDenominator", denominator);
            propertiesToSave.Add("System.GPS.LongitudeNumerator", longitudeNumerator);
            propertiesToSave.Add("System.GPS.LongitudeDenominator", denominator);

            try
            {
                await m_imageProperties.SavePropertiesAsync(propertiesToSave);
            }
            catch (Exception err)
            {
                Debug.WriteLine(err.Message);
                return(false);
            }
            return(true);
        }
コード例 #13
0
            public async Task<ImageSource> InitializeAsync(IRandomAccessStream streamSource)
            {
                var bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, streamSource);
                var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);

                _frameProperties = new FrameProperties?[bitmapDecoder.FrameCount];
                _bitmapDecoder = bitmapDecoder;
                _imageProperties = imageProperties;

                CreateCanvasResources();

                _isInitialized = true;
                return _canvasImageSource;
            }
コード例 #14
0
 private static void GetImageProperties(XElement itemElement, out string cacheKey, out ImageProperties imageProperties)
 {
     imageProperties = new ImageProperties();
     imageProperties.IsImagePresent = Convert.ToBoolean(itemElement.Attribute("isImagePresent").Value);
     imageProperties.Format         = (DynamicImageFormat)Enum.Parse(typeof(DynamicImageFormat), itemElement.Attribute("format").Value);
     if (itemElement.Attribute("width") != null)
     {
         imageProperties.Width = Convert.ToInt32(itemElement.Attribute("width").Value);
     }
     if (itemElement.Attribute("height") != null)
     {
         imageProperties.Height = Convert.ToInt32(itemElement.Attribute("height").Value);
     }
     imageProperties.ColourDepth = Convert.ToInt32(itemElement.Attribute("colourDepth").Value);
     if (itemElement.Attribute("jpegCompressionLevel") != null)
     {
         imageProperties.JpegCompressionLevel = Convert.ToInt32(itemElement.Attribute("jpegCompressionLevel").Value);
     }
     cacheKey = itemElement.Attribute("id").Value;
 }
コード例 #15
0
        private async void loadImageAsync()
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            StorageFile imageFile = await picker.PickSingleFileAsync();

            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile   storageFile   = null;

            sourceImage = null;

            if (imageFile != null)
            {
                ImageProperties properties = await imageFile.Properties.GetImagePropertiesAsync();

                height = (double)properties.Height;
                width  = (double)properties.Width;
                double ratio;

                if (height < width)
                {
                    ratio = canvasSize / width;
                }
                else
                {
                    ratio = canvasSize / height;
                }
                newHeight = height * ratio;
                newWidth  = width * ratio;
                xOffset   = (canvasSize - newWidth) / 2;
                yOffset   = (canvasSize - newHeight) / 2;

                try
                {
                    storageFile = await storageFolder.GetFileAsync(imageFile.Name);
                }
                catch (Exception e) { }
                if (storageFile == null)
                {
                    copiedFile = await imageFile.CopyAsync(storageFolder);
                }
                else
                {
                    copiedFile = storageFile;
                }
                sourceImage = await StorageFileToWriteableBitmap(imageFile);

                imageFilePath = copiedFile.Path;
                imageFilePath = imageFilePath.Replace("\\", "/");
                ImageBitmap   = sourceImage;

                // set any previous background path to null
                BackgroundImagePath  = null;
                group.backgroundPath = null;

                // set the GroupContent to hold this image
                ImageContainer ic = new ImageContainer
                {
                    xOffset   = xOffset,
                    yOffset   = yOffset,
                    newWidth  = newWidth,
                    newHeight = newHeight,
                    imagePath = imageFilePath,
                    image     = ImageBitmap,
                };
                group.imageContainer = ic;
            }
        }
コード例 #16
0
        static Rect PDF_PORTION_RECT = new Rect(100, 100, 300, 400); //portion of a page

        public static async Task <Images> GetFileListWithBitmapImages(List <string> fileTypes, bool loadFilesFromLocalFolder = false, List <string> fileListToLoad = null)
        {
            Images imagecollection = new Images();
            //ObservableCollection<List<ImageSource>> ListImageDisplay = new ObservableCollection<List<ImageSource>>();

            IReadOnlyList <StorageFile> files = null;

            if (!loadFilesFromLocalFolder) //Open file picker.
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.List;
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                foreach (string fileType in fileTypes)
                {
                    openPicker.FileTypeFilter.Add(fileType);
                }
                files = await openPicker.PickMultipleFilesAsync();
            }
            else     //Load files from local folder
            {
                if (fileListToLoad != null)
                {
                    foreach (string filePath in fileListToLoad)
                    {
                        var uri  = new System.Uri(filePath);// ("ms-appx:///images/logo.png");
                        var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

                        List <StorageFile> filesLocal = new List <StorageFile>();
                        filesLocal.Add(file);
                        files = filesLocal;
                    }
                }
            }
            if (files != null && files.Count > 0)
            {
                StringBuilder output = new StringBuilder("Picked files:\n");
                // Application now has read/write access to the picked file(s)
                foreach (StorageFile file in files)
                {
                    output.Append(file.Name + "\n");
                    bool             fastThumbnail    = false;
                    ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail;
                    if (fastThumbnail)
                    {
                        thumbnailOptions |= ThumbnailOptions.ReturnOnlyIfCached;
                    }

                    const uint size = 500;
                    using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, size))
                    {
                        if (thumbnail != null)
                        {
                            List <ImageSource> bitmapImageList = null;

                            ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync();

                            if (file.FileType.ToLower() == ".pdf")
                            {
                                DocumentProperties docProp = await file.Properties.GetDocumentPropertiesAsync();

                                Images image = await LoadPDFBitmapImage(file, RENDEROPTIONS.NORMAL);

                                imagecollection.ListImageDisplay.Add(image.ListImageDisplay[0]);
                                imagecollection.ListWriteImages.Add(image.ListWriteImages[0]);
                                //image.ListWriteImages.Add()
                            }
                            else
                            {
                                bitmapImageList = new List <ImageSource>();
                                BitmapImage bitmapImage = new BitmapImage();
                                bitmapImage.SetSource(thumbnail);
                                bitmapImageList.Add(bitmapImage);

                                using (var imgStream = await file.OpenAsync(FileAccessMode.Read))
                                {
                                    List <WriteableBitmap> lstwriteable = new List <WriteableBitmap>();
                                    WriteableBitmap        bitmap       = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height);
                                    bitmap.SetSource(imgStream);
                                    lstwriteable.Add(bitmap);
                                    imagecollection.ListWriteImages.Add(lstwriteable);
                                }

                                imagecollection.ListImageDisplay.Add(bitmapImageList);
                            }


                            //ListImageDisplay.Add(bitmapImageList);
                        }
                    }
                }
            }
            else
            {
            }
            return(imagecollection);
        }
コード例 #17
0
        public async void getPhotos(JObject options, IPromise promise)
        {
            try
            {
                if (options["first"] == null)
                {
                    promise.Reject(new ArgumentNullException("The option [first] must be defined."));
                    return;
                }

                if ((int)options["first"] < 1)
                {
                    promise.Reject(new ArgumentException("The option [first] is not valid."));
                    return;
                }

                var limit = (uint)(options["first"]);

                // TODO:
                // after
                // mimeTypes, groupName

                if (options["groupTypes"] != null)
                {
                    promise.Reject(new ArgumentException("The option [groupTypes] is not supported on UWP"));
                    return;
                }

                QueryOptions queryOption;

                switch ((string)(options["assetType"]))
                {
                case "All":
                    queryOption = new QueryOptions(CommonFileQuery.OrderByDate, SupportedVideoFileTypes
                                                   .Concat(SupportedImageFileTypes)
                                                   .ToList()
                                                   );
                    break;

                case "Videos":
                    queryOption = new QueryOptions(CommonFileQuery.OrderByDate, SupportedVideoFileTypes);
                    break;

                case "Photos":
                default:
                    queryOption = new QueryOptions(CommonFileQuery.OrderByDate, SupportedImageFileTypes);
                    break;
                }

                StorageFolder picturesFolder = KnownFolders.CameraRoll;
                queryOption.FolderDepth = FolderDepth.Deep;

                IReadOnlyList <StorageFile> sortedItems = await picturesFolder
                                                          .CreateFileQueryWithOptions(queryOption)
                                                          .GetFilesAsync(0, limit);

                var result    = new JObject();
                var edges     = new JArray();
                var pageinfo  = new JObject();
                var endcursor = "";

                foreach (StorageFile file in sortedItems)
                {
                    var node     = new JObject();
                    var nodeObj  = new JObject();
                    var image    = new JObject();
                    var location = new JObject();
                    var uri      = new Uri(file.Path);

                    ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();

                    // Put ImageInfo
                    image.Add("uri", uri);
                    image.Add("width", imageProperties.Width);
                    image.Add("height", imageProperties.Height);

                    // Put BasicNodeInfo
                    node.Add("image", image);
                    node.Add("type", file.ContentType);
                    node.Add("timestamp", imageProperties.DateTaken.ToUnixTimeSeconds());
                    node.Add("group_name", file.DisplayName);

                    // Put LocationInfo
                    if (imageProperties.Latitude != null && imageProperties.Longitude != null)
                    {
                        location.Add("latitude", imageProperties.Latitude);
                        location.Add("longitude", imageProperties.Longitude);
                        node.Add("location", location);
                    }

                    nodeObj.Add("node", node);
                    edges.Add(nodeObj);

                    endcursor = imageProperties.DateTaken.ToString();
                }

                // Put PageInfo
                pageinfo.Add("has_next_page", limit < sortedItems.Count);
                pageinfo.Add("end_cursor", endcursor);

                // Put Edges
                result.Add("edges", edges);
                result.Add("page_info", pageinfo);

                promise.Resolve(result);
            }
            catch (Exception ex)
            {
                promise.Reject(new InvalidOperationException("CameraRoll.getPhotos()", ex));
            }
        }
コード例 #18
0
        public static Image ApplyImageProperties(byte[] blobContent, ImageProperties properties)
        {
            Bitmap image = null;

            try {
                using (var ms = new MemoryStream(blobContent)) {
                    image = (Bitmap)System.Drawing.Image.FromStream(ms, false, false);
                    image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb);
                    if (properties.Crop != null)
                    {
                        AForge.Imaging.Filters.Crop filter = new AForge.Imaging.Filters.Crop(new Rectangle(properties.Crop.XOffset, properties.Crop.YOffset, properties.Crop.CropWidth, properties.Crop.CropHeight));
                        image = filter.Apply(image);
                    }
                    if (properties.ImageWidth != properties.OriginalWidth || properties.ImageHeight != properties.OriginalHeight)
                    {
                        var filter = new ResizeBicubic(properties.ImageWidth, properties.ImageHeight);
                        image = filter.Apply(image);
                    }
                    if (properties.Colors != null)
                    {
                        if (properties.Colors.TransparentColor != null)
                        {
                            image.MakeTransparent(ColorTranslator.FromHtml("#" + properties.Colors.TransparentColor));
                        }
                        var brightness = properties.Colors.Brightness;
                        var bfilter    = new BrightnessCorrection(brightness);
                        bfilter.ApplyInPlace(image);
                        var contrast = properties.Colors.Contrast;
                        var cfilter  = new ContrastCorrection(contrast);
                        cfilter.ApplyInPlace(image);
                        if (properties.Colors.Hue != 0)
                        {
                            var         hue    = properties.Colors.Hue;
                            HueModifier filter = new HueModifier(hue);
                            filter.ApplyInPlace(image);
                        }
                        var saturation = properties.Colors.Saturation;
                        var sfilter    = new SaturationCorrection(saturation * 0.01f);
                        sfilter.ApplyInPlace(image);
                    }
                    # region Effects
                    if (!String.IsNullOrEmpty(properties.Effects))
                    {
                        var effects = properties.Effects.Split(';');
                        foreach (var item in effects)
                        {
                            switch (item)
                            {
                            case "Grayscale":
                                var g = new Grayscale(0.2125, 0.7154, 0.0721);
                                image = g.Apply(image);
                                break;

                            case "Sepia":
                                var s = new Sepia();
                                image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb);
                                s.ApplyInPlace(image);
                                break;

                            case "Rotate Channels":
                                image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb);
                                var r = new RotateChannels();
                                r.ApplyInPlace(image);
                                break;

                            case "Invert":
                                var i = new Invert();
                                i.ApplyInPlace(image);
                                break;

                            case "Blur":
                                var b = new Blur();
                                b.ApplyInPlace(image);
                                break;

                            case "Gaussian Blur":
                                var gb = new GaussianBlur(4, 11);
                                gb.ApplyInPlace(image);
                                break;

                            case "Convolution":
                                int[,] kernel = { { -2, -1, 0 }, { -1, 1, 1 }, { 0, 1, 2 } };
                                var c = new Convolution(kernel);
                                c.ApplyInPlace(image);
                                break;

                            case "Edges":
                                var e = new Edges();
                                e.ApplyInPlace(image);
                                break;
                            }
                        }
                    }
                    # endregion
                }
            } catch (Exception) {
コード例 #19
0
        public async Task<ImagePackage> InitializeAsync(CoreDispatcher dispatcher, Image image, Uri uriSource,
            IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource)
        {
   
            var bitmapDecoder = ImagingCache.Get<BitmapDecoder>(uriSource);
            if (bitmapDecoder == null)
            {
                var inMemoryStream = new InMemoryRandomAccessStream();
                var copyAction = RandomAccessStream.CopyAndCloseAsync(
                               streamSource.GetInputStreamAt(0L),
                               inMemoryStream.GetOutputStreamAt(0L));
                await copyAction.AsTask(cancellationTokenSource.Token);
                bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, inMemoryStream);
                ImagingCache.Add(uriSource, bitmapDecoder);
            }

            var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);
            var frameProperties = new List<FrameProperties>();

            for (var i = 0u; i < bitmapDecoder.FrameCount; i++)
            {
                var bitmapFrame = await bitmapDecoder.GetFrameAsync(i).AsTask(cancellationTokenSource.Token).ConfigureAwait(false); ;
                frameProperties.Add(await RetrieveFramePropertiesAsync(i, bitmapFrame));
            }

            _frameProperties = frameProperties;
            _bitmapDecoder = bitmapDecoder;
            _imageProperties = imageProperties;
            _dispatcher = dispatcher;

            await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 CreateCanvasResources();
                 var uri = image.Tag as Uri;
                 if (uri == uriSource)
                 {
                     image.Source = _canvasImageSource;
                 }
             });

            _isInitialized = true;
            return new ImagePackage(this, _canvasImageSource, _imageProperties.PixelWidth, _imageProperties.PixelHeight); ;
        }
コード例 #20
0
 protected void DeleteImageFromDiskCache(string cacheKey, ImageProperties imageProperties, HttpContext httpContext)
 {
     string filePath = httpContext.Server.MapPath(GetDiskCacheFilePath(httpContext, cacheKey, imageProperties.FileExtension));
     DeleteImageFromDiskCache(imageProperties, filePath);
 }
コード例 #21
0
 private static string GetUrl(string cacheKey, ImageProperties imageProperties)
 {
     const string path = "~/Assets/Images/DynamicImages/";
     string fileName = string.Format("{0}.{1}", cacheKey, imageProperties.FileExtension);
     return VirtualPathUtility.ToAbsolute(path) + fileName;
 }
コード例 #22
0
        /// <summary>
        /// Updates the band wallpaper
        /// </summary>
        /// <param name="file"></param>
        public async Task <bool> UpdateBandWallpaper(StorageFile file)
        {
            try
            {
                IBandInfo pairedBand = await GetPairedBand();

                if (pairedBand == null)
                {
                    // We don't have a band.
                    return(true);
                }

                // Try to connect to the band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBand))
                {
                    WriteableBitmap bitmap       = null;
                    BandImage       newBandImage = null;
                    //byte[] pixelArray = null;
                    using (AutoResetEvent are = new AutoResetEvent(false))
                    {
                        // Get the bitmap on the UI thread.
                        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
                        {
                            try
                            {
                                // Create a bitmap for the Me Tile image.
                                // The image must be 310x102 pixels for Microsoft Band 1
                                // and 310x102 or 310x128 pixels for Microsoft Band 2.
                                ImageProperties properties = await file.Properties.GetImagePropertiesAsync();
                                bitmap = new WriteableBitmap((int)properties.Width, (int)properties.Height);
                                bitmap.SetSource((await file.OpenReadAsync()));
                                newBandImage = bitmap.ToBandImage();
                                //pixelArray = bitmap.ToByteArray();
                            }
                            catch (Exception) { }
                            are.Set();
                        });

                        are.WaitOne(10000);
                    }

                    // Check if we failed
                    if (bitmap == null || newBandImage == null)
                    {
                        throw new Exception("Failed to make new bitmap image.");
                    }

                    // Try to set the image.
                    await bandClient.PersonalizationManager.SetMeTileImageAsync(newBandImage);

                    //// Compute the average color
                    //Color averageColor = new Color();
                    //uint bAvg = 0;
                    //uint rAvg = 0;
                    //uint gAvg = 0;
                    //uint count = 0;
                    //for (int i = 0; i < pixelArray.Length; i += 4)
                    //{
                    //    rAvg += pixelArray[i + 1];
                    //    gAvg += pixelArray[i + 2];
                    //    bAvg += pixelArray[i + 3];
                    //    count++;
                    //}
                    //averageColor.R = (byte)(rAvg / count);
                    //averageColor.B = (byte)(bAvg / count);
                    //averageColor.G = (byte)(gAvg / count);

                    //BandTheme theme = new BandTheme() { Base = averageColor.ToBandColor() };
                    //await bandClient.PersonalizationManager.SetThemeAsync(theme);
                }
            }
            catch (Exception e)
            {
                m_baconMan.MessageMan.DebugDia("failed to set band wallpaper", e);
                return(false);
            }
            return(true);
        }
コード例 #23
0
        public async Task<ImageSource> InitializeAsync(CoreDispatcher dispatcher,
            IRandomAccessStream streamSource, CancellationTokenSource cancellationTokenSource)
        {

            var inMemoryStream = new InMemoryRandomAccessStream();
            var copyAction = RandomAccessStream.CopyAndCloseAsync(
                           streamSource.GetInputStreamAt(0L),
                           inMemoryStream.GetOutputStreamAt(0L));
            await copyAction.AsTask(cancellationTokenSource.Token);

            var bitmapDecoder = await BitmapDecoder.
                CreateAsync(BitmapDecoder.GifDecoderId, inMemoryStream).AsTask(cancellationTokenSource.Token).ConfigureAwait(false);
            var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);
            var frameProperties = new List<FrameProperties>();
            for (var i = 0u; i < bitmapDecoder.FrameCount; i++)
            {
                var bitmapFrame = await bitmapDecoder.GetFrameAsync(i).AsTask(cancellationTokenSource.Token).ConfigureAwait(false); ;
                frameProperties.Add(await RetrieveFramePropertiesAsync(i, bitmapFrame));
            }

            _frameProperties = frameProperties;
            _bitmapDecoder = bitmapDecoder;
            _imageProperties = imageProperties;
            _dispatcher = dispatcher;

            await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 CreateCanvasResources();
             });

            _isInitialized = true;
            return _canvasImageSource;
        }
コード例 #24
0
 protected new GridViewCommandColumnButtonControl CreateCommandButtonControl(GridViewCommandColumn column, ColumnCommandButtonType commandItemType, GridViewCommandButtonType buttonType, string text, ImageProperties image, int visibleIndex, bool postponeClick)
 {
     if (!CanCreateCommandButton(commandItemType)) return null;
     
     var isEditingRow = DataProxy.IsNewRowEditing && visibleIndex == -2147483647 || visibleIndex >= 0 && DataProxy.IsRowEditing(visibleIndex);
     
     var eventArgs = new ASPxGridViewCommandButtonEventArgs(column, commandItemType, text, image, visibleIndex, isEditingRow, buttonType);
     
     Grid.RaiseCommandButtonInitialize_Internal(eventArgs);
     
     return eventArgs.Visible ? new GridViewCommandColumnButtonControl(eventArgs, Grid, GetCommandButtonClickHandlerArgs(commandItemType), postponeClick) : null;
 }
コード例 #25
0
 public OutputDescriptor(ImageProperties imageProperties, ImageOutputProperties imageOutputProperties)
 {
     this.Path          = imageOutputProperties.GetFullPath(imageProperties.FileName);
     this.ImageFormat   = imageOutputProperties.ImageFormat;
     this.OverwriteFile = imageOutputProperties.OverwriteFile;
 }
コード例 #26
0
        public new GridViewCommandColumnButtonControl CreateCommandButtonControl(GridViewCommandColumnButton button, int visibleIndex, bool postponeClick, bool visibleByDefault)
        {
            if (!visibleByDefault && !button._GetIsVisible()) return null;

            var commandButtonSettings = GetCommandButtonSettings(button.ButtonType);
            var buttonType = GetButtonType(commandButtonSettings, button._Column().ButtonType);
            
            var text = !string.IsNullOrEmpty(button.Text) ? button.Text : commandButtonSettings.Text;
            
            if (string.IsNullOrEmpty(text))
                text = Grid.SettingsText.GetCommandButtonText(button.ButtonType);
            
            var image = new ImageProperties();
            image.CopyFrom(commandButtonSettings.Image);
            image.CopyFrom(button.Image);

            return CreateCommandButtonControl(button._Column(), button.ButtonType, buttonType, text, image, visibleIndex, postponeClick);
        }
コード例 #27
0
            public async Task<ImageSource> InitializeAsync(IRandomAccessStream streamSource)
            {
                var bitmapDecoder = await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, streamSource);
                var imageProperties = await RetrieveImagePropertiesAsync(bitmapDecoder);
                var frameProperties = new List<FrameProperties>();

                for (var i = 0u; i < bitmapDecoder.FrameCount; i++)
                {
                    var bitmapFrame = await bitmapDecoder.GetFrameAsync(i);
                    frameProperties.Add(await RetrieveFramePropertiesAsync(bitmapFrame));
                }

                _frameProperties = frameProperties;
                _bitmapDecoder = bitmapDecoder;
                _imageProperties = imageProperties;

                CreateCanvasResources();

                _isInitialized = true;
                return _canvasImageSource;
            }
コード例 #28
0
 /// <summary>
 /// Partially modify an Image You can use update attributes of a resource
 /// </summary>
 /// <param name="imageId"></param> 
 /// <param name="image">Modified Image</param> 
 /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> 
 /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param> 
 /// <returns>Image</returns>
 public Image PartialUpdate(string imageId, ImageProperties image, bool? parameter = null, int? depth = null)
 {
     ApiResponse<Image> response = PartialUpdateWithHttpInfo(imageId, image, parameter, depth);
     return response.Data;
 }
コード例 #29
0
        static void GeneratePhotoGrid()
        {
            string portfolioDir = @"C:\Users\tgrue\OneDrive\Pictures\Portfolio";

            List <ImageProperties> images = new List <ImageProperties>();

            //get portfolio images
            string[] portfolioFiles = Directory.GetFiles(portfolioDir);
            int      index          = 1;

            foreach (string iName in portfolioFiles)
            {
                JpegEncoder encoder = new JpegEncoder();
                encoder.Quality = 65;
                //generate thumbnail
                using (Image image = Image.Load(portfolioFiles[index - 1]))
                {
                    int width  = 700;
                    int height = 0;
                    image.Mutate(x => x.Resize(width, height));

                    image.Save(wwwBaseDir + @"\Images\Portfolio\Thumbnails\portfolio-" + index + ".jpg", encoder);
                }
                //generate larger image
                using (Image image = Image.Load(portfolioFiles[index - 1]))
                {
                    int width  = 1500;
                    int height = 0;

                    image.Mutate(x => x.Resize(width, height));
                    string name = "portfolio-" + index + ".jpg";
                    image.Save(wwwBaseDir + @"\Images\Portfolio\" + name, encoder);
                    ImageProperties ip = new ImageProperties();
                    ip.width  = width;
                    ip.height = image.Height;
                    ip.index  = index;
                    ip.name   = name;
                    images.Add(ip);
                }
                index++;
            }

            try

            {
                string content;

                using (var sr = new StreamReader(wwwBaseDir + @"\index.html"))
                {
                    content = sr.ReadToEnd();
                }
                using (StreamWriter outputFile = new StreamWriter(wwwBaseDir + @"\index.html"))
                {
                    string[] contentArr = content.Split("\r\n");

                    foreach (string s in contentArr)
                    {
                        outputFile.WriteLine(s);
                        if (s == "<!-- Photo Grid -->")//start generation process
                        {
                            int count = 0;
                            int half  = images.Count / 2;
                            outputFile.WriteLine("<div class=\"w3-half\">");
                            foreach (ImageProperties ip in images)
                            {
                                if (count == half)
                                {
                                    outputFile.WriteLine("</div>");
                                    outputFile.WriteLine("<div class=\"w3-half\">");
                                }
                                outputFile.WriteLine("<a href=\"Images\\Portfolio\\" + ip.name + "\" itemprop=\"contentUrl\" data-size=\"" + ip.width + "x" + ip.height + "\">");
                                outputFile.WriteLine(" <img src=\"Images\\Portfolio\\Thumbnails\\" + ip.name + "\" itemprop=\"thumbnail\" alt=\"Image description\" style = \"width:100% \"/>");
                                outputFile.WriteLine("</a>");
                                ++count;
                            }
                            outputFile.WriteLine("</div>");
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
コード例 #30
0
        /// <summary>
        /// Partially modify an Image You can use update attributes of a resource
        /// </summary>
        /// <param name="imageId"></param>
        /// <param name="image">Modified Image</param>
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param>
        /// <returns>Task of Image</returns>
        public async System.Threading.Tasks.Task<Image> PartialUpdateAsync(string imageId, ImageProperties image, bool? parameter = null, int? depth = null)
        {
            ApiResponse<Image> response = await PartialUpdateAsyncWithHttpInfo(imageId, image, parameter, depth);
            return response.Data;

        }
コード例 #31
0
        public async Task <ActionResult <ReturnSignUserResponse> > GoogleSignInAsync(
            [FromBody] GoogleTokenRequest model,
            [FromServices] IGoogleAuth service,
            [FromServices] IUserDirectoryBlobProvider blobProvider,


            [FromServices] TelemetryClient logClient,
            [FromServices] IHttpClientFactory clientFactory,
            CancellationToken cancellationToken)
        {
            var result = await service.LogInAsync(model.Token, cancellationToken);

            _logger.Info($"received google user {result}");
            if (result == null)
            {
                logClient.TrackTrace("result from google is null");
                ModelState.AddModelError("Google", _localizer["GoogleNoResponse"]);
                return(BadRequest(ModelState));
            }

            var result2 = await _signInManager.ExternalLoginSignInAsync("Google", result.Id, true, true);

            if (result2.Succeeded)
            {
                return(ReturnSignUserResponse.SignIn());
                //return new ReturnSignUserResponse(false);
            }

            if (result2.IsLockedOut)
            {
                logClient.TrackTrace("user is locked out");
                ModelState.AddModelError("Google", _loginLocalizer["LockOut"]);
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByEmailAsync(result.Email);

            if (result2.IsNotAllowed && user != null && await _userManager.IsLockedOutAsync(user))
            {
                ModelState.AddModelError("Google", _loginLocalizer["LockOut"]);
                return(BadRequest(ModelState));
            }
            if (user == null)
            {
                var country = await _countryProvider.GetUserCountryAsync(cancellationToken);

                user = new User(result.Email,
                                result.FirstName, result.LastName,
                                result.Language, country)
                {
                    EmailConfirmed = true
                };


                var result3 = await _userManager.CreateAsync(user);

                if (result3.Succeeded)
                {
                    if (!string.IsNullOrEmpty(result.Picture))
                    {
                        using var httpClient = clientFactory.CreateClient();
                        var message = await httpClient.GetAsync(result.Picture, cancellationToken);

                        await using var sr = await message.Content.ReadAsStreamAsync();

                        var mimeType = message.Content.Headers.ContentType;
                        try
                        {
                            var uri = await blobProvider.UploadImageAsync(user.Id, result.Picture, sr,
                                                                          mimeType.ToString(), cancellationToken);

                            var imageProperties = new ImageProperties(uri, ImageProperties.BlurEffect.None);
                            var url             = Url.ImageUrl(imageProperties);
                            var fileName        = uri.AbsolutePath.Split('/').LastOrDefault();
                            user.UpdateUserImage(url, fileName);
                        }
                        catch (ArgumentException e)
                        {
                            logClient.TrackException(e, new Dictionary <string, string>()
                            {
                                ["FromGoogle"] = result.Picture
                            });
                        }
                    }
                    await _userManager.AddLoginAsync(user, new UserLoginInfo("Google", result.Id, result.Name));

                    return(await MakeDecisionAsync(user, true, null, cancellationToken));
                }
                logClient.TrackTrace($"failed to register {string.Join(", ", result3.Errors)}");

                ModelState.AddModelError("Google", _localizer["GoogleUserRegisteredWithEmail"]);
                return(BadRequest(ModelState));
            }
            if (!user.EmailConfirmed)
            {
                user.EmailConfirmed = true;
                await _userManager.UpdateAsync(user);
            }

            await _userManager.AddLoginAsync(user, new UserLoginInfo("Google", result.Id, result.Name));

            return(await MakeDecisionAsync(user, true, null, cancellationToken));
        }
コード例 #32
0
 private extern static int DD_Draw(IntPtr handle, IntPtr pBuffer, ImageProperties properties);
コード例 #33
0
        public async void SaveImage(StorageFile linkedFile, StorageFile resizedImage, Size newSize)
        {
            var imageStream = await linkedFile.OpenReadAsync();

            //Resize and Save

            //BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);

            var fileEncoder = BitmapEncoder.JpegEncoderId;

            switch (linkedFile.Path.Substring(linkedFile.Path.Length - 4, 4).ToLower())
            {
            case ".png":
                fileEncoder = BitmapEncoder.PngEncoderId;
                break;

            case "tiff":
                fileEncoder = BitmapEncoder.TiffEncoderId;
                break;

            case "bmp":
                fileEncoder = BitmapEncoder.BmpEncoderId;
                break;

            default:
                fileEncoder = BitmapEncoder.JpegEncoderId;
                break;
            }

            using (var sourceStream = await linkedFile.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

                ImageProperties props = await linkedFile.Properties.GetImagePropertiesAsync();

                //Debug.WriteLine(linkedFile.DisplayName + " " + props.Orientation);

                BitmapTransform transform = new BitmapTransform()
                {
                    ScaledWidth       = (uint)newSize.Width,
                    ScaledHeight      = (uint)newSize.Height,
                    InterpolationMode = BitmapInterpolationMode.Fant
                };

                if (!(props.Orientation == PhotoOrientation.Normal || props.Orientation == PhotoOrientation.Unspecified || props.Orientation == PhotoOrientation.FlipVertical || props.Orientation == PhotoOrientation.Rotate180))
                {
                    transform.ScaledWidth  = (uint)newSize.Height;
                    transform.ScaledHeight = (uint)newSize.Width;
                }

                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

                using (var destinationStream = await resizedImage.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(fileEncoder, destinationStream);

                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)newSize.Width, (uint)newSize.Height, 96, 96, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }

            //using (imageStream)
            //{
            //    using (var resizedStream = await resizedImage.OpenAsync(FileAccessMode.ReadWrite))
            //    {
            //        var encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);

            //        encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
            //        encoder.BitmapTransform.ScaledWidth = (uint)newSize.Width;
            //        encoder.BitmapTransform.ScaledHeight = (uint)newSize.Height;

            //        BitmapTransform transform = new BitmapTransform()
            //        {
            //            ScaledHeight = (uint)newSize.Width,
            //            ScaledWidth = (uint)newSize.Height,
            //            InterpolationMode = BitmapInterpolationMode.Fant
            //        };

            //        PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

            //        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)newSize.Width, (uint)newSize.Height, 96, 96, pixelData.DetachPixelData());

            //        await encoder.FlushAsync();
            //    }
            //}



            //using (imageStream)
            //{

            //    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);

            //    BitmapTransform transform = new BitmapTransform()
            //    {
            //        ScaledWidth = (uint)newSize.Width,
            //        ScaledHeight = (uint)newSize.Height,
            //        InterpolationMode = BitmapInterpolationMode.Fant
            //    };

            //    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

            //    using (var resizedStream = await resizedImage.OpenAsync(FileAccessMode.ReadWrite))
            //    {
            //        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(fileEncoder, resizedStream);
            //        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)newSize.Width, (uint)newSize.Height, 96, 96, pixelData.DetachPixelData());
            //        await encoder.FlushAsync();
            //    }

            //}
        }
コード例 #34
0
 public ImagePropertiesValidator(string imageFileName)
 {
     m_imagedFileName  = imageFileName;
     m_imageProperties = new ImageProperties(m_imagedFileName);
 }
コード例 #35
0
        internal override void Parse()
        {
            /*
             * <Images xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
             *    <OSImage>
             *      <AffinityGroup>name-of-the-affinity-group</AffinityGroup>
             *      <Category>category-of-the-image</Category>
             *      <Label>image-description</Label>
             *      <Location>geo-location-of-the-stored-image</Location>
             *      <LogicalSizeInGB>size-of-the-image</LogicalSizeInGB>
             *      <MediaLink>url-of-the-containing-blob</MediaLink>
             *      <Name>image-name</Name>
             *      <OS>operating-system-of-the-image</OS>
             *      <Eula>image-eula</Eula>
             *      <Description>image-description</Description>
             *      <ImageFamily>image-family</ImageFamily>
             *      <ShowInGui>true|false</ShowInGui>
             *      <PublishedDate>published-date</PublishedDate>
             *      <IsPremium>true|false</IsPremium>
             *      <PrivacyUri>uri-of-privacy-policy</PrivacyUri>
             *      <RecommendedVMSize>size-of-the-virtual-machine</RecommendedVMSize>
             *      <PublisherName>publisher-identifier</PublisherName>
             *      <PricingDetailLink>pricing-details</PricingDetailLink>
             *      <SmallIconUri>uri-of-icon</SmallIconUri>
             *      <Language>language-of-image</Language>
             *    </OSImage>
             *    …
             *  </Images>*/
            IEnumerable <XElement> rootElements = Document.Element(GetSchema() + "Images")
                                                  .Elements(GetSchema() + "OSImage");

            foreach (XElement osDetail in rootElements)
            {
                //if (osDetail.Element(GetSchema() + "MediaLink") == null)
                //{
                //    continue;
                //}

                //if (osDetail.Element(GetSchema() + "MediaLink").Value == String.Empty)
                //{
                //    continue;
                //}

                if (osDetail.Element(GetSchema() + "ImageFamily") != null)
                {
                    if (osDetail.Element(GetSchema() + "ImageFamily").Value.Contains("RightScale"))
                    {
                        continue;
                    }
                }
                var imageProperties = new ImageProperties();
                // get the affinity group if it exists
                if (osDetail.Element(GetSchema() + "Description") != null)
                {
                    imageProperties.Description = osDetail.Element(GetSchema() + "Description").Value;
                }
                if (osDetail.Element(GetSchema() + "Name") != null)
                {
                    imageProperties.Name = osDetail.Element(GetSchema() + "Name").Value;
                }
                if (osDetail.Element(GetSchema() + "Label") != null)
                {
                    imageProperties.Label = osDetail.Element(GetSchema() + "Label").Value;
                }
                if (osDetail.Element(GetSchema() + "Eula") != null)
                {
                    imageProperties.Eula = osDetail.Element(GetSchema() + "Eula").Value;
                }
                if (osDetail.Element(GetSchema() + "ImageFamily") != null)
                {
                    imageProperties.ImageFamily = osDetail.Element(GetSchema() + "ImageFamily").Value;
                }
                if (osDetail.Element(GetSchema() + "IsPremium") != null)
                {
                    imageProperties.IsPremium = bool.Parse(osDetail.Element(GetSchema() + "IsPremium").Value);
                }
                if (osDetail.Element(GetSchema() + "ShowInGui") != null)
                {
                    imageProperties.ShowInGui = bool.Parse(osDetail.Element(GetSchema() + "ShowInGui").Value);
                }
                if (osDetail.Element(GetSchema() + "MediaLink") != null)
                {
                    imageProperties.MediaLink = osDetail.Element(GetSchema() + "MediaLink").Value;
                }
                if (osDetail.Element(GetSchema() + "OS") != null)
                {
                    imageProperties.OperatingSystem = (PlatformType)Enum.Parse(typeof(PlatformType), osDetail.Element(GetSchema() + "OS").Value);
                }
                if (osDetail.Element(GetSchema() + "PublishedDate") != null)
                {
                    imageProperties.PublishedDate = DateTime.Parse(osDetail.Element(GetSchema() + "PublishedDate").Value);
                }

                CommandResponse.Add(imageProperties);
            }
        }
コード例 #36
0
 public static uint GetWidth(this ImageProperties props) => props.Width;
コード例 #37
0
        /// <summary>
        /// Partially modify an Image You can use update attributes of a resource
        /// </summary>
        /// <param name="imageId"></param>
        /// <param name="image">Modified Image</param>
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param>
        /// <returns>Task of ApiResponse (Image)</returns>
        public async System.Threading.Tasks.Task<ApiResponse<Image>> PartialUpdateAsyncWithHttpInfo(string imageId, ImageProperties image, bool? parameter = null, int? depth = null)
        {
            // verify the required parameter 'imageId' is set
            if (imageId == null) throw new ApiException(400, "Missing required parameter 'imageId' when calling PartialUpdate");
            // verify the required parameter 'image' is set
            if (image == null) throw new ApiException(400, "Missing required parameter 'image' when calling PartialUpdate");


            var path_ = "/images/{imageId}";

            var pathParams = new Dictionary<String, String>();
            var queryParams = new Dictionary<String, String>();
            var headerParams = new Dictionary<String, String>();
            var formParams = new Dictionary<String, String>();
            var fileParams = new Dictionary<String, FileParameter>();
            Object postBody = null;

            // to determine the Content-Type header
            String[] httpContentTypes = new String[] {
                "application/vnd.profitbricks.partial-properties+json", "application/json"
            };
            String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);

            // to determine the Accept header
            String[] httpHeaderAccepts = new String[] {
                "application/vnd.profitbricks.resource+json"
            };
            String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
            if (httpHeaderAccept != null)
                headerParams.Add("Accept", httpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            pathParams.Add("format", "json");
            if (imageId != null) pathParams.Add("imageId", Configuration.ApiClient.ParameterToString(imageId)); // path parameter

            if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
            if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter



            postBody = Configuration.ApiClient.Serialize(image); // http body (model) parameter



            // authentication (basicAuth) required

            // http basic authentication required
            if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
            {
                headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
            }


            // make the HTTP request
            IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_,
                Method.PATCH, queryParams, postBody, headerParams, formParams, fileParams,
                pathParams, httpContentType);

            int statusCode = (int)response.StatusCode;

            if (statusCode >= 400)
                throw new ApiException(statusCode, "Error calling PartialUpdate: " + response.Content, response.Content);
            else if (statusCode == 0)
                throw new ApiException(statusCode, "Error calling PartialUpdate: " + response.ErrorMessage, response.ErrorMessage);

            return new ApiResponse<Image>(statusCode,
                response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (Image)Configuration.ApiClient.Deserialize(response, typeof(Image)));

        }
コード例 #38
0
        /// <summary>
        /// Loads any Photo that is a Jpeg or PNG that the user chooses
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void loadBtn_Command(XamlUICommand sender, ExecuteRequestedEventArgs args)
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            //The types that are alowed to be seen by the user to load
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.FileTypeFilter.Add(".jpeg");
            fileOpenPicker.FileTypeFilter.Add(".png");
            fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;

            var inputFile = await fileOpenPicker.PickSingleFileAsync();

            if (inputFile == null)
            {
                // The user cancelled the picking operation
                return;
            }

            SoftwareBitmap softwareBitmap;
            int            scale = 4;

            using (IRandomAccessStream stream = await inputFile.OpenAsync(FileAccessMode.Read))
            {
                // Create the decoder from the stream
                if (stream.Size > 119)
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    // Get the SoftwareBitmap representation of the file

                    ImageProperties x = await inputFile.Properties.GetImagePropertiesAsync();

                    imageProperties = x;

                    //Scales the photo depending on size
                    if (x.Width > 2000 && x.Height > 1600)
                    {
                        mainCanvas.Width  = x.Width / (scale * 2);
                        mainCanvas.Height = x.Height / (scale * 2);
                    }
                    else if (x.Width > 1000 && x.Height > 800)
                    {
                        mainCanvas.Width  = x.Width / scale;
                        mainCanvas.Height = x.Height / scale;
                    }
                    else
                    {
                        mainCanvas.Width  = x.Width;
                        mainCanvas.Height = x.Height;
                    }
                    //Transforms the Softwarebitmap so that it doesnt run out of memory
                    BitmapTransform bt = new BitmapTransform();
                    softwareBitmap  = new SoftwareBitmap(BitmapPixelFormat.Bgra8, (int)(mainCanvas.Width), (int)(mainCanvas.Height));
                    bt.ScaledHeight = (uint)mainCanvas.Height;
                    bt.ScaledWidth  = (uint)mainCanvas.Width;
                    //Decodes the Image to write it to the Bitmap
                    softwareBitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, bt, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);

                    await mainCanvas.Bitmap.SetSourceAsync(stream);

                    mainCanvas.Bitmap = BitmapFactory.New((int)mainCanvas.Width, (int)mainCanvas.Height);
                    mainCanvas.Bitmap.Clear(((SolidColorBrush)mainCanvas.Background).Color);

                    mainCanvas.ImageControlSource = mainCanvas.Bitmap;

                    softwareBitmap.CopyToBuffer(mainCanvas.Bitmap.PixelBuffer);
                }
            }
        }
コード例 #39
0
 public ReportImageControl(int id, int posX, int posY, int width, int height) : base(id, posX, posY, width, height)
 {
     Properties = new ImageProperties(this);
 }
コード例 #40
0
        protected void DeleteImageFromDiskCache(string cacheKey, ImageProperties imageProperties, HttpContext httpContext)
        {
            string filePath = httpContext.Server.MapPath(GetDiskCacheFilePath(httpContext, cacheKey, imageProperties.FileExtension));

            DeleteImageFromDiskCache(imageProperties, filePath);
        }
コード例 #41
0
 public static uint GetHeight(this ImageProperties props) => props.Height;
コード例 #42
0
        protected new GridViewCommandColumnButtonControl CreateCommandButtonControl(GridViewCommandColumn column, ColumnCommandButtonType commandItemType, GridViewCommandButtonType buttonType, string text, ImageProperties image, int visibleIndex, bool postponeClick)
        {
            if (!CanCreateCommandButton(commandItemType))
            {
                return(null);
            }

            var isEditingRow = DataProxy.IsNewRowEditing && visibleIndex == -2147483647 || visibleIndex >= 0 && DataProxy.IsRowEditing(visibleIndex);

            var eventArgs = new ASPxGridViewCommandButtonEventArgs(column, commandItemType, text, image, visibleIndex, isEditingRow, buttonType);

            Grid.RaiseCommandButtonInitialize_Internal(eventArgs);

            return(eventArgs.Visible ? new GridViewCommandColumnButtonControl(eventArgs, Grid, GetCommandButtonClickHandlerArgs(commandItemType), postponeClick) : null);
        }
コード例 #43
0
ファイル: Extensions.cs プロジェクト: GuocRen/Unigram
        public static uint GetWidth(this ImageProperties props)
        {
            return(props.Width);

            return(props.Orientation == PhotoOrientation.Rotate180 ? props.Width : props.Height);
        }
コード例 #44
0
 private static void GetImageProperties(XElement itemElement, out string cacheKey, out ImageProperties imageProperties)
 {
     imageProperties = new ImageProperties();
     imageProperties.IsImagePresent = Convert.ToBoolean(itemElement.Attribute("isImagePresent").Value);
     imageProperties.Format = (DynamicImageFormat)Enum.Parse(typeof(DynamicImageFormat), itemElement.Attribute("format").Value);
     if (itemElement.Attribute("width") != null)
         imageProperties.Width = Convert.ToInt32(itemElement.Attribute("width").Value);
     if (itemElement.Attribute("height") != null)
         imageProperties.Height = Convert.ToInt32(itemElement.Attribute("height").Value);
     imageProperties.ColourDepth = Convert.ToInt32(itemElement.Attribute("colourDepth").Value);
     if (itemElement.Attribute("jpegCompressionLevel") != null)
         imageProperties.JpegCompressionLevel = Convert.ToInt32(itemElement.Attribute("jpegCompressionLevel").Value);
     cacheKey = itemElement.Attribute("id").Value;
 }
コード例 #45
0
        public Annotations SendRequest(string imagePath)
        {
            var imageArray   = File.ReadAllBytes(imagePath);
            var imageContent = Convert.ToBase64String(imageArray);

            var responses = _visionService.Images.Annotate(new BatchAnnotateImagesRequest()
            {
                Requests = new[]
                {
                    new AnnotateImageRequest()
                    {
                        Features = new[]
                        {
                            new Feature()
                            {
                                Type       = DetectionTypes.LabelDetection,
                                MaxResults = _maxResults
                            },
                            new Feature()
                            {
                                Type       = DetectionTypes.TextDetection,
                                MaxResults = _maxResults
                            },
                            new Feature()
                            {
                                Type       = DetectionTypes.LandmarkDetection,
                                MaxResults = _maxResults
                            },
                            new Feature()
                            {
                                Type       = DetectionTypes.LogoDetection,
                                MaxResults = _maxResults
                            },
                            new Feature()
                            {
                                Type       = DetectionTypes.FaceDetection,
                                MaxResults = _maxResults
                            },
                            new Feature()
                            {
                                Type       = DetectionTypes.SafeSearchDetection,
                                MaxResults = _maxResults
                            },
                            new Feature()
                            {
                                Type       = DetectionTypes.ImageProperties,
                                MaxResults = _maxResults
                            },
                        },
                        Image = new Image()
                        {
                            Content = imageContent
                        }
                    }
                }
            }).Execute();

            var labelAnnotations     = new List <EntityAnnotation>();
            var textAnnotations      = new List <EntityAnnotation>();
            var landmarkAnnotations  = new List <EntityAnnotation>();
            var logoAnnotations      = new List <EntityAnnotation>();
            var faceAnnotations      = new List <FaceAnnotation>();
            var safeSearchAnnotation = new SafeSearchAnnotation();
            var imageProperties      = new ImageProperties();
            var webDetection         = new WebDetection();
            var cropHints            = new CropHintsAnnotation();

            foreach (var response in responses.Responses)
            {
                if (response.LabelAnnotations != null)
                {
                    foreach (var labelAnnotation in response.LabelAnnotations)
                    {
                        labelAnnotations.Add(labelAnnotation);
                    }
                }

                if (response.LandmarkAnnotations != null)
                {
                    foreach (var landmarkAnnotation in response.LandmarkAnnotations)
                    {
                        landmarkAnnotations.Add(landmarkAnnotation);
                    }
                }

                if (response.LogoAnnotations != null)
                {
                    foreach (var logoAnnotation in response.LogoAnnotations)
                    {
                        logoAnnotations.Add(logoAnnotation);
                    }
                }

                if (response.TextAnnotations != null)
                {
                    foreach (var textAnnotation in response.TextAnnotations)
                    {
                        textAnnotations.Add(textAnnotation);
                    }
                }

                if (response.FaceAnnotations != null)
                {
                    foreach (var faceAnnotation in response.FaceAnnotations)
                    {
                        faceAnnotations.Add(faceAnnotation);
                    }
                }

                if (response.WebDetection != null)
                {
                    webDetection = response.WebDetection;
                }

                if (response.CropHintsAnnotation != null)
                {
                    cropHints = response.CropHintsAnnotation;
                }

                if (response.SafeSearchAnnotation != null)
                {
                    safeSearchAnnotation = response.SafeSearchAnnotation;
                }

                if (response.ImagePropertiesAnnotation != null)
                {
                    imageProperties = response.ImagePropertiesAnnotation;
                }
            }

            return(new Annotations(labelAnnotations, textAnnotations, logoAnnotations, landmarkAnnotations, faceAnnotations, safeSearchAnnotation, imageProperties, webDetection, cropHints));
        }
コード例 #46
0
 private static ImageProperties GetImageProperties(XElement itemElement)
 {
     var result = new ImageProperties();
     result.UniqueKey = itemElement.Attribute("uniqueKey").Value;
     result.IsImagePresent = Convert.ToBoolean(itemElement.Attribute("isImagePresent").Value);
     result.Format = (DynamicImageFormat)Enum.Parse(typeof(DynamicImageFormat), itemElement.Attribute("format").Value);
     if (itemElement.Attribute("width") != null)
         result.Width = Convert.ToInt32(itemElement.Attribute("width").Value);
     if (itemElement.Attribute("height") != null)
         result.Height = Convert.ToInt32(itemElement.Attribute("height").Value);
     result.ColourDepth = Convert.ToInt32(itemElement.Attribute("colourDepth").Value);
     if (itemElement.Attribute("jpegCompressionLevel") != null)
         result.JpegCompressionLevel = Convert.ToInt32(itemElement.Attribute("jpegCompressionLevel").Value);
     result.CacheProviderKey = itemElement.Attribute("id").Value;
     return result;
 }