Пример #1
0
        /// <summary>
        /// Evento para desenhar as linhas base.
        /// </summary>
        private void pctImagem_Paint(object sender, PaintEventArgs e)
        {
            if (this.pctImagem.Image == null)
            {
                return;
            }

            // Viewport
            RectangleF viewPort = new RectangleF(0f, 0f, this.pctImagem.Width, this.pctImagem.Height);

            // Window
            RectangleF window = new RectangleF(0f, 0f, this.selectedBitmap.Width, this.selectedBitmap.Height);

            // transforma os pontos
            PointF p1 = BitmapTools.LogicalToDevice(new PointF(0f, this.Ylower), viewPort, window);
            PointF p2 = BitmapTools.LogicalToDevice(new PointF(this.selectedBitmap.Width - 1, this.Ylower), viewPort, window);
            PointF p3 = BitmapTools.LogicalToDevice(new PointF(0f, this.Yupper), viewPort, window);
            PointF p4 = BitmapTools.LogicalToDevice(new PointF(this.selectedBitmap.Width - 1, this.Yupper), viewPort, window);

            // traços
            Pen pen1 = new Pen(Brushes.Blue, 2f);
            Pen pen2 = new Pen(Brushes.Red, 2f);

            pen1.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
            pen2.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

            // desenha as linhas
            e.Graphics.DrawLine(pen1, p1, p2);
            e.Graphics.DrawLine(pen2, p3, p4);
        }
Пример #2
0
        private async Task <UserInfo> TryGetUserInfoAsync(IActivatedEventArgsWithUser argsWithUser)
        {
            if (argsWithUser != null)
            {
                var user     = argsWithUser.User;
                var userInfo = new UserInfo
                {
                    AccountName = await user.GetPropertyAsync(KnownUserProperties.AccountName) as String,
                    FirstName   = await user.GetPropertyAsync(KnownUserProperties.FirstName) as String,
                    LastName    = await user.GetPropertyAsync(KnownUserProperties.LastName) as String
                };
                if (!userInfo.IsEmpty)
                {
                    if (String.IsNullOrEmpty(userInfo.AccountName))
                    {
                        userInfo.AccountName = $"{userInfo.FirstName} {userInfo.LastName}";
                    }
                    var pictureStream = await user.GetPictureAsync(UserPictureSize.Size64x64);

                    if (pictureStream != null)
                    {
                        userInfo.PictureSource = await BitmapTools.LoadBitmapAsync(pictureStream);
                    }
                    return(userInfo);
                }
            }
            return(UserInfo.Default);
        }
Пример #3
0
        public async Task ResizePngTest()
        {
            // Arrange
            const uint newSideLength = 100u;

            var folder = await Package.Current.InstalledLocation.GetFolderAsync(@"Assets\TestImages");

            var testPhoto = await folder.GetFileAsync("TestUploadPhoto.png");

            var stream = await testPhoto.OpenReadAsync();

            // Image should not be already in destination size
            var sourceDecoder = await BitmapDecoder.CreateAsync(stream);

            Assert.AreNotEqual(newSideLength, sourceDecoder.PixelWidth);
            Assert.AreNotEqual(newSideLength, sourceDecoder.PixelHeight);

            // Act
            var result = await BitmapTools.Resize(stream, newSideLength, newSideLength);

            // Verify
            Assert.IsNotNull(result);

            var decoder = await BitmapDecoder.CreateAsync(result);

            Assert.AreEqual(newSideLength, decoder.PixelHeight);
            Assert.AreEqual(newSideLength, decoder.PixelWidth);
        }
        /// <summary>
        /// Updates the preview image.
        /// </summary>
        private async void UpdatePreviewImage()
        {
            var sourceImageWidthScale  = _imageCanvas.Width / _sourceImagePixelWidth;
            var sourceImageHeightScale = _imageCanvas.Height / _sourceImagePixelHeight;

            var previewImageSize = new Size(
                _selectedRegion.SelectedRect.Width / sourceImageWidthScale,
                _selectedRegion.SelectedRect.Height / sourceImageHeightScale);

            double previewImageScale = 1;

            if (!(previewImageSize.Width <= _imageCanvas.Width &&
                  previewImageSize.Height <= _imageCanvas.Height))
            {
                previewImageScale = Math.Min(_imageCanvas.Width / previewImageSize.Width,
                                             _imageCanvas.Height / previewImageSize.Height);
            }

            try
            {
                PreviewImage = await BitmapTools.GetCroppedBitmapAsync(
                    _fileStream,
                    new Point(_selectedRegion.SelectedRect.X / sourceImageWidthScale,
                              _selectedRegion.SelectedRect.Y / sourceImageHeightScale),
                    previewImageSize,
                    previewImageScale);
            }
            catch (ArgumentException)
            {
                // Swallow this exception, sometimes XAML data binding
                // delivers some invalid values.
            }
        }
        /// <summary>
        /// Loads the image
        /// </summary>
        public async Task LoadImage()
        {
            try
            {
                var fileStream = await SourceFile.OpenAsync(FileAccessMode.Read);

                if (Rotation != BitmapRotation.None)
                {
                    var rotatedStream = await BitmapTools.Rotate(fileStream, Rotation);

                    await _cropControl.LoadImage(rotatedStream);
                }
                else
                {
                    await _cropControl.LoadImage(fileStream);
                }
            }
            catch (Exception exception)
            {
                _telemetryClient.TrackException(exception);
                await _dialogService.ShowNotification("InvalidImage_Message", "InvalidImage_Title");

                _navigationFacade.GoBack();
            }
        }
Пример #6
0
        public async Task <ImagePickerResult> OpenImagePickerAsync()
        {
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".bmp");
            picker.FileTypeFilter.Add(".gif");

            var file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                var bytes = await GetImageBytesAsync(file);

                return(new ImagePickerResult
                {
                    FileName = file.Name,
                    ContentType = file.ContentType,
                    ImageBytes = bytes,
                    ImageSource = await BitmapTools.LoadBitmapAsync(bytes)
                });
            }
            return(null);
        }
Пример #7
0
        public NlmCheckButton(Padding padding, Size size, String toolTipText, String iconDir, Boolean fadeOnChecked, NlmTreeListView listView)
        {
            ListView = listView;

            IconFull = new Bitmap(GetType().Module.Assembly.GetManifestResourceStream(iconDir));
            IconHalf = BitmapTools.ChangeOpacity((IconFull), (float)0.3);

            Appearance = Appearance.Button;
            FlatStyle  = FlatStyle.Flat;
            BackColor  = Color.FromArgb(0, 255, 255, 255);
            FlatAppearance.BorderSize         = 0;
            FlatAppearance.BorderColor        = Color.FromArgb(43, 120, 197);
            FlatAppearance.MouseDownBackColor = Color.FromArgb(154, 184, 225);
            FlatAppearance.MouseOverBackColor = Color.FromArgb(174, 204, 235);
            FlatAppearance.CheckedBackColor   = Color.FromArgb(174, 204, 235);
            Size                  = size;
            ImageAlign            = ContentAlignment.MiddleCenter;
            BackgroundImage       = IconFull;
            BackgroundImageLayout = ImageLayout.Center;
            Margin                = padding;
            Padding               = new Padding(0);
            ToolTipText           = toolTipText;
            FadeOnChecked         = fadeOnChecked;
            SetStyle(ControlStyles.Selectable, false);

            MouseEnter     += new EventHandler(ButtonMouseEnter);
            MouseLeave     += new EventHandler(ButtonMouseLeave);
            MouseDown      += new MouseEventHandler(ButtonMouseDown);
            MouseUp        += new MouseEventHandler(ButtonMouseUp);
            CheckedChanged += new EventHandler(CheckChanged);
        }
Пример #8
0
        static public async Task <ProductModel> CreateProductModelAsync(Product source, bool includeAllFields)
        {
            var model = new ProductModel()
            {
                ProductID         = source.product_id,
                CategoryID        = source.category_id,
                Name              = source.name,
                Description       = source.desc,
                Size              = source.size,
                Color             = source.color,
                ListPrice         = source.list_price,
                DealerPrice       = source.dealer_price,
                TaxType           = source.tax_type,
                Discount          = source.discount,
                DiscountStartDate = source.discount_begin_dt,
                DiscountEndDate   = source.discount_end_dt,
                StockUnits        = source.stock_unit,
                SafetyStockLevel  = source.safety_stock_level,
                CreatedOn         = source.reg_dt,
                LastModifiedOn    = source.upd_dt,
                Thumbnail         = source.thumbnail,
                ThumbnailSource   = await BitmapTools.LoadBitmapAsync(source.thumbnail)
            };

            if (includeAllFields)
            {
                model.Picture       = source.picture;
                model.PictureSource = await BitmapTools.LoadBitmapAsync(source.picture);
            }
            return(model);
        }
Пример #9
0
        public JsonResult AddStudent(string schoolId, string classId, string idCard, string pwd, string name, bool sex, string headImg, string sno)
        {
            if (string.IsNullOrEmpty(pwd))
            {
                return(Json(new { state = false, msg = "Password cannot null" }));
            }
            var hdcode    = new Hdcode();
            var rule      = BitmapTools.Name2Rule(name, out var size);
            var planNum   = hdcode.addPlan("学生:" + name, rule, size);
            var studentId = Database.AddStudent(schoolId, classId, idCard, pwd, name, sex, sno, planNum);

            if (studentId == -1)
            {
                return(Json(new { state = false, studentId, msg = "插入失败" }));
            }
            else if (studentId == -2)
            {
                return(Json(new { state = false, studentId, msg = "身份证号已存在" }));
            }
            else
            {
                var studentPath = Server.MapPath("/Resources/student/" + studentId);
                if (!Directory.Exists(studentPath))
                {
                    _ = Directory.CreateDirectory(studentPath);
                }
                SaveAndCompressImage(headImg, studentPath, "headImg");

                return(Json(new { state = true, studentId }));
            }
        }
Пример #10
0
        private async Task <ProductModel> CreateProductModelAsync(Product source, bool includeAllFields)
        {
            var model = new ProductModel()
            {
                ProductID         = source.ProductID,
                CategoryID        = source.CategoryID,
                SubCategoryID     = source.SubCategoryID,
                Name              = source.Name,
                Description       = source.Description,
                Size              = source.Size,
                Color             = source.Color,
                Gender            = source.Gender,
                ListPrice         = source.ListPrice,
                DealerPrice       = source.DealerPrice,
                TaxType           = source.TaxType,
                Discount          = source.Discount,
                DiscountStartDate = source.DiscountStartDate.AsNullableDateTimeOffset(),
                DiscountEndDate   = source.DiscountEndDate.AsNullableDateTimeOffset(),
                StockUnits        = source.StockUnits,
                SafetyStockLevel  = source.SafetyStockLevel,
                StartDate         = source.StartDate.AsNullableDateTimeOffset(),
                EndDate           = source.EndDate.AsNullableDateTimeOffset(),
                CreatedOn         = source.CreatedOn.AsDateTimeOffset(),
                LastModifiedOn    = source.LastModifiedOn.AsDateTimeOffset(),
                Thumbnail         = source.Thumbnail,
                ThumbnailBitmap   = await BitmapTools.LoadBitmapAsync(source.Thumbnail)
            };

            if (includeAllFields)
            {
                model.Picture       = source.Picture;
                model.PictureBitmap = await BitmapTools.LoadBitmapAsync(source.Picture);
            }
            return(model);
        }
Пример #11
0
        static public async Task <ProductModel> CreateProductModelAsync(Product source, bool includeAllFields)
        {
            var model = new ProductModel()
            {
                ProductID         = source.ProductID,
                CategoryID        = source.CategoryID,
                Name              = source.Name,
                Description       = source.Description,
                Size              = source.Size,
                Color             = source.Color,
                ListPrice         = source.ListPrice,
                DealerPrice       = source.DealerPrice,
                TaxType           = source.TaxType,
                Discount          = source.Discount,
                DiscountStartDate = source.DiscountStartDate,
                DiscountEndDate   = source.DiscountEndDate,
                StockUnits        = source.StockUnits,
                SafetyStockLevel  = source.SafetyStockLevel,
                CreatedOn         = source.CreatedOn,
                LastModifiedOn    = source.LastModifiedOn,
                Thumbnail         = source.Thumbnail,
                ThumbnailSource   = await BitmapTools.LoadBitmapAsync(source.Thumbnail)
            };

            if (includeAllFields)
            {
                model.Picture       = source.Picture;
                model.PictureSource = await BitmapTools.LoadBitmapAsync(source.Picture);
            }
            return(model);
        }
Пример #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tobj"></param>
        /// <param name="bmp"></param>
        /// <param name="imgFormat"></param>
        /// <param name="palFormat"></param>
        public static void InjectBitmap(Bitmap bmp, HSD_TOBJ tobj, GXTexFmt imgFormat, GXTlutFmt palFormat)
        {
            if (imgFormat == GXTexFmt.CI8)  // doesn't work well with alpha
            {
                bmp = BitmapTools.ReduceColors(bmp, 256);
            }
            if (imgFormat == GXTexFmt.CI4 || imgFormat == GXTexFmt.CI14X2)
            {
                bmp = BitmapTools.ReduceColors(bmp, 16);
            }

            var bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var length     = bitmapData.Stride * bitmapData.Height;

            byte[] bytes = new byte[length];

            Marshal.Copy(bitmapData.Scan0, bytes, 0, length);
            bmp.UnlockBits(bitmapData);

            tobj.EncodeImageData(bytes, bmp.Width, bmp.Height, imgFormat, palFormat);

            // dispose if we use our color reduced bitmap
            //if (imgFormat == GXTexFmt.CI8 || imgFormat == GXTexFmt.CI4 || imgFormat == GXTexFmt.CI14X2)
            //    bmp.Dispose();
        }
Пример #13
0
 // Constructors.
 public MappedActiveImageRenderer(Bitmap trueImage, Bitmap falseImage, Bitmap nullImage)
 {
     TrueActiveImage    = trueImage;
     TrueInactiveImage  = BitmapTools.ChangeOpacity(trueImage, 0.3F);
     FalseActiveImage   = falseImage;
     FalseInactiveImage = BitmapTools.ChangeOpacity(falseImage, 0.3F);
     NullActiveImage    = nullImage;
     NullInactiveImage  = BitmapTools.ChangeOpacity(nullImage, 0.3F);
 }
Пример #14
0
        /// <summary>
        /// Converts <see cref="HSD_TOBJ"/> into <see cref="Bitmap"/>
        /// </summary>
        /// <param name="tobj"></param>
        /// <returns></returns>
        public static Bitmap ToBitmap(HSD_TOBJ tobj)
        {
            if (tobj.ImageData == null)
            {
                return(null);
            }

            var rgba = tobj.GetDecodedImageData();

            return(BitmapTools.BGRAToBitmap(rgba, tobj.ImageData.Width, tobj.ImageData.Height));
        }
Пример #15
0
        public bool Detect()
        {
            List <int> xposlen, yposlen;
            Rectangle  rt = new Rectangle(0, 0, _src.Size.Width, _src.Size.Height);

            int[] ycnt = BitmapTools.CountYPixsum(_src, rt);
            int[] xcnt = BitmapTools.CountXPixsum(_src, rt);
            ycnt = ycnt.Select(r => _src.Width - r).ToArray();
            xcnt = xcnt.Select(r => _src.Height - r).ToArray();

            int ymin = (int)Math.Ceiling(ycnt.Where(r => r > 0).Average() / 4);
            int xmin = (int)Math.Ceiling(xcnt.Where(r => r > 0).Average() / 4);

            ycnt = ycnt.Select(r => r > ymin?r :0).ToArray();
            xcnt = xcnt.Select(r => r > xmin?r :0).ToArray();

            yposlen = BitmapTools.SectionCount(ycnt, ymin, _src.Width, 2);
            xposlen = BitmapTools.SectionCount(xcnt, xmin, _src.Height, 2);
            if (xposlen.Count == 0 || yposlen.Count == 0)
            {
                return(false);
            }
            MergeSection(yposlen);
            MergeSection(xposlen);
            if (RemoveAndCheck(xposlen, 4) && RemoveAndCheck(yposlen, choicecount))
            {
                m_choicepoint = new List <List <Point> >();
                int sum = 0;
                for (int i = 1; i < xposlen.Count; i += 2)
                {
                    sum += xposlen[i] * xposlen[i];
                }
                choicesize.Width = (int)Math.Sqrt(sum * 2 / xposlen.Count);
                sum = 0;
                for (int i = 1; i < yposlen.Count; i += 2)
                {
                    sum += yposlen[i] * yposlen[i];
                }
                choicesize.Height = (int)Math.Sqrt(sum * 2 / yposlen.Count);

                for (int i = 0; i < yposlen.Count; i += 2)
                {
                    List <Point> c = new List <Point>();
                    for (int j = 0; j < xposlen.Count; j += 2)
                    {
                        c.Add(new Point(xposlen[j], yposlen[i]));
                    }
                    m_choicepoint.Add(c);
                }
                return(true);
            }
            //DrawToFile(xcnt);
            return(false);
        }
Пример #16
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="src"></param>
 /// <param name="src"></param>
 /// <param name="colr"></param>
 /// <returns></returns>
 private static Bitmap GetColoredCharacter(Bitmap src, Rectangle rect, Color colr)
 {
     if (rect.X < src.Width && rect.Y < src.Height && rect.X + rect.Width <= src.Width && rect.Y + rect.Height <= src.Height)
     {
         using (Bitmap croppedImage = src.Clone(rect, PixelFormat.Format32bppArgb))
             return(BitmapTools.Multiply(croppedImage, colr.R, colr.G, colr.B));
     }
     else
     {
         return(null);
     }
 }
        /// <summary>
        /// Uploads the photo.
        /// </summary>
        /// <param name="stream">The memory stream.</param>
        /// <param name="localPath">The local path.</param>
        /// <param name="caption">The caption.</param>
        /// <param name="categoryId">The id of the assocaited category.</param>
        /// <returns>The uploaded photo.</returns>
        public async Task <Photo> UploadPhoto(Stream stream, string localPath, string caption, string categoryId)
        {
            try
            {
                var sasContracts = await GetSasUrls();

                // Upload photos into azure
                foreach (var sasContract in sasContracts)
                {
                    var blob =
                        new CloudBlockBlob(
                            new Uri($"{sasContract.FullBlobUri}{sasContract.SasToken}"));

                    var sideLength = sasContract.SasPhotoType.ToSideLength();

                    var resizedStream = await BitmapTools.Resize(
                        stream.AsRandomAccessStream(), sideLength,
                        sideLength);

                    await blob.UploadFromStreamAsync(resizedStream);
                }

                var photoContract = new PhotoContract
                {
                    CategoryId   = categoryId,
                    Description  = caption,
                    OSPlatform   = AnalyticsInfo.VersionInfo.DeviceFamily,
                    User         = AppEnvironment.Instance.CurrentUser.ToDataContract(),
                    ThumbnailUrl =
                        sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.Thumbnail)?
                        .FullBlobUri.ToString(),
                    StandardUrl =
                        sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.Standard)?
                        .FullBlobUri.ToString(),
                    HighResolutionUrl =
                        sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.HighRes)?
                        .FullBlobUri.ToString()
                };

                var responsePhotoContract =
                    await _mobileServiceClient.InvokeApiAsync <PhotoContract, PhotoContract>("Photo",
                                                                                             photoContract,
                                                                                             HttpMethod.Post,
                                                                                             null);

                return(responsePhotoContract.ToDataModel());
            }
            catch (Exception e)
            {
                _telemetryClient.TrackException(e);
                throw new ServiceException("UploadPhoto error", e);
            }
        }
Пример #18
0
        /// <summary>
        /// Evento chamado quando o usuário solta o botão do mouse.
        /// </summary>
        private void pctImagem_MouseUp(object sender, MouseEventArgs e)
        {
            // Viewport
            RectangleF viewPort = new RectangleF(0f, 0f, this.pctImagem.Width, this.pctImagem.Height);

            // Window
            RectangleF window = new RectangleF(0f, 0f, this.selectedBitmap.Width, this.selectedBitmap.Height);

            if (this.buttonPressedUpper)
            {
                int Y = e.Y;

                // corrige Y
                if (Y > this.pctImagem.Height)
                {
                    Y = this.pctImagem.Height - 1;
                }
                else if (Y < 0)
                {
                    Y = 0;
                }

                PointF logicalPoint = BitmapTools.DeviceToLogical(new PointF(0f, Y), window, viewPort);
                this.Yupper             = logicalPoint.Y;
                this.buttonPressedUpper = false;
            }
            else if (this.buttonPressedLower)
            {
                int Y = e.Y;

                // corrige Y
                if (Y > this.pctImagem.Height)
                {
                    Y = pctImagem.Height - 1;
                }
                else if (Y < 0)
                {
                    Y = 0;
                }

                PointF logicalPoint = BitmapTools.DeviceToLogical(new PointF(0f, Y), window, viewPort);
                this.Ylower             = logicalPoint.Y;
                this.buttonPressedLower = false;
            }

            // calcula altura
            CalculateHeight();

            // redesenha imagem
            this.pctImagem.Invalidate();
        }
Пример #19
0
        private bool DetectFeatureRectAngle4(Bitmap bmp, Rectangle r, int maxlen, ref Rectangle outrect)
        {
            Rectangle rectyline = r;

            int[]      yycnt = BitmapTools.CountYPixsum(bmp, rectyline);
            List <int> ycnt  = yycnt.Select(rec => 2 - rec).ToList();

            //count Xpoint
            int Ypoint    = 0;
            int len       = 0;
            int yblackcnt = 0;
            int Ylen      = 1;

            for (int i = 0; i < ycnt.Count; i++)
            {
                if (ycnt[i] > yblackcnt)
                {
                    if (len == 0)
                    {
                        Ypoint = i;
                    }
                    len++;
                }
                else
                {
                    if (len >= maxlen)
                    {
                        Ylen = len;
                        break;
                    }
                    else
                    {
                        len = 0;
                    }
                }
            }
            if (len > Ylen)
            {
                Ylen = len;
            }

            outrect.Y      = Ypoint;
            outrect.Height = Ylen;
            if (Ylen >= maxlen)
            {
                return(true);
            }
            return(false);
        }
Пример #20
0
        private bool DetectFeatureRectAngle3(Bitmap bmp, Rectangle r, int maxlen, out Rectangle outrect)
        {
            Rectangle rectxline = r;

            int[]      xxcnt = BitmapTools.CountXPixsum(bmp, rectxline);
            List <int> xcnt  = xxcnt.Select(rec => 2 - rec).ToList();

            //count Xpoint
            int Xpoint    = 0;
            int len       = 0;
            int xblackcnt = 0;
            int Xlen      = 1;

            for (int i = 0; i < xcnt.Count; i++)
            {
                if (xcnt[i] > xblackcnt)
                {
                    if (len == 0)
                    {
                        Xpoint = i;
                    }
                    len++;
                }
                else
                {
                    if (len >= maxlen)
                    {
                        Xlen = len;
                        break;
                    }
                    else
                    {
                        len = 0;
                    }
                }
            }
            if (len > Xlen)
            {
                Xlen = len;
            }

            outrect = new Rectangle(Xpoint, 0, Xlen, 2);
            if (Xlen >= maxlen)
            {
                return(true);
            }
            return(false);
        }
 public object Convert(object value, Type targetType, object parameter, string language)
 {
     if (value is byte[] array)
     {
         return(BitmapTools.LoadBitmap(array));
     }
     else if (value is ImageSource imageSource)
     {
         return(imageSource);
     }
     else if (value is String url)
     {
         return(url);
     }
     return(null);
 }
        /// <summary>
        /// Loads the image.
        /// </summary>
        /// <param name="fileStream">The file stream.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">The file stream must not be null</exception>
        public async Task LoadImage(IRandomAccessStream fileStream)
        {
            if (fileStream == null)
            {
                throw new ArgumentException("fileStream must not be null");
            }

            _fileStream = fileStream;

            _sourceImage.Source = null;

            var decoder = await BitmapDecoder.CreateAsync(fileStream);

            _sourceImagePixelHeight = decoder.PixelHeight;
            _sourceImagePixelWidth  = decoder.PixelWidth;

            if (_sourceImagePixelHeight < 2 * CornerSize ||
                _sourceImagePixelWidth < 2 * CornerSize)
            {
                // Image too small.
                throw new ArgumentOutOfRangeException(
                          $"Please select an image which is larger than {2 * CornerSize}*{2 * CornerSize}");
            }

            double sourceImageScale = 1;

            if (_sourceImagePixelHeight < _layoutRoot.ActualHeight &&
                _sourceImagePixelWidth < _layoutRoot.ActualWidth)
            {
                _sourceImage.Stretch = Stretch.None;
            }
            else
            {
                sourceImageScale = Math.Min(_layoutRoot.ActualWidth / _sourceImagePixelWidth,
                                            _layoutRoot.ActualHeight / _sourceImagePixelHeight);
                _sourceImage.Stretch = Stretch.Uniform;
            }

            _sourceImage.Source = await BitmapTools.GetCroppedBitmapAsync(
                fileStream,
                new Point(0, 0),
                new Size(_sourceImagePixelWidth, _sourceImagePixelHeight),
                sourceImageScale);

            PreviewImage = null;
        }
Пример #23
0
        private void SaveAndCompressImage(string base64, string path, string fileName)
        {
            var imgPath     = path + "/" + fileName + ".jpg";
            var imgMiniPath = path + "/" + fileName + ".min.jpg";
            var bmp         = BitmapTools.Base64ToBitmap(base64);

            if (bmp == null)
            {
                return;
            }

            var bmpMini = BitmapTools.MakeMiniBitmap(bmp, 200);

            bmp.Save(imgPath, ImageFormat.Jpeg);
            bmpMini.Save(imgMiniPath, ImageFormat.Jpeg);
            bmp.Dispose();
            bmpMini.Dispose();
        }
        /// <summary>
        /// Creates the non-scaled cropped image.
        /// </summary>
        public async Task <WriteableBitmap> GetCroppedImage()
        {
            var sourceImageWidthScale  = _imageCanvas.Width / _sourceImagePixelWidth;
            var sourceImageHeightScale = _imageCanvas.Height / _sourceImagePixelHeight;

            var previewImageSize = new Size(
                _selectedRegion.SelectedRect.Width / sourceImageWidthScale,
                _selectedRegion.SelectedRect.Height / sourceImageHeightScale);

            var croppedImage = await BitmapTools.GetCroppedBitmapAsync(
                _fileStream,
                new Point(_selectedRegion.SelectedRect.X / sourceImageWidthScale,
                          _selectedRegion.SelectedRect.Y / sourceImageHeightScale),
                previewImageSize,
                1);

            return(croppedImage);
        }
Пример #25
0
        public void Join(int lat0, int lon0, int lat1, int lon1)
        {
            int dlat = lat0 - lat1;
            int dlon = lon1 - lon0;

            var readers = new List <RawReader>();

            var concatBitmaps = new List <EnumerableBitmap <short> >();

            for (int lat = lat0; lat >= lat1; lat--)
            {
                var bitmapPaths = new List <string>();
                for (int lon = lon0; lon <= lon1; lon++)
                {
                    string bitmapPath = string.Format(_inputPath, MapPosition(lat, lon));
                    bitmapPaths.Add(bitmapPath);
                }
                var rawReaders = bitmapPaths.Select(p => File.Exists(p) ? new RawReader(File.OpenRead(p)) : null).ToArray();
                readers.AddRange(rawReaders);

                var rowBitmaps = rawReaders.Select(r => r != null ? r.ReadBitmap <short>(1201, 1201) : (IBitmap <short>)_oceanBitmap).ToArray();
                var rowBitmap  = BitmapTools.Concatenate(rowBitmaps);

                concatBitmaps.Add(rowBitmap);
            }

            var theBitmap = BitmapTools.Append(concatBitmaps.ToArray());

            using (var tiffWriter = new TiffWriter(File.Create($@"Datasets\Planets\Earth\ViewFinderPanoramas\dem3_{MapPosition(lat0, lon0)}_{MapPosition(lat1, lon1)}.tif")))
            {
                tiffWriter.BigTiff = true;
                theBitmap          = theBitmap.Convert((p) =>
                {
                    return((short)(((p >> 8) & 0xff) | ((p << 8) & 0xff00)));
                });
                tiffWriter.WriteImageFile(theBitmap);
            }

            foreach (var reader in readers)
            {
                reader?.Dispose();
            }
        }
        /// <summary>
        /// Takes the photo.
        /// </summary>
        public async Task <WriteableBitmap> TakePhoto()
        {
            var stream = new InMemoryRandomAccessStream();

            if (_mediaCapture.VideoDeviceController.FocusControl.Supported)
            {
                await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();
            }

            // Capture the photo
            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            // Get width and height for square aspect ratio
            var minDim = Math.Min(_selectedPreviewResolution.Width, _selectedPreviewResolution.Height);

            var xOffset = (_selectedPreviewResolution.Width - minDim) / 2.0;
            var yOffset = (_selectedPreviewResolution.Height - minDim) / 2.0;

            if (AppEnvironment.Instance.IsMobileDeviceFamily)
            {
                // Adjust orientation depending on camera panel
                var rotation = (_device.EnclosureLocation?.Panel == Panel.Front)
                    ? BitmapRotation.Clockwise270Degrees
                    : BitmapRotation.Clockwise90Degrees;

                // Rotate the image
                stream = await BitmapTools.Rotate(stream, rotation);

                // We have a different orientation on mobile, so also swap offsets
                var tempOffset = xOffset;
                yOffset = xOffset;
                xOffset = tempOffset;
            }

            // Now crop the image
            var writeableBitmap =
                await
                BitmapTools.GetCroppedBitmapAsync(stream, new Point(xOffset, yOffset), new Size(minDim, minDim),
                                                  1);

            return(writeableBitmap);
        }
Пример #27
0
        public string FindBestVisualMatch(FontInfo fontInfo, Bitmap referenceImage)
        {
            // TODO: improve grayscaling color matrix this currently results in 'N' being the best match for all comparisons
            // referenceImage = BitmapTools.ConvertToGrayscale(referenceImage);

            float  bestMatchDistance = 0;
            Bitmap bestMatch         = null; // TODO: specify a fallback character in the FontInfo class that is used instead of the first literal one

            foreach (var characterBitmap in fontInfo.CharacterMap.Keys)
            {
                var distance = BitmapTools.CalculateDifference(characterBitmap, referenceImage);
                if (bestMatch == null || distance < bestMatchDistance)
                {
                    bestMatchDistance = distance;
                    bestMatch         = characterBitmap;
                }
            }

            return(fontInfo.CharacterMap[bestMatch]);
        }
Пример #28
0
        static public async Task <CustomerModel> CreateCustomerModelAsync(Customer source, bool includeAllFields)
        {
            var model = new CustomerModel()
            {
                CustomerID = source.customer_id,
                //Title = source.Title,
                FirstName = source.firstname,
                //MiddleName = source.MiddleName,
                LastName = source.lastname,
                //Suffix = source.Suffix,
                Gender       = source.gender,
                EmailAddress = source.email,
                //AddressLine1 = source.AddressLine1,
                //AddressLine2 = source.AddressLine2,
                //City = source.City,
                //Region = source.Region,
                //CountryCode = source.country_cd,
                //PostalCode = source.PostalCode,
                Phone           = source.phone_no,
                CreatedOn       = source.reg_dt,
                LastModifiedOn  = source.upd_dt,
                Thumbnail       = source.thumbnail,
                ThumbnailSource = await BitmapTools.LoadBitmapAsync(source.thumbnail)
            };

            if (includeAllFields)
            {
                model.BirthDate = source.birthdate;
                //model.Education = source.Education;
                //model.Occupation = source.Occupation;
                //model.YearlyIncome = source.YearlyIncome;
                //model.MaritalStatus = source.MaritalStatus;
                //model.TotalChildren = source.TotalChildren;
                //model.ChildrenAtHome = source.ChildrenAtHome;
                //model.IsHouseOwner = source.IsHouseOwner;
                //model.NumberCarsOwned = source.NumberCarsOwned;
                model.Picture       = source.picture;
                model.PictureSource = await BitmapTools.LoadBitmapAsync(source.picture);
            }
            return(model);
        }
        private async Task <CustomerModel> CreateCustomerModelAsync(Customer source, bool includeAllFields)
        {
            var model = new CustomerModel()
            {
                CustomerID      = source.CustomerID,
                Title           = source.Title,
                FirstName       = source.FirstName,
                MiddleName      = source.MiddleName,
                LastName        = source.LastName,
                Suffix          = source.Suffix,
                Gender          = source.Gender,
                EmailAddress    = source.EmailAddress,
                AddressLine1    = source.AddressLine1,
                AddressLine2    = source.AddressLine2,
                City            = source.City,
                Region          = source.Region,
                CountryCode     = source.CountryCode,
                PostalCode      = source.PostalCode,
                Phone           = source.Phone,
                CreatedOn       = source.CreatedOn.AsDateTimeOffset(),
                LastModifiedOn  = source.LastModifiedOn.AsNullableDateTimeOffset(),
                Thumbnail       = source.Thumbnail,
                ThumbnailBitmap = await BitmapTools.LoadBitmapAsync(source.Thumbnail)
            };

            if (includeAllFields)
            {
                model.BirthDate       = source.BirthDate.AsNullableDateTimeOffset();
                model.Education       = source.Education;
                model.Occupation      = source.Occupation;
                model.YearlyIncome    = source.YearlyIncome;
                model.MaritalStatus   = source.MaritalStatus;
                model.TotalChildren   = source.TotalChildren;
                model.ChildrenAtHome  = source.ChildrenAtHome;
                model.IsHouseOwner    = source.IsHouseOwner;
                model.NumberCarsOwned = source.NumberCarsOwned;
                model.Picture         = source.Picture;
                model.PictureBitmap   = await BitmapTools.LoadBitmapAsync(source.Picture);
            }
            return(model);
        }
Пример #30
0
        public async Task RotateJpgTest()
        {
            // Arrange
            var folder = await Package.Current.InstalledLocation.GetFolderAsync(@"Assets\TestImages");

            var testPhoto = await folder.GetFileAsync("TestUploadPhoto.jpg");

            var photoStream = await testPhoto.OpenReadAsync();

            var sourceImageDecoder = await BitmapDecoder.CreateAsync(photoStream);

            // Act
            var rotatedStream = await BitmapTools.Rotate(photoStream, BitmapRotation.Clockwise90Degrees);

            // Verify
            Assert.IsNotNull(rotatedStream);

            var rotatedImageDecoder = await BitmapDecoder.CreateAsync(rotatedStream);

            Assert.AreEqual(sourceImageDecoder.PixelWidth, rotatedImageDecoder.PixelHeight);
            Assert.AreEqual(sourceImageDecoder.PixelHeight, rotatedImageDecoder.PixelWidth);
        }