/// <summary>
        /// Creates an embeddable thumbnail of the reference image
        /// </summary>
        /// <param name="_Image"></param>
        public void CreateThumbnail( ImageUtility.Bitmap _Image )
        {
            int		MaxDim = Math.Max( _Image.Width, _Image.Height );
            int		ThumbnailSize = 256;

            int		W = ThumbnailSize * _Image.Width / MaxDim;
            int		H = ThumbnailSize * _Image.Height / MaxDim;

            // Build the thumbnail
            m_Thumbnail = new byte[W,H];
            for ( int Y=0; Y < H; Y++ )
                for ( int X=0; X < W; X++ )
                {
                    ImageUtility.float4	XYZ = _Image.ContentXYZ[X*_Image.Width/W, Y*_Image.Height/H];
                    m_Thumbnail[X,Y] = (byte) Math.Min( 255, Math.Max( 0, 255.0f * XYZ.y ) );
                }
        }
Exemple #2
0
 public void SetImage(string path)
 {
     if (!File.Exists(path))
     {
         return;
     }
     if (Enum.GetNames(typeof(EGDIFormats)).Contains(Path.GetExtension(path).TrimStart('.').ToUpper()))
     {
         ImagePreviewControl.Image = Image.FromFile(path) ?? SystemIcons.Warning.ToBitmap();
     }
     else if (Path.GetExtension(path).ToUpper().Contains("TGA") || Path.GetExtension(path).ToUpper().Contains("DDS"))
     {
         ImagePreviewControl.Image = ImageUtility.FromFile(path) ?? SystemIcons.Warning.ToBitmap();
     }
     else
     {
         ImagePreviewControl.Image = SystemIcons.Warning.ToBitmap();
     }
     this.Text = Path.GetFileName(path);
 }
Exemple #3
0
        public static double CompareShapePercentage(ProbabilisticImage A, ProbabilisticImage B)
        {
            double PointCount = Math.Pow(A.R, 2);
            double Amount = 0.0, IncreaseAmount = 1.0 / PointCount;

            for (int x = -A.R; x < A.R; x++)
            {
                for (int y = -A.R; y < A.R; y++)
                {
                    double RelativeX = (double)x / (double)A.R;
                    double RelativeY = (double)y / (double)A.R;

                    Point ACompare = new Point();
                    Point BCompare = new Point();

                    if (A.IsCircle && B.IsCircle)
                    {
                        ACompare = A.GetCircularPoint(RelativeX, RelativeY);
                        BCompare = B.GetCircularPoint(RelativeX, RelativeY);
                    }
                    else
                    {
                        ACompare = A.GetRectangularPoint(RelativeX, RelativeY);
                        BCompare = B.GetRectangularPoint(RelativeX, RelativeY);
                    }

                    Color APixel = A.GetPixel(ACompare);
                    Color BPixel = B.GetPixel(BCompare);

                    //Console.WriteLine("{0} == {1} = {2}", APixel.ToString(), B.GetPixel(BCompare).ToString(), ImageUtility.ColorCheck(APixel, B.GetPixel(BCompare)));

                    //If neither is a background color, then it must be part of the main picture, and therefore the shape is the same here.
                    if ((!ImageUtility.ColorCheck(A.BackgroundColor, APixel)) == (!ImageUtility.ColorCheck(B.BackgroundColor, BPixel)))
                    {
                        Amount += IncreaseAmount;
                    }
                }
            }

            return(Amount);
        }
Exemple #4
0
        /// <summary>
        /// Image of the text
        /// </summary>
        private IImageAdapter GetTypoResult()
        {
            int          maxX = 0;
            int          maxY = 0;
            ITypographer avtp = TypographerBroker.Instance;

            foreach (GlyphChar glyphChar in Glyphs)
            {
                int x = (int)(glyphChar.ComputedLayout.SizeF.Width + glyphChar.ComputedLayout.PositionF.X + .5);
                int y = (int)(glyphChar.ComputedLayout.SizeF.Height + glyphChar.ComputedLayout.PositionF.Y + .5);
                if (x > maxX)
                {
                    maxX = x;
                }
                if (y > maxY)
                {
                    maxY = y;
                }
            }
            IImageAdapter retVal = new ImageAdapter(maxX, maxY, BackgroundColor);

//                    IImageAdapter imageChar = null;
//                    for (int t = 0; t < _text.Count; t++)
            foreach (GlyphChar glyphChar in Glyphs)
            {
                // HACK : Call Render Char one more time but ignore Background color
                avtp.Text                = glyphChar.Character.ToString();
                avtp.FontSize            = Font.Size;
                avtp.FontName            = Font.Name;
                avtp.BackgroundColor     = BackgroundColor;
                avtp.ForegroundColor     = ForegroundColor;
                avtp.TextRenderingHint   = TextRenderingHint;
                glyphChar.GeneratedImage = avtp.Render();

                Point offset             = glyphChar.ComputedLayout.Position;
                System.Drawing.Size size = new System.Drawing.Size(glyphChar.GeneratedImage.Width, glyphChar.GeneratedImage.Height);
                retVal = ImageUtility.CopyImageAdapter(retVal, glyphChar.GeneratedImage, offset, size, true);
            }

            return(retVal);
        }
Exemple #5
0
        public ResponseModel <string> AddGalleryImage(GalleryViewModel model, string serverPath, string thumbPath)
        {
            ResponseModel <string> response = new ResponseModel <string> {
                Data = ""
            };

            try
            {
                Gallery gallery = new Gallery();
                gallery.CreatedOn = DateTime.Now;
                gallery.IsActive  = true;
                gallery.IsMain    = false;
                gallery.StoreId   = model.StoreId;

                string FileName    = Guid.NewGuid().ToString() + "." + Convert.ToString(model.FileName.Split('.')[1]);
                var    path        = Path.Combine(serverPath, FileName.ToString());
                string image64Base = model.Image.Replace("\r", "").Replace("\n", "");
                byte[] imageBytes  = Convert.FromBase64String(image64Base);
                File.WriteAllBytes(path, imageBytes);

                gallery.Image = FileName;
                using (MemoryStream ms = new MemoryStream(imageBytes))
                {
                    // string thumbName = Guid.NewGuid().ToString() + "." + Convert.ToString(ImageFormat.Png);
                    var outpath = Path.Combine(thumbPath, FileName.ToString());
                    ImageUtility.Thumbnail(path, outpath);
                    gallery.ThumbnailImage = FileName;
                }
                gallery.CheckInId = model.CheckInId;
                acmContext.Gallery.Add(gallery);
                acmContext.SaveChanges();
                response.Status  = true;
                response.Message = "success";
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
            }
            return(response);
        }
Exemple #6
0
        private void lstPhotos_DrawItem(object sender, DrawItemEventArgs e)
        {
            Graphics g = e.Graphics;

            if (e.Index < 0 || e.Index > Manager.Album.Count - 1)
            {
                return;
            }
            Photograph p = Manager.Album[e.Index];

            Rectangle imageRect = ImageUtility.ScaleToFit(p.Image, DrawRect);

            imageRect.X = e.Bounds.X + 2;
            imageRect.Y = e.Bounds.Y + 1;

            g.DrawImage(p.Image, imageRect);
            g.DrawRectangle(Pens.Black, imageRect);
            p.ReleaseImage();

            Rectangle textRect = new Rectangle();

            textRect.X      = imageRect.Right + 2;
            textRect.Y      = imageRect.Y + ((imageRect.Height - e.Font.Height) / 2);
            textRect.Width  = e.Bounds.Width - imageRect.Width - 4;
            textRect.Height = e.Font.Height;

            Brush textBrush;

            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                g.FillRectangle(SystemBrushes.Highlight, textRect);
                textBrush = SystemBrushes.HighlightText;
            }
            else
            {
                g.FillRectangle(SystemBrushes.Window, textRect);
                textBrush = SystemBrushes.WindowText;
            }

            g.DrawString(lstPhotos.GetItemText(p), e.Font, textBrush, textRect);
        }
Exemple #7
0
    public static byte[] GetProductImage(string photoID, bool useCache)
    {
        string[] vals   = photoID.Split('_');
        long     goodID = Convert.ToInt64(vals[0]);
        int      viewID = Convert.ToInt32(vals[1]);

        if (useCache && prodPhotoCache.ContainsKey(goodID))
        {
            return(prodPhotoCache[goodID]);
        }

        byte[] bytes = DiskCache.GetImage(goodID, 0, viewID);
        if (bytes != null)
        {
            return(bytes);
        }
        else
        {
            bytes = ImageUtility.GetNoImageStub();
        }

        Hashtable pars = new Hashtable();

        pars["Images"] = new String[] { photoID };
        CGoodImage[] images = GetObject <CGoodImage[]>("GetImages", pars);
        if (images != null)
        {
            bytes = images[0].Image;
            if (bytes != null)
            {
                DiskCache.WriteImage(bytes, goodID, 0, viewID);
            }
        }

        if (useCache)
        {
            prodPhotoCache[goodID] = bytes;
        }

        return(bytes);
    }
Exemple #8
0
        private Dictionary <string, Image> BuildImageList(Guid objectPoolUid)
        {
            if (!_controller.ObjectPoolManager.Pools.Contains(objectPoolUid))
            {
                return(null);
            }

            Dictionary <string, Image> imgList = new Dictionary <string, Image>();

            foreach (ObjectClass obj in _controller.ObjectPoolManager.Pools[objectPoolUid].Objects)
            {
                if (obj.Image != null)
                {
                    Bitmap image = ImageUtility.CreateCenteredBitmap(obj.Image, 64, 64);
                    image.Tag = obj.Uid;
                    imgList.Add(obj.Name, image);
                }
            }

            return(imgList);
        }
Exemple #9
0
 private void OpenUserControlInNewTab <T>(string tabHeader) where T : UserControlPage
 {
     if (!UserControlIsAlreadyOpen <T>())
     {
         var userControl = (UserControlPage)Activator.CreateInstance <T>();
         var panel       = new FmDocumentPanel();
         panel.TabCaption = tabHeader;
         panel.Content    = userControl;
         if (!string.IsNullOrEmpty(userControl.ImagePath))
         {
             panel.CaptionImage = ImageUtility.CreateSvgImage(userControl.ImagePath);
         }
         panel.IsVisibleChanged += PanelOnIsVisibleChanged;
         MyDocumentGroup.Add(panel);
         panel.IsActive = true;
     }
     else
     {
         ActivateTheUserControl <T>();
     }
 }
        /// <summary>
        /// 生成一组套图
        /// </summary>
        /// <param name="fileIdentity"></param>
        /// <param name="newFileName"></param>
        public static void CreateImages(string fileIdentity, string newFileName)
        {
            if (ImageList.Count == 0)
            {
                return;
            }
            var result = FileUploadManager.FileExists(fileIdentity);

            if (!result)
            {
                return;
            }
            var bytes = FileUploadManager.GetFileData(fileIdentity);

            ImageList.ForEach(v => ThreadPool.QueueUserWorkItem(
                                  delegate
            {
                var imgageHelp = new ImageUtility();
                imgageHelp.ZoomAuto(bytes, (int)v.Value.Width, (int)v.Value.Height, true);
            }));
        }
        public void IndexFilesAsync(FileInfo[] imageFiles, System.ComponentModel.BackgroundWorker IndexBgWorker, object argument = null)
        {
            ConcurrentBag <RGBProjectionRecord> listOfRecords = new ConcurrentBag <RGBProjectionRecord>();

            RgbProjections projections    = null;
            int            totalFileCount = imageFiles.Length;

            int i = 0; long nextSequence;
            //In the class scope:
            Object lockMe = new Object();

            Parallel.ForEach(imageFiles, currentImageFile =>
            {
                var fi = currentImageFile;
                using (Bitmap bitmap = ImageUtility.ResizeBitmap(new Bitmap(fi.FullName), 100, 100))
                {
                    projections = new RgbProjections(ImageUtility.GetRgbProjections(bitmap));
                }

                lock (lockMe)
                {
                    nextSequence = i++;
                }

                RGBProjectionRecord record = new RGBProjectionRecord
                {
                    Id            = nextSequence,
                    ImageName     = fi.Name,
                    ImagePath     = fi.FullName,
                    RGBProjection = projections
                };

                listOfRecords.Add(record);

                IndexBgWorker.ReportProgress(i);
            });
            BinaryAlgoRepository <List <RGBProjectionRecord> > repo = new BinaryAlgoRepository <List <RGBProjectionRecord> >();

            repo.Save(listOfRecords.ToList());
        }
        public TopProfileSelectorView()
        {
            InitializeComponent();
            this.WhenActivated(dispose =>
            {
                this.WhenAnyFallback(x => x.ViewModel !.Configuration.SelectedProfile !.Nickname, string.Empty)
                .BindToStrict(this, x => x.ProfileNameBlock.Text)
                .DisposeWith(dispose);

                this.WhenAnyFallback(x => x.ViewModel !.Configuration.SelectedProfile !.Release, GameRelease.SkyrimSE)
                .ObserveOn(RxApp.TaskpoolScheduler)
                .Select(gameRelease =>
                {
                    return(ImageUtility.BitmapImageFromResource(ResourceConstants.AssemblyName, ResourceConstants.GetIcon(gameRelease)));
                })
                .ObserveOnGui()
                .BindToStrict(this, x => x.GameIconImage.Source)
                .DisposeWith(dispose);

                this.WhenAnyValue(x => x.ViewModel !.OpenProfilesPageCommand)
                .BindToStrict(this, x => x.OpenProfilesPageButton.Command)
                .DisposeWith(dispose);

                this.WhenAnyFallback(x => x.ViewModel !.Configuration.SelectedProfile !.UpdateProfileNugetVersionCommand)
                .Select(x => x as ICommand)
                .BindToStrict(this, x => x.UpdateButton.Command)
                .DisposeWith(dispose);
                this.WhenAnyFallback(x => x.ViewModel !.Configuration.SelectedProfile !.UpdateProfileNugetVersionCommand)
                .Select(x => x?.CanExecute ?? Observable.Return(false))
                .Switch()
                .Select(x => x ? Visibility.Visible : Visibility.Collapsed)
                .BindToStrict(this, x => x.UpdateButton.Visibility)
                .DisposeWith(dispose);

                this.WhenAnyValue(x => x.ViewModel !.InModal)
                .Select(x => !x)
                .BindToStrict(this, x => x.IsEnabled)
                .DisposeWith(dispose);
            });
        }
Exemple #13
0
    public ShopGoldData(Dictionary <string, object> rawData)
    {
        skuId  = JsonUtility.GetString(rawData, TAG_PACKAGE_NAME);
        goldId = JsonUtility.GetString(rawData, TAG_ITEM_ID);

        goldPrice = JsonUtility.GetFloat(rawData, TAG_PRICE);

        goldName = JsonUtility.GetString(rawData, TAG_ITEM_NAME);
        codeIAP  = JsonUtility.GetString(rawData, TAG_SKIN_NAME);
        if (codeIAP.Contains("no_ads") || codeIAP.Contains("xmas_bundle_2016"))
        {
            spriteIAP = ImageUtility.CreateSpriteFromObject(AssetManager.Instance.GetPrefabByKeyword(codeIAP));
            isSprite  = true;
        }
        else
        {
            // use 'codeIAP' to generate prefab and put under parent.
//			goldName = JsonUtility.GetInt(rawData, TAG_AMOUNT) + " GOLD";
            //spriteIAP = ImageUtility.CreateSpriteFromObject (AssetManager.Instance.GetPrefabByKeyword(codeIAP));
            isSprite = false;
        }
    }
Exemple #14
0
        /// <summary>
        /// renders the text based on the properties set
        /// </summary>
        public IImageAdapter Render()
        {
            IImageAdapter retVal = null;

            mFormattedText = new FormattedText(Text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, getTypeface(), FontSize, new System.Windows.Media.SolidColorBrush(_foreGround));
            int textWidth  = (int)mFormattedText.Width;
            int textHeight = (int)mFormattedText.Height;

            using (ImageUtility imageUtil = new ImageUtility(textWidth, textHeight))
            {
                imageUtil.GetSetPixelUnsafeBegin();
                int                stride            = textWidth * 4;
                byte[]             milBuffer         = new byte[stride * textHeight];
                RenderTargetBitmap renderTargeBitmap = (RenderTargetBitmap)RenderTargetBitmap.Create(textWidth, textHeight, 96, 96, PixelFormats.Bgra32, null, milBuffer, stride);
                {
                    Visual visual = new TypoDrawingVisual(mFormattedText, _backGround);
                    renderTargeBitmap.Render(visual);
                    renderTargeBitmap.CopyPixels(milBuffer, stride, 0);

                    int    index       = 0;
                    byte[] vscanBuffer = imageUtil.GetStreamBufferBGRA();
                    for (int y = 0; y < textHeight; y++)
                    {
                        for (int x = 0; x < textWidth; x++)
                        {
                            index = 4 * (y * textWidth + x);

                            vscanBuffer[index]     = milBuffer[index];
                            vscanBuffer[index + 1] = milBuffer[index + 1];
                            vscanBuffer[index + 2] = milBuffer[index + 2];
                            vscanBuffer[index + 3] = milBuffer[index + 3];
                        }
                    }
                }
                imageUtil.GetSetPixelUnsafeCommit();
                retVal = new ImageAdapter(imageUtil.Bitmap32Bits);
            }
            return(retVal);
        }
Exemple #15
0
        public async Task <IActionResult> Create([Bind("BlogId,Title,Abstract,Content,IsPublished")] Post post, IFormFile image) //delete the Id in a create when it is scaffolded like this
        {
            if (ModelState.IsValid)
            {
                post.Created = DateTime.Now;
                post.Updated = DateTime.Now;
                post.Slug    = Regex.Replace(post.Title.ToLower(), @"\s", "-");
                //Write Image
                if (image != null)
                {
                    post.FileName = image.FileName;
                    post.Image    = ImageUtility.EncodeImage(image);
                }

                _context.Add(post);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["BlogId"] = new SelectList(_context.Blogs, "Id", "Name", post.BlogId);
            return(View(post));
        }
Exemple #16
0
        /// <summary>
        /// Returns a bitmap of gray levels where the 'red-ness' of the original pixel determines the
        /// black/white value. Black pixels are farthest from red and white pixels are closest.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public Bitmap GetMaskImage(CIELab[] cieMap, int width, int height)
        {
            // get chromaticty distance map and min/max chromaticty distances

            double minCD, maxCD;

            double[] cdMap = GetChromaticityDistanceMap(cieMap, width, height, out minCD, out maxCD);

            // create a black image of the same size

            Bitmap mask = ImageUtility.CreateImage(width, height, PixelFormat.Format32bppPArgb, Color.FromArgb(255, 0, 0, 0));

            // process each pixel

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    // Mask value =
                    //
                    //							    maxCD - chromaticty distance [x,y]
                    //				Round( 255 *  ------------------------------------- )
                    //								          maxCD - minCD
                    //

                    double temp = (maxCD - cdMap[y * width + x]) / (maxCD - minCD);

                    int maskValue = (int)Math.Min(255.0, Math.Max(0.0, Math.Round(255.0 * temp)));

                    // set RGBA values

                    mask.SetPixel(x, y, Color.FromArgb(255, maskValue, maskValue, maskValue));
                }
            }

            // return mask image

            return(mask);
        }
        public void ShouldSaveToBlogImagesFolder()
        {
            _applicationEnvironment = new Mock<IApplicationEnvironment>();
            _formFile = new Mock<IFormFile>();

            _applicationEnvironment.Setup(x => x.ApplicationBasePath)
                .Returns(Mother.ApplicationBasePath);

            var someStream = new MemoryStream(100);

            _formFile.Setup(x => x.OpenReadStream()).Returns(someStream);

            var sut = new ImageUtility(_applicationEnvironment.Object);
            var image = sut.SaveImage(Mother.BlogImageFileName, Mother.ImageDescription, _formFile.Object);

            var actual = image.ImagePath;
            var expected = Mother.ApplicationBasePath + Mother.BlogImagePath;
            Console.WriteLine(expected);
            Console.WriteLine(actual);

            Assert.True(true);
        }
Exemple #18
0
        public static PageContent CreatePrintPageContentOxyPlot(Size pageSize, PlotModel plot, int width, int height, string header)
        {
            var page = new FixedPage {
                Width = pageSize.Width, Height = pageSize.Height
            };
            BitmapSource plotBitmapSrc = ImageUtility.ExportToBitmap(plot, width, height, OxyColors.Transparent, 96);

            System.Windows.Controls.Image img = new System.Windows.Controls.Image();
            img.Source = plotBitmapSrc;
            GroupBox grpBox = new GroupBox();

            grpBox.Header  = header;
            grpBox.Content = img;
            page.Children.Add(grpBox);
            page.Measure(pageSize);
            page.Arrange(new Rect(new Point(), pageSize));
            page.UpdateLayout();
            var firstPageContent = new PageContent();

            ((IAddChild)firstPageContent).AddChild(page);
            return(firstPageContent);
        }
Exemple #19
0
        private string ProcessPage(PDFFile pdf, string destDir, string guid, int pageIndex, int pageCount, int imgQuality)
        {
            string imgPaths = destDir + guid;//Guid.NewGuid().ToString();

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

            if (imgQuality == 0)
            {
                imgQuality = 100;
            }

            Bitmap oriBmp = pdf.GetPageImage(pageIndex, 96);

            Bitmap bmp = ImageUtility.CutAsBmp(oriBmp, CutBorderWidth, CutTopHeight, oriBmp.Width - 2 * CutBorderWidth, oriBmp.Height - CutTopHeight - CutBottomHeight);

            string result = string.Format(@"{0}\{1}.jpg", imgPaths, pageIndex);

            if (bmp.Width >= 700)
            {
                _imageHeight = (int)bmp.Height; // / 2;
                _imageWidth  = (int)bmp.Width;  // / 2;
                ImageUtility.ThumbAsJPG(bmp, result, _imageWidth, _imageHeight, imgQuality);

                //tempImg = bmp.GetThumbnailImage((int)bmp.Width / 2, (int)bmp.Height / 2, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                //tempImg.Save(string.Format(@"{0}\{1}-ori.jpg", imgPaths, i), System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                _imageHeight = bmp.Height;
                _imageWidth  = bmp.Width;

                ImageUtility.CompressAsJPG(bmp, result, imgQuality);
            }
            return(result);
            //bmp.Save(string.Format(@"{0}\{1}.jpg",imgPaths,i), System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        public void Run()
        {
            // TODO
            // Grab an image from a public URL and write a function that rescales the image to a desired format
            // The use of 3rd party plugins is permitted
            // For example: 100x80 (thumbnail) and 1200x1600 (preview)


            //image url for test
            string imgUrl = "https://www.gstatic.com/webp/gallery/5.jpg";
            //call method to get image from certain url
            var imagebytes = ImageUtility.GetImageFromURL(imgUrl);
            //new require size
            Size size = new Size(50, 50);
            //new require format
            //quality scale from 1 - 100
            ISupportedImageFormat format = new PngFormat {
                Quality = 70
            };
            //ISupportedImageFormat format = new JpegFormat { Quality = 70 };

            //call rescal image
            var newImagebytes = ImageUtility.RescaleImage(imagebytes, size, format);

            ////////////////////////////////////////////
            ///////////////test the resut////////////////
            ////////////////////////////////////////////
            //first bitmap
            Bitmap bitmapSrc = ImageUtility.ByteArrayToBitmap(imagebytes);
            //second bitmap
            Bitmap bitmapDist = ImageUtility.ByteArrayToBitmap(newImagebytes);


            //print the first image's length
            Console.WriteLine("length of first image {0}", bitmapSrc.RawFormat.ToString());
            //print the second image's length
            Console.WriteLine("length of second image {0}", bitmapDist.Size);
        }
        private async Task CacheNextTenSlides(
            string assetId,
            string serverUri,
            int width   = 80,
            int height  = 60,
            ulong index = 0)
        {
            var utility = new AssetUtility(GetStores());

            for (var i = index; i < index; i++)
            {
                var key = string.Format(cacheKeyFormat, assetId, serverUri, width, height, i).GetHashCode();

                var byteArray = _imagesCache.Get <byte[]>(key);
                if (byteArray != null)
                {
                    continue;
                }

                var thumbnail = await utility.GetSliceImageDataAsync(new AssetSliceRequest()
                {
                    AssetId    = assetId,
                    ServerUri  = serverUri,
                    Width      = width,
                    Height     = height,
                    FragmentId = i,
                });

                if (thumbnail == null || thumbnail.Length == 0)
                {
                    continue;
                }

                var data = ImageUtility.ResizeImage(thumbnail, width, height);

                _imagesCache.Set(key, data, TimeSpan.FromSeconds(CacheInterval));
            }
        }
Exemple #22
0
        public async Task <IActionResult> Edit(int id, [Bind("BlogId,Title,Abstract,Content,IsPublished")] Post post, IFormFile image) //add IformFile image
        {
            if (id != post.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    post.Updated = DateTime.Now;

                    if (image != null)                                   //add line
                    {
                        post.FileName = image.FileName;                  //add line
                        post.Image    = ImageUtility.EncodeImage(image); //add line
                    }

                    _context.Update(post);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PostExists(post.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["BlogId"] = new SelectList(_context.Blogs, "Id", "Id", post.BlogId);
            return(View(post));
        }
Exemple #23
0
        /// <summary>
        /// Return the color on the screen at a certain point
        /// </summary>
        public System.Windows.Media.Color getColorAtPoint(int X, int Y)
        {

            this.screen  = ImageUtility.CaptureScreen(internalHWnd, true);

            System.Drawing.Color myColor = System.Drawing.Color.FromArgb(0x00, 0x00, 0x00, 0x00);

            try
            {
                myColor = screen.GetPixel(X,Y);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                logComment(" Error in ImageUtils: " + ex); return Colors.Black;
            }

            logComment(" Color at position " + X.ToString() + " " + Y.ToString() + " was " + myColor.A.ToString() + " " + myColor.R.ToString()+ " " + myColor.G.ToString()+ " " + myColor.B.ToString());

            System.Windows.Media.Color returnColor = System.Windows.Media.Color.FromArgb(myColor.A,myColor.R,myColor.G,myColor.B);

            return returnColor;
         
        }
Exemple #24
0
        // GET: Posts/Delete/5
        public async Task <IActionResult> Delete(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var post = await _context.Posts
                       .Include(p => p.Blogs)
                       .FirstOrDefaultAsync(m => m.Id == id);

            if (post == null)
            {
                return(NotFound());
            }

            if (post.Image != null && post.Image.Length > 0)
            {
                ViewData["Image"] = ImageUtility.DecodeImage(post);
            }

            return(View(post));
        }
Exemple #25
0
 protected void ImageRead(PipeRequest request, Pipe pipe)
 {
     if (Active)
     {
         _imageRequest = null;
         try
         {
             if (request.Result.IsNative)
             {
                 LoadedImage = ImageUtility.BitmapImageFromBytes(request.Result.AsByteArray);
             }
             else
             {
                 using (Stream stream = request.Result.OpenStream())
                     LoadedImage = ImageUtility.BitmapImageFromStream(stream);
             }
         }
         catch
         {
             LoadedImage = ImageUtility.GetErrorImage();
         }
     }
 }
Exemple #26
0
        /// <summary>
        /// Prepares an image adapter by hosting Xaml document in a Window. Screen shot
        /// is take waitTime after the window is shown.
        /// </summary>
        /// <param name="filename">xaml file name</param>
        /// <param name="width">width of the window</param>
        /// <param name="height">height of the window</param>
        /// <returns>Image Adapter</returns>
        public static IImageAdapter PrepareXamlImageAdapterInWindow(String filename, double width, double height)
        {
            System.Windows.Window window = new System.Windows.Window();

            window.Width           = width;
            window.Height          = height;
            window.Topmost         = true;
            window.WindowStyle     = System.Windows.WindowStyle.None;
            window.BorderThickness = new System.Windows.Thickness(0);
            window.ResizeMode      = System.Windows.ResizeMode.NoResize;

            //move window off the leftmost so it would be under the mouse.
            window.Left = 50;
            window.Top  = 50;

            // parse content from xaml file.
            FileStream xamlStream = File.OpenRead(filename);

            System.Windows.FrameworkElement content = XamlReader.Load(xamlStream) as System.Windows.FrameworkElement;
            window.Content = content;


            //using the local resource dictionary to avoid test noise due to varying system themes.
            AddLocalResourceDictionary(window, localResourceDictionaryPath);

            window.Show();

            //scale down to default system dpi to use same master for different dpi.
            DpiScalingHelper.ScaleWindowToFixedDpi(window, defaultSystemDpi, defaultSystemDpi);

            DispatcherHelper.DoEvents(waitTime.Milliseconds);

            Bitmap       capture        = ImageUtility.CaptureElement(window);
            ImageAdapter captureAdapter = new ImageAdapter(capture);

            return(captureAdapter);
        }
Exemple #27
0
        /// <summary>
        /// Save the Package after compare model occured
        /// </summary>
        /// <param name="packagePath"></param>
        public void Save(string packagePath)
        {
            CheckPath(packagePath);
            if (Image == null)
            {
                throw new RenderingVerificationException("Cannot save: No image associated with this ModelManager");
            }

            Bitmap  bmp     = null;
            Package package = null;

            if (_descriptorManager._isDirty)
            {
                Analyze();
            }
            try
            {
                package = Package.Create(packagePath, false);
                bmp     = ImageUtility.ToBitmap(Image);
                package.MasterBitmap   = bmp;
                package.MasterModel    = _descriptorManager.Serialize();
                package.PackageCompare = PackageCompareTypes.ModelAnalytical;
                package.Save();
            }
            finally
            {
                if (package != null)
                {
                    package.Dispose(); package = null;
                }
                if (bmp != null)
                {
                    bmp.Dispose(); bmp = null;
                }
            }
        }
Exemple #28
0
        private MediaResource MakeContributionImage(User createdByUser, ImageUtility image, List <ImageCreationTask> imageCreationTasks, MediaResourceCreateCommand command)
        {
            IDictionary <string, object> exifData = image.GetExifData();
            ImageDimensions imageDimensions       = image.GetDimensions();

            var metadata = new Dictionary <string, string>();

            if (exifData.Count > 0)
            {
                metadata = GetImageExifMetadata(exifData, createdByUser.Timezone);
            }

            return(_mediaResourceFactory.MakeContributionImage(
                       command.Key,
                       createdByUser,
                       command.UploadedOn,
                       command.FileName,
                       imageDimensions,
                       command.FileStream.Length,
                       exifData,
                       image.GetMimeType(),
                       metadata,
                       imageCreationTasks));
        }
        public TopProfileSelectorView()
        {
            InitializeComponent();
            this.WhenActivated(dispose =>
            {
                this.WhenAnyFallback(x => x.ViewModel !.Configuration.SelectedProfile !.Nickname, string.Empty)
                .BindToStrict(this, x => x.ProfileNameBlock.Text)
                .DisposeWith(dispose);

                this.WhenAnyFallback(x => x.ViewModel !.Configuration.SelectedProfile !.Release, GameRelease.SkyrimSE)
                .ObserveOn(RxApp.TaskpoolScheduler)
                .Select(gameRelease =>
                {
                    return(ImageUtility.BitmapImageFromResource(ResourceConstants.AssemblyName, ResourceConstants.GetIcon(gameRelease)));
                })
                .ObserveOnGui()
                .BindToStrict(this, x => x.GameIconImage.Source)
                .DisposeWith(dispose);

                this.WhenAnyValue(x => x.ViewModel !.OpenProfilesPageCommand)
                .BindToStrict(this, x => x.OpenProfilesPageButton.Command)
                .DisposeWith(dispose);
            });
        }
        public static void CreateImagesByNewegg(string fileIdentity, string newFileName, bool isNeedWatermark)
        {
            if (ImageList.Count == 0)
            {
                return;
            }
            var result = FileUploadManager.FileExists(fileIdentity);

            if (!result)
            {
                return;
            }
            var bytes = FileUploadManager.GetFileData(fileIdentity);

            ImageList.ForEach(v => ThreadPool.QueueUserWorkItem(
                                  delegate
            {
                var imageHelp = new ImageUtility {
                    FileName = newFileName, MidFilepath = v.Key.ToString()
                };
                imageHelp.Upload += Upload;
                imageHelp.ZoomAuto(bytes, (int)v.Value.Width, (int)v.Value.Height, isNeedWatermark);
            }));
        }
        public ActionResult GetImage(int productGroupID, int width, int height)
        {
            using (var unit = GetUnitOfWork())
            {
                var    imagePath = unit.Service <ProductGroup>().Get(c => c.ProductGroupID == productGroupID).ImagePath;
                string extension = string.Empty;

                Image img = null;

                if (string.IsNullOrEmpty(imagePath))
                {
                    img       = Image.FromFile(Request.PhysicalApplicationPath + @"Content\images\Icons\FileTypeIcons\unknown.png");
                    extension = "png";
                }
                else
                {
                    img       = Image.FromFile(Path.Combine(ConfigurationManager.AppSettings["FTPMediaDirectory"], ConfigurationManager.AppSettings["FTPProductGroupMediaPath"], imagePath));
                    extension = imagePath.Substring(imagePath.LastIndexOf('.') + 1);
                }

                var im = ImageUtility.ResizeImage(img, height, width);
                return(new ImageResult(im, extension));
            }
        }
Exemple #32
0
 private PointF ImageUV2Client( ImageUtility.float2 _Position )
 {
     RectangleF	ImageRect = ImageClientRect();
     //			return new PointF( ImageRect.X + _Position.x * ImageRect.Width, ImageRect.Y + _Position.y * ImageRect.Height );
     //			return new PointF( ImageRect.X + _Position.x * ImageRect.Height, ImageRect.Y + _Position.y * ImageRect.Height );
     return new PointF( 0.5f * (Width - ImageRect.Height) + _Position.x * ImageRect.Height, ImageRect.Y + _Position.y * ImageRect.Height );
 }
        private MediaResource MakeContributionImage(User createdByUser, ImageUtility image, List<ImageCreationTask> imageCreationTasks, MediaResourceCreateCommand command)
        {
            IDictionary<string, object> exifData = image.GetExifData();
            ImageDimensions imageDimensions = image.GetDimensions();

            var metadata = new Dictionary<string, string>();

            if (exifData.Count > 0)
            {
                metadata = GetImageExifMetadata(exifData, createdByUser.Timezone);
            }

            return _mediaResourceFactory.MakeContributionImage(
                command.Key,
                createdByUser,
                command.UploadedOn,
                command.FileName,
                imageDimensions,
                command.FileStream.Length,
                exifData,
                image.GetMimeType(),
                metadata,
                imageCreationTasks);
        }
        private MediaResource MakeBackgroundImage(User createdByUser, ImageUtility image, List<ImageCreationTask> imageCreationTasks, MediaResourceCreateCommand command)
        {
            ImageDimensions imageDimensions = image.GetDimensions();

            return _mediaResourceFactory.MakeBackgroundImage(
                command.Key,
                createdByUser,
                command.UploadedOn,
                command.FileName,
                imageDimensions,
                image.GetMimeType(),
                imageCreationTasks);
        }
Exemple #35
0
        private unsafe void UpdateProgress( ImageUtility.ImageFile _image, uint Y, bool _Bias )
        {
            const uint	REFRESH_EVERY_N_SCANLINES = 4;
            if ( Y == 0 || (Y & (REFRESH_EVERY_N_SCANLINES-1)) != 0 )
                return;

            viewportPanelResult.Image = _image;
            Application.DoEvents();
        }
Exemple #36
0
 protected ImageUtility.float2[] BuildClipVertices( ImageUtility.float2 _Center, ImageUtility.float2 _HalfSize, ImageUtility.float2 _AxisX, ImageUtility.float2 _AxisY )
 {
     return new ImageUtility.float2[4] {
                     _Center - _HalfSize.x * _AxisX + _HalfSize.y * _AxisY,
                     _Center + _HalfSize.x * _AxisX + _HalfSize.y * _AxisY,
                     _Center - _HalfSize.x * _AxisX - _HalfSize.y * _AxisY,
                     _Center + _HalfSize.x * _AxisX - _HalfSize.y * _AxisY,
                 };
 }
Exemple #37
0
        /// <summary>
        /// Integrates the luminance of the pixels in a given circle selected by the user
        /// </summary>
        /// <param name="_X"></param>
        /// <param name="_Y"></param>
        /// <param name="_Radius"></param>
        /// <param name="_PercentOfBlackValues"></param>
        /// <param name="_HasSaturatedValues">Returns the percentage of encountered saturated values. 0 is okay, more means the probe shouldn't be used</param>
        /// <returns></returns>
        private ImageUtility.float3 IntegrateLuminance( float _X, float _Y, float _Radius, out ImageUtility.float3 _MinXYZ, out ImageUtility.float3 _MaxXYZ, out float _PercentOfBlackValues, out float _PercentOfSaturatedValues )
        {
            float	Radius = Math.Max( 1, _Radius * m_BitmapXYZ.Width );
            float	CenterX = _X * m_BitmapXYZ.Width;
            float	CenterY = _Y * m_BitmapXYZ.Height;
            float	SqRadius = Radius*Radius;

            int		X0 = Math.Max( 0, Math.Min( m_BitmapXYZ.Width-1, (int) Math.Floor( CenterX - Radius ) ) );
            int		X1 = Math.Max( 0, Math.Min( m_BitmapXYZ.Width-1, (int) Math.Ceiling( CenterX + Radius ) ) );
            int		Y0 = Math.Max( 0, Math.Min( m_BitmapXYZ.Height-1, (int) Math.Floor( CenterY - Radius ) ) );
            int		Y1 = Math.Max( 0, Math.Min( m_BitmapXYZ.Height-1, (int) Math.Ceiling( CenterY + Radius ) ) );

            const float	SMOOTHSTEP_MAX_RADIUS = 0.2f;	// We reach max weight 1 at 20% of the border of the circle

            bool	ApplySpatialCorrection = checkBoxSpatialLuminanceCorrection.Checked;

            int		TotalBlackValuesCount = 0;
            int		TotalSaturatedValuesCount = 0;
            int		TotalValuesCount = 0;
            ImageUtility.float3	SumXYZ = new ImageUtility.float3( 0, 0, 0 );
            _MinXYZ = new ImageUtility.float3( 0, +float.MaxValue, 0 );
            _MaxXYZ = new ImageUtility.float3( 0, 0, 0 );
            float	SumWeights = 0.0f;
            for ( int Y=Y0; Y < Y1; Y++ )
                for ( int X=X0; X < X1; X++ )
                {
                    float	SqR = (X-CenterX)*(X-CenterX) + (Y-CenterY)*(Y-CenterY);
                    if ( SqR > SqRadius )
                        continue;

                    float	r = (float) Math.Sqrt( SqR ) / Radius;	// Nomalized radius
            //					float	Weight = Math.Min( 1.0f, floatTrackbarControl1.Value * (float) Math.Exp( -floatTrackbarControl2.Value * r ) );

                    float	x = Math.Max( 0.0f, Math.Min( 1.0f, (1.0f - r) / SMOOTHSTEP_MAX_RADIUS ) );
                    float	Weight = x*x*(3.0f - 2.0f*x);

            //DEBUG					m_BitmapXYZ.ContentXYZ[X,Y].y = Weight;
                    ImageUtility.float3	XYZ = (ImageUtility.float3) m_BitmapXYZ.ContentXYZ[X,Y];
                    if ( ApplySpatialCorrection )
                    {
                        ImageUtility.float3	xyY = ImageUtility.ColorProfile.XYZ2xyY( XYZ );
                        xyY.z *= m_CalibrationDatabase.GetSpatialLuminanceCorrectionFactor( (float) X / m_BitmapXYZ.Width, (float) Y / m_BitmapXYZ.Height );
                        XYZ = ImageUtility.ColorProfile.xyY2XYZ( xyY );
                    }

                    if ( XYZ.y < 0.001f )
                        TotalBlackValuesCount++;		// Warning!
                    if ( XYZ.y > 0.999f )
                        TotalSaturatedValuesCount++;	// Warning!
                    TotalValuesCount++;

                    if ( XYZ.y < _MinXYZ.y )
                        _MinXYZ = XYZ;
                    if ( XYZ.y > _MaxXYZ.y )
                        _MaxXYZ = XYZ;
                    SumXYZ += Weight * XYZ;
                    SumWeights += Weight;
                }

            //DEBUG			RebuildImage();

            _PercentOfBlackValues = (float) TotalBlackValuesCount / TotalValuesCount;
            _PercentOfSaturatedValues = (float) TotalSaturatedValuesCount / TotalValuesCount;

            SumXYZ = (1.0f/SumWeights) * SumXYZ;
            return SumXYZ;
        }
 private PointF ImageUV2Client( ImageUtility.float2 _Position )
 {
     RectangleF	ImageRect = ImageClientRect();
     return new PointF( _Position.x * ImageRect.Width + ImageRect.X, _Position.y * ImageRect.Height + ImageRect.Y );
 }
        /// <summary>
        /// Computes the statistical mode of the values
        /// </summary>
        /// <param name="_Values"></param>
        /// <returns></returns>
        private ImageUtility.float3 ComputeMode( ImageUtility.float3[] _Values )
        {
            int		COUNT = _Values.Length;

            // The idea is simply to discretize the set of values and count the ones that are the most represented
            float	Start = _Values[0].y;
            float	End = _Values[_Values.Length-1].y;
            float	IntervalLength = 0.0f, Normalizer = 0.0f;
            if ( Math.Abs( End - Start ) > 1e-6f )
            {
                IntervalLength = (End - Start) / COUNT;
                Normalizer = 1.0f / IntervalLength;
            }

            // Fill bins
            int[]		Bins = new int[COUNT];
            ImageUtility.float3[]	BinsSum = new ImageUtility.float3[COUNT];
            for ( int i=0; i < _Values.Length; i++ )
            {
                int	BinIndex = Math.Min( COUNT-1, (int) Math.Floor( (_Values[i].y - Start) * Normalizer ) );
                Bins[BinIndex]++;
                BinsSum[BinIndex] += _Values[i];
            }

            // Find the one that contains most values (yep, that's the mode!)
            int		MaxValuesCount = 0;
            int		MaxValuesBinIndex = -1;
            for ( int BinIndex=0; BinIndex < COUNT; BinIndex++ )
                if ( Bins[BinIndex] > MaxValuesCount )
                {	// More filled up bin discovered!
                    MaxValuesCount = Bins[BinIndex];
                    MaxValuesBinIndex = BinIndex;
                }

            ImageUtility.float3	ModeXYZ = (1.0f / MaxValuesCount) * BinsSum[MaxValuesBinIndex];
            return ModeXYZ;
        }
 /// <summary>
 /// Computes the statistical mean of the values
 /// </summary>
 /// <param name="_Values"></param>
 /// <returns></returns>
 private ImageUtility.float3 ComputeMean( ImageUtility.float3[] _Values )
 {
     ImageUtility.float3	AvgXYZ = new ImageUtility.float3( 0, 0, 0 );
     for ( int i=0; i < _Values.Length; i++ )
         AvgXYZ += _Values[i];
     AvgXYZ = (1.0f / _Values.Length) * AvgXYZ;
     return AvgXYZ;
 }
        /// <summary>
        /// Builds a swatch bitmap
        /// </summary>
        /// <param name="_Width"></param>
        /// <param name="_Height"></param>
        /// <param name="_xyY"></param>
        /// <returns></returns>
        private ImageUtility.Bitmap BuildSwatch( int _Width, int _Height, ImageUtility.float3 _xyY )
        {
            ImageUtility.Bitmap	Result = new ImageUtility.Bitmap( _Width, _Height, new ImageUtility.ColorProfile( ImageUtility.ColorProfile.STANDARD_PROFILE.sRGB ) );
            ImageUtility.float4	XYZ = new ImageUtility.float4( ImageUtility.ColorProfile.xyY2XYZ( _xyY ), 1.0f );
            for ( int Y=0; Y < _Height; Y++ )
                for ( int X=0; X < _Width; X++ )
                    Result.ContentXYZ[X,Y] = XYZ;

            return Result;
        }
        /// <summary>
        /// Computes the average color within a rectangle in UV space
        /// </summary>
        /// <param name="_TopLeft">The top left corner (in UV space) of the rectangle to sample</param>
        /// <param name="_BottomRight">The bottom right corner (in UV space) of the rectangle to sample</param>
        /// <returns>The average xyY color</returns>
        public ImageUtility.float3 ComputeAverageSwatchColor( ImageUtility.float2 _TopLeft, ImageUtility.float2 _BottomRight )
        {
            // Average xyY values in the specified rectangle
            int		X0 = Math.Max( 0, Math.Min( m_Texture.Width-1, (int) Math.Floor( _TopLeft.x * m_Texture.Width ) ) );
            int		Y0 = Math.Max( 0, Math.Min( m_Texture.Height-1, (int) Math.Floor( _TopLeft.y * m_Texture.Height ) ) );
            int		X1 = Math.Min( m_Texture.Width, Math.Max( X0+1, (int) Math.Floor( _BottomRight.x * m_Texture.Width ) ) );
            int		Y1 = Math.Min( m_Texture.Height, Math.Max( Y0+1, (int) Math.Floor( _BottomRight.y * m_Texture.Height ) ) );
            int		W = X1 - X0;
            int		H = Y1 - Y0;

            ImageUtility.float4	AverageXYZ = new ImageUtility.float4( 0, 0, 0, 0 );
            for ( int Y=Y0; Y < Y1; Y++ )
                for ( int X=X0; X < X1; X++ )
                {
                    ImageUtility.float4	XYZ = m_Texture.ContentXYZ[X,Y];
                    AverageXYZ += XYZ;
                }
            AverageXYZ = (1.0f / (W*H)) * AverageXYZ;

            ImageUtility.float3	xyY =  ImageUtility.ColorProfile.XYZ2xyY( (ImageUtility.float3) AverageXYZ );
            return xyY;
        }
        /// <summary>
        /// Captures the calibrated texture
        /// </summary>
        /// <param name="_Source">The source image to capture</param>
        /// <param name="_Database">Database to perform proper calibration</param>
        /// <param name="_Parms">Parameters for the capture</param>
        public void Capture( ImageUtility.Bitmap _Source, CameraCalibrationDatabase _Database, CaptureParms _Parms )
        {
            if ( _Source == null )
                throw new Exception( "Invalid source bitmap to build texture from!" );
            if ( _Database == null )
                throw new Exception( "Invalid calibration database found in parameters!" );
            if ( _Parms == null )
                throw new Exception( "Invalid calibration parameters!" );
            if ( m_SwatchWidth <= 0 || m_SwatchHeight <= 0 )
                throw new Exception( "Invalid swatch size! Must be > 0!" );

            // Save parameters as they're associated to this texture
            m_CaptureParameters = _Parms;
            m_WhiteReflectanceReference = _Database.WhiteReflectanceReference;
            m_WhiteReflectanceCorrectionFactor = _Database.WhiteReflectanceCorrectionFactor;
            m_SpatialCorrectionEnabled = _Database.WhiteReferenceImage != null;

            //////////////////////////////////////////////////////////////////////////
            // Setup the database to find the most appropriate calibration data for our image infos
            _Database.PrepareCalibrationFor( _Parms.ISOSpeed, _Parms.ShutterSpeed, _Parms.Aperture );

            //////////////////////////////////////////////////////////////////////////
            // Build target texture
            ImageUtility.float4	AvgXYZ = new ImageUtility.float4( 0, 0, 0, 0 );
            //DEBUG
            // float	MinLuminance_Raw = float.MaxValue;
            // float	MaxLuminance_Raw = -float.MaxValue;

            const int	EXTREME_VALUES_COUNT = 100;
            ImageUtility.float3[]	ArrayMin = new ImageUtility.float3[EXTREME_VALUES_COUNT];
            ImageUtility.float3[]	ArrayMax = new ImageUtility.float3[EXTREME_VALUES_COUNT];
            for ( int i=0; i < EXTREME_VALUES_COUNT; i++ )
            {
                ArrayMin[i] = new ImageUtility.float3( 0, 1, 0 );
                ArrayMax[i] = new ImageUtility.float3( 0, 0, 0 );
            }

            if ( _Parms.CropSource )
            {
                float	fImageWidth = 2.0f * _Parms.CropRectangleHalfSize.x * _Source.Height;
                float	fImageHeight = 2.0f * _Parms.CropRectangleHalfSize.y * _Source.Height;
                int		W = (int) Math.Floor( fImageWidth );
                int		H = (int) Math.Floor( fImageHeight );

                ImageUtility.float2	AxisX = new ImageUtility.float2( (float) Math.Cos( _Parms.CropRectangleRotation ), -(float) Math.Sin( _Parms.CropRectangleRotation ) );
                ImageUtility.float2	AxisY = new ImageUtility.float2( (float) Math.Sin( _Parms.CropRectangleRotation ), (float) Math.Cos( _Parms.CropRectangleRotation ) );

                ImageUtility.float2	TopLeftCorner = new ImageUtility.float2( 0.5f * (_Source.Width - _Source.Height) + _Parms.CropRectangleCenter.x * _Source.Height, _Source.Height * _Parms.CropRectangleCenter.y )
                                                  + _Source.Height * (-_Parms.CropRectangleHalfSize.x * AxisX - _Parms.CropRectangleHalfSize.y * AxisY);

                m_Texture = new ImageUtility.Bitmap( W, H, new ImageUtility.ColorProfile( ImageUtility.ColorProfile.STANDARD_PROFILE.sRGB ) );
                ImageUtility.float4	XYZ;
                ImageUtility.float3	ShortXYZ;
                ImageUtility.float3	xyY;

                ImageUtility.float2	CurrentScanlinePixel = TopLeftCorner + 0.5f * (fImageWidth - W) * AxisX + 0.5f * (fImageHeight - H) * AxisY;
                if ( Math.Abs( _Parms.CropRectangleRotation ) < 1e-6f )
                {	// Use integer pixels to avoid attenuated values due to bilinear filtering
                    CurrentScanlinePixel.x = (float) Math.Floor( CurrentScanlinePixel.x );
                    CurrentScanlinePixel.y = (float) Math.Floor( CurrentScanlinePixel.y );
                }
                for ( int Y=0; Y < H; Y++ )
                {
                    ImageUtility.float2	CurrentPixel = CurrentScanlinePixel;
                    for ( int X=0; X < W; X++ )
                    {
                        float	U = CurrentPixel.x / _Source.Width;
                        float	V = CurrentPixel.y / _Source.Height;

                        XYZ = _Source.BilinearSample( CurrentPixel.x, CurrentPixel.y );

            //DEBUG
            // float	L = XYZ.y * _Database.GetSpatialLuminanceCorrectionFactor( U, V );
            // if ( L < MinLuminance_Raw )
            // 	MinLuminance_Raw = L;
            // if ( L > MaxLuminance_Raw )
            // 	MaxLuminance_Raw = L;
            //DEBUG

                        xyY = ImageUtility.ColorProfile.XYZ2xyY( (ImageUtility.float3) XYZ );
                        xyY = _Database.CalibrateWithSpatialCorrection( U, V, xyY );	// Apply luminance calibration
                        ShortXYZ = ImageUtility.ColorProfile.xyY2XYZ( xyY );
                        XYZ = new ImageUtility.float4( ShortXYZ, XYZ.w );
                        m_Texture.ContentXYZ[X,Y] = XYZ;

                        // Update min/max/avg values
                        InsertMinMax( ShortXYZ, ArrayMin, ArrayMax, EXTREME_VALUES_COUNT );
                        AvgXYZ += XYZ;

                        CurrentPixel += AxisX;
                    }
                    CurrentScanlinePixel += AxisY;
                }
            }
            else
            {	// Simple texture copy, with luminance calibration
                m_Texture = new ImageUtility.Bitmap( _Source.Width, _Source.Height, new ImageUtility.ColorProfile( ImageUtility.ColorProfile.STANDARD_PROFILE.sRGB ) );
                ImageUtility.float4	XYZ;
                ImageUtility.float3	ShortXYZ;
                ImageUtility.float3	xyY;

                int	W = m_Texture.Width;
                int	H = m_Texture.Height;

                int	X0 = 0;
                int	X1 = W;
                int	Y0 = 0;
                int	Y1 = H;

            //DEBUG
            // X0 = 1088; Y0 = 764;
            // X1 = X0 + 1100; Y1 = Y0 + 632;

                for ( int Y=Y0; Y < Y1; Y++ )
                {
                    float	V = (float) Y / H;
                    for ( int X=X0; X < X1; X++ )
                    {
                        float	U = (float) X / W;

                        XYZ = _Source.ContentXYZ[X,Y];

            //DEBUG
            // float	L = XYZ.y * _Database.GetSpatialLuminanceCorrectionFactor( U, V );
            // if ( L < MinLuminance_Raw )
            // 	MinLuminance_Raw = L;
            // if ( L > MaxLuminance_Raw )
            // 	MaxLuminance_Raw = L;
            //DEBUG

                        xyY = ImageUtility.ColorProfile.XYZ2xyY( (ImageUtility.float3) XYZ );
                        xyY = _Database.CalibrateWithSpatialCorrection( U, V, xyY );	// Apply luminance calibration
                        ShortXYZ = ImageUtility.ColorProfile.xyY2XYZ( xyY );
                        XYZ = new ImageUtility.float4( ShortXYZ, XYZ.w );
                        m_Texture.ContentXYZ[X,Y] = XYZ;

                        // Update min/max/avg values
                        InsertMinMax( ShortXYZ, ArrayMin, ArrayMax, EXTREME_VALUES_COUNT );
                        AvgXYZ += XYZ;
                    }
                }
            }

            // Normalize average swatch color
            float	Normalizer = 1.0f / (m_Texture.Width*m_Texture.Height);
            ImageUtility.float3	avgxyY = ImageUtility.ColorProfile.XYZ2xyY( Normalizer * ((ImageUtility.float3) AvgXYZ) );
            m_SwatchAvg.xyY = avgxyY;

            // Compute min & max using statistical norm
             			ImageUtility.float3	BestXYZ_Min;
             			ImageUtility.float3	BestXYZ_Max;

            if ( _Parms.UseModeInsteadOfMean )
            {	// Use mode
                BestXYZ_Min = ComputeMode( ArrayMin );
                BestXYZ_Max = ComputeMode( ArrayMax );
            }
            else
            {	// Use mean
             				BestXYZ_Min = ComputeMean( ArrayMin );
             				BestXYZ_Max = ComputeMean( ArrayMax );
            }
            m_SwatchMin.xyY = ImageUtility.ColorProfile.XYZ2xyY( BestXYZ_Min );
            m_SwatchMax.xyY = ImageUtility.ColorProfile.XYZ2xyY( BestXYZ_Max );

            m_SwatchMin.Texture = BuildSwatch( m_SwatchWidth, m_SwatchHeight, m_SwatchMin.xyY );
            m_SwatchMax.Texture = BuildSwatch( m_SwatchWidth, m_SwatchHeight, m_SwatchMax.xyY );
            m_SwatchAvg.Texture = BuildSwatch( m_SwatchWidth, m_SwatchHeight, m_SwatchAvg.xyY );

            // Rebuild custom swatches
            foreach ( CustomSwatch CS in m_CustomSwatches )
                CS.Texture = BuildSwatch( m_SwatchWidth, m_SwatchHeight, CS.xyY );

            //////////////////////////////////////////////////////////////////////////
            // Feed some purely informational shot infos to the main texture, probably won't be saved anyway...
            m_Texture.HasValidShotInfo = true;
            m_Texture.ISOSpeed = _Parms.ISOSpeed;
            m_Texture.ShutterSpeed = _Parms.ShutterSpeed;
            m_Texture.Aperture = _Parms.Aperture;
        }
Exemple #44
0
 /// <summary>
 /// Sets the crop rectangle to a specific value
 /// </summary>
 public void SetCropRectangle( ImageUtility.float2 _Center, ImageUtility.float2 _HalfSize, float _Rotation )
 {
     m_CropRectangleIsDefault = false;
     m_CropRectangleCenter = _Center;
     m_CropRectangleHalfSize = _HalfSize;
     m_CropRectangleRotation = _Rotation;
     Invalidate();
 }
        /// <summary>
        /// Calibrates a raw luminance value with spatial luminance correction
        /// </summary>
        /// <param name="_U">The U coordinate in the image (U=X/Width)</param>
        /// <param name="_V">The V coordinate in the image (V=Y/Height)</param>
        /// <param name="_Luminance">The uncalibrated value</param>
        /// <returns>The calibrated reflectance value</returns>
        /// <remarks>Typically, you start from a RAW XYZ value that you convert to xyY, pass it to this method
        /// and replace it into your orignal xyY, convert back to XYZ and voilà!</remarks>
        public ImageUtility.float3 CalibrateWithSpatialCorrection( float _U, float _V, ImageUtility.float3 _xyY )
        {
            if ( m_RootNode == null )
                throw new Exception( "Calibration grid hasn't been built: did you provide a valid database path? Does the path contain camera calibration data?" );
            if ( m_InterpolatedCalibration == null )
                throw new Exception( "Calibration grid hasn't been prepared for calibration: did you call the PrepareCalibrationFor() method?" );

            float	CorrectionFactor = m_WhiteReflectanceCorrectionFactor;
                    CorrectionFactor *= GetSpatialLuminanceCorrectionFactor( _U, _V );	// Apply spatial correction

            float	Reflectance = m_InterpolatedCalibration.Calibrate( CorrectionFactor * _xyY.z );
            _xyY.z = Reflectance;
            if ( m_DoWhiteBalance )
            {
                ImageUtility.float3	XYZ = ImageUtility.ColorProfile.xyY2XYZ( _xyY );
                XYZ *= m_WhiteBalanceXYZ;
                _xyY = ImageUtility.ColorProfile.XYZ2xyY( XYZ );
            }
            return _xyY;
        }
        private void InsertMinMax( ImageUtility.float3 v, ImageUtility.float3[] _Min, ImageUtility.float3[] _Max, int _Length )
        {
            if ( v.y < _Min[_Length-1].y )
            {	// We're sure we're good enough for that array!
                for ( int i=0; i < _Length; i++ )
                    if ( v.y < _Min[i].y )
                    {	// Insert here
                        if ( i != _Length-1 )
                            Array.Copy( _Min, i, _Min, i+1, _Length-i-1 );
                        _Min[i] = v;
                        break;
                    }
            }

            if ( v.y > _Max[_Length-1].y )
            {	// We're sure we're good enough for that array!
                for ( int i=0; i < _Length; i++ )
                    if ( v.y > _Max[i].y )
                    {	// Insert here
                        if ( i != _Length-1 )
                            Array.Copy( _Max, i, _Max, i+1, _Length-i-1 );
                        _Max[i] = v;
                        break;
                    }
            }
        }
Exemple #47
0
 private PointF ImageUV2Client_NoSquareAspectRatio( ImageUtility.float2 _Position )
 {
     RectangleF	ImageRect = ImageClientRect();
     return new PointF( ImageRect.X + _Position.x * ImageRect.Width, ImageRect.Y + _Position.y * ImageRect.Height );
 }
 /// <summary>
 /// Saves a texture to disk
 /// </summary>
 /// <param name="_Texture"></param>
 /// <param name="_FileName"></param>
 /// <param name="_FileType"></param>
 /// <param name="_Format"></param>
 private void SaveImage( ImageUtility.Bitmap _Texture, System.IO.FileInfo _FileName, ImageUtility.Bitmap.FILE_TYPE _FileType, ImageUtility.Bitmap.FORMAT_FLAGS _Format )
 {
     using ( System.IO.FileStream S = _FileName.Create() )
         _Texture.Save( S, _FileType, _Format, null );
 }
Exemple #49
0
        /// <summary>
        /// Integrates luminance for the provided probe by sampling luminances in the provided disc
        /// </summary>
        /// <param name="_Probe"></param>
        /// <param name="_Center"></param>
        /// <param name="_Radius"></param>
        private void IntegrateLuminance( CameraCalibration.Probe _Probe, ImageUtility.float2 _Center, float _Radius )
        {
            ImageUtility.float3	MinXYZ, MaxXYZ;
            float	BlackValues, SaturatedValues;
            ImageUtility.float3	AverageXYZ = IntegrateLuminance( _Center.x, _Center.y, _Radius, out MinXYZ, out MaxXYZ, out BlackValues, out SaturatedValues );

            bool	DisableProbe = false;
            if ( BlackValues > BLACK_VALUES_TOLERANCE &&
                MessageBox( "This probe has more than 5% luminance values that are too dark, it's advised you don't use it to calibrate the camera as its values will not be useful.\r\n" +
                            "\r\nDo you wish to disable this probe?",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Warning ) == DialogResult.Yes )
            {
                DisableProbe = true;
            }
            else if ( SaturatedValues > SATURATED_VALUES_TOLERANCE &&
                MessageBox( "This probe has more than 5% luminance values that are saturated, it's advised you don't use it to calibrate the camera as its values will not be useful.\r\n" +
                            "\r\nDo you wish to disable this probe?",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Warning ) == DialogResult.Yes )
            {
                DisableProbe = true;
            }

            if ( DisableProbe )
            {	// Disable probe
                _Probe.m_IsAvailable = false;
                _Probe.m_LuminanceMeasured = 0.0f;
                UpdateUIFromCalibration();
                return;
            }

            _Probe.m_LuminanceMeasured = checkBoxCalibrationUseAverageLuminance.Checked ? AverageXYZ.y : MaxXYZ.y;

            // We now have valid measurement disc infos
            _Probe.m_MeasurementDiscIsAvailable = true;
            _Probe.m_MeasurementCenterX = _Center.x;
            _Probe.m_MeasurementCenterY = _Center.y;
            _Probe.m_MeasurementRadius = _Radius;

            CommitImageToCurrentCalibration();	// We used the current image as reference for this calibration so commit its data
        }
        /// <summary>
        /// Prepares the interpolated calibration table to process the pixels in an image shot with the specified shot infos
        /// </summary>
        /// <param name="_Image"></param>
        public void PrepareCalibrationFor( ImageUtility.Bitmap _Image )
        {
            if ( !_Image.HasValidShotInfo )
                throw new Exception( "Can't prepare calibration for specified image since it doesn't have valid shot infos!" );

            PrepareCalibrationFor( _Image.ISOSpeed, _Image.ShutterSpeed, _Image.Aperture );
        }
Exemple #51
0
        public void ProcessRequest(HttpContext context)
        {
            var nickname = context.Request["nick"];
            var text     = context.Request["data"];
            var product  = context.Request["product"];
            var price    = context.Request["price"];

            if (String.IsNullOrEmpty(nickname) ||
                String.IsNullOrEmpty(product) ||
                String.IsNullOrEmpty(text) ||
                String.IsNullOrEmpty(price))
            {
                return;
            }
            nickname = HttpUtility.UrlDecode(nickname);
            text     = HttpUtility.UrlDecode(text);
            product  = HttpUtility.UrlDecode(product);
            var midword = "为您推荐了";

            Bitmap   theBitmap   = new Bitmap(initialWidth, initialHeight);
            Graphics theGraphics = Graphics.FromImage(theBitmap);

            //呈现质量
            theGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            //背景色
            theGraphics.Clear(Color.FromArgb(255, 255, 255));
            //边框
            //theGraphics.DrawRectangle(new Pen(Color.FromArgb(61, 173, 47), 1), 1, 1, initialWidth - 2,
            //    initialHeight - 2);
            //圆弧边框
            Pen       p    = new Pen(Color.FromArgb(61, 173, 47), 1);
            Rectangle rect = new Rectangle(1, 1, initialWidth - 2, initialHeight - 2);

            using (GraphicsPath path = new ImageUtility().CreateRoundedRectanglePath(rect, 7))
            {
                theGraphics.DrawPath(p, path);
                theGraphics.FillPath(new SolidBrush(Color.White), path);
            }


            string FontType = "微软雅黑";
            Font   theFont  = new Font(FontType, 18f, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);

            //准备工作。定义画刷颜色

            Brush greenBrush = new SolidBrush(Color.FromArgb(61, 173, 47));   //填充的颜色
            Brush greyBrush  = new SolidBrush(Color.FromArgb(144, 144, 144)); //填充的颜色
            //var img = Bitmap.FromFile(baseRoot + "//images//slogo.jpg");//图片地址
            var imgFile = baseRoot + "//images//slogo.jpg";


            var qrcode = QRCodeHelper.CreateQRCodeWithLogo(text, imgFile);

            //var thumbnail = GetThumbnail(img, 35, 35);
            var imgX = (initialWidth - qrcode.Width) / 2;
            var imgY = (initialHeight - qrcode.Height) / 2;

            theGraphics.DrawImage(qrcode, new System.Drawing.Rectangle(imgX, imgY, qrcode.Width, qrcode.Height),
                                  new System.Drawing.Rectangle(0, 0, qrcode.Width, qrcode.Height),
                                  System.Drawing.GraphicsUnit.Pixel);


            nickname = nickname.Length > 4 ? nickname.Substring(0, 4) : nickname;
            midword  = "为您推荐了";
            product  = product.Length > 4 ? product.Substring(0, 5) : product;
            price    = "¥" + price;
            var tips = "(长按识别二维码参团购买)";

            var start = 40;

            if (nickname.Length == 1)
            {
                start = 75;
            }
            else if (nickname.Length == 2)
            {
                start = 60;
            }
            else if (nickname.Length == 3)
            {
                start = 50;
            }
            else if (nickname.Length == 4)
            {
                start = 30;
            }
            theGraphics.DrawString(nickname, theFont, greenBrush, start, 15);
            theGraphics.DrawString(midword, theFont, greyBrush, 115, 15);
            theGraphics.DrawString(product, theFont, greenBrush, 220, 15);

            theGraphics.DrawString(price, theFont, greyBrush, 122, 40);
            theGraphics.DrawString(tips, theFont, greyBrush, 47, 275);

            MemoryStream ms = new MemoryStream();

            theBitmap.Save(ms, ImageFormat.Png);
            //context.Session["code"] = code;
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(ms.ToArray());
            theGraphics.Dispose();
            theBitmap.Dispose();
            ms.Dispose();
        }
        /// <summary>
        /// Builds the custom swatches
        /// </summary>
        /// <param name="_CustomSwatchSamplingLocations">In UV space. XY=Top Left corner, ZW=Bottom Right corner</param>
        public void BuildCustomSwatches( ImageUtility.float4[] _CustomSwatchSamplingLocations )
        {
            if ( m_Texture == null )
                throw new Exception( "Cannot build custom swatched because no texture was captured!" );
            if ( _CustomSwatchSamplingLocations == null )
                throw new Exception( "Invalid swatch parameters!" );
            if ( m_SwatchWidth <= 0 || m_SwatchHeight <= 0 )
                throw new Exception( "Invalid swatch size! Must be > 0!" );

            m_CustomSwatches = new CustomSwatch[_CustomSwatchSamplingLocations.Length];
            for ( int CustomSwatchIndex=0; CustomSwatchIndex < m_CustomSwatches.Length; CustomSwatchIndex++ )
            {
                CustomSwatch	S = new CustomSwatch();
                m_CustomSwatches[CustomSwatchIndex] = S;

                S.Location = _CustomSwatchSamplingLocations[CustomSwatchIndex];
                S.xyY = ComputeAverageSwatchColor( new ImageUtility.float2( S.Location.x, S.Location.y ), new ImageUtility.float2( S.Location.z, S.Location.w ) );
                S.Texture = BuildSwatch( m_SwatchWidth, m_SwatchHeight, S.xyY );
            }
        }