Calculate the area of a photo (WPF chapter)

Source: Internet
Author: User

Yesterday, the old week suddenly wanted to say to the big friends of the UWP app to calculate the size of the photo play, and the old week also indicated that the WPF version of the example. So, give it to the guys today.

WPF is integrated in the. NET Framework, and is part of. NET, never tell me that you learn. NET does not learn WPF, which is not right, including ASP. NET, WCF, WF, and so on, are not in essence detached from. Net.

No nonsense, no one to listen to, let's talk about it.

Unlike the UWP in the WPF library, the image decoding encoding API does not appear to be as powerful as the UWP, presumably because the desktop program can invoke the Win32 API and COM reasons. But the old week has to tell you something. After testing, the WPF method is used to calculate the area of the photo, which is much more performance than GDI, especially for large photos. Before WPF appeared, there was a iamge class under the System.Drawing namespace, and a bitmap class was derived that could be used to calculate the area of the photo. Old week in the N years before a photo area calculator, in addition to calculate the area, you can also enter the unit price (how much per square meter), and then calculate the size of the printing photo and the final price, and has a simple ticket printing function. This program is based on GDI, which is done with the System.Drawing under the namespace, because in that era, WPF has not been invented.

WPF incorporates the decoding/encoding classes of images into UI-related media functions, is located under the System.Windows.Media.Imaging namespace, there is a bitmapimage class, it can read the photo pixel width, as well as the resolution, with these parameters can calculate the area.

However, you have to be aware that the threading security model of WPF is relatively strict, in order to protect the UI thread from unintentional destruction, the BitmapImage class is indirectly inheriting the Dispatcherobject class, and you have to understand that there are dispatcher objects that cannot be manipulated across threads. If you want to display them on the UI, the instance of the bitmap object must belong to the UI thread.

If you're using data binding to worry about performance, you can turn on asynchronous binding, and the WPF binding has a IsAsync property that opens it, and the UI thread uses the worker thread to load the data when it is dispatched. The experiment shows that the more CPU cores you have, the faster you can handle the configuration. Especially when it comes to multimedia, like video, you can't get a computer 50 years ago to talk about performance optimization, you should at least take a computer that's up to time to evaluate. You can not use the social productivity of the spring and autumn Warring States Period to compare with Datang prosperous.

In order to save overhead, you can set decodepixelwidth or decodepixelheight when using an image

property, these two properties do not set at the same time, you set one on the line, so that the image can be automatically calculated when rendering the scale, otherwise it will distort the image, of course, if you want to distort the image, it is another matter.

Setting these two properties does not affect the actual pixels we read from the image, and to get the image width, the pixelwidth and Pixelheight properties should be accessed, and decodepixelheight/width will not affect the values of the two properties. In addition, the resolution in both horizontal and vertical directions can be obtained through the Dpix and Dpiy properties.

Well, in the same way, a data class is encapsulated first.

     Public classphotodata:inotifypropertychanged {#regionPrivate fieldsintwidth =default(int), height =default(int); DoubleDpix =default(Double), Dpiy =default(Double); BitmapImage Bitmap=NULL; DoubleArea ; #endregion        #regionINotifyPropertyChanged Members Public EventPropertyChangedEventHandler propertychanged; #endregion        #regionconstructor function PublicPhotodata (stringFilePath) {            //instantiating an Image objectPhotoimage =NewBitmapImage (); Photoimage.decodepixelwidth= -; //Initializing an imagePhotoimage.begininit (); Photoimage.urisource=NewUri (FilePath);            Photoimage.endinit (); //get the required parametersWidth =Photoimage.pixelwidth; Height=Photoimage.pixelheight; Dpix=Photoimage.dpix; Dpiy=Photoimage.dpiy; //Calculate AreaComputearea (); }        #endregion        #regionMethodPrivate voidOnPropertyChanged ([Callermembername]stringPrpname ="")        {             This. PropertyChanged?. Invoke ( This,NewPropertyChangedEventArgs (prpname)); }        /// <summary>        ///Calculate Area/// </summary>        Private voidComputearea () {//Convert width and height to inches first            DoubleINCHW = Width/Dpix; DoubleInchh = Height/Dpiy; /*area in square meters 1 inches = 2.54 centimeters*/ Area= (INCHW *2.54d) * (INCHH *2.54d) /10000d; }        #endregion        #regionProperty/// <summary>        ///Photo Width/// </summary>         Public intWidth {Get{returnwidth;} Private Set            {                if(Value! =width) {Width=value;                OnPropertyChanged (); }            }        }        /// <summary>        ///Photo Height/// </summary>         Public intHeight {Get{returnheight;} Private Set            {                if(Value! =height) {Height=value;                OnPropertyChanged (); }            }        }        /// <summary>        ///Horizontal Resolution/// </summary>         Public DoubleDpix {Get{returnDpix;} Private Set            {                if(Dpix! =value) {Dpix=value;                OnPropertyChanged (); }            }        }        /// <summary>        ///Vertical Resolution/// </summary>         Public DoubleDpiy {Get{returnDpiy;} Private Set            {                if(Value! =Dpiy) {Dpiy=value;                OnPropertyChanged (); }            }        }        /// <summary>        ///Image Instance/// </summary>         PublicBitmapImage Photoimage {Get{returnbitmap;} Private Set            {                if(Bitmap! =value) {Bitmap=value;                OnPropertyChanged (); }            }        }        /// <summary>        ///area (sqm)/// </summary>         Public DoubleArea {Get{returnArea ;} Private Set            {                if(Value! =Area ) { Area=value;                OnPropertyChanged (); }            }        }        #endregion    }

I don't explain this much, I should know better than yesterday. Note that the unit I used today is square meters, calculate the square centimeter after dividing by 10000.

In a similar way, we first calculate the area of a single photo and put it into a collection.

                string[] files =Openfiledlg.filenames; //Start Calculationphotolist.                Clear (); IsRunning=true; foreach(stringFinchfiles) {                    Try{photodata Data=NewPhotodata (f); Photolist.                    ADD (data); }                    Catch(Exception ex) {//Log Exception InformationTrace.WriteLine ($"{DateTime.Now.ToLongTimeString ()}--{ex. Message}"); Continue; }                }

Then, the total area is counted.

                double Totalarea = photolist. Sum (d + =                {                    if (double). Isinfinity (D.area))                    {                        return  0d;                    }                     return D.area;                });

In order to make this program more vivid and lovable, more connotation, the old week also uses the speech reading API, under the System.Speech.Synthesis namespace.

                // Voice reading                Task.run (() =                {                    usingnew  SpeechSynthesizer ())                    {                        Symthedizer . Speak (msg);                    }                });

Use Task to variant aloud, without affecting the rendering of content on the UI.

Please look at the final result.

Well, it's time for dinner, and today's cowhide is blown here, and there's room to continue blowing.

Sample source code Download

Calculate the area of a photo (WPF chapter)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.