Imagesharp an open source project focused on Netcore platform image processing

Source: Internet
Author: User
Tags base64 dashed line drawtext

What we are sharing today is a focus on Netcore platform image processing of open source project, frankly for this article to take the name of 5 minutes, may be the word poor or want to better express the role of this open source project, the project has many functions in image processing, such as: scaling, cropping, painting, combination of pictures and so on, today is mainly about the actual example of how she can draw and generate verification codes.

    • Brief introduction Imagesharp
    • Try drawing two lines (solid lines and dashed lines)
    • Generate a thumbnail image
    • stooped on the picture
    • Make a verification code picture
    • Combine razorpage templates to show captcha images
Brief introduction Imagesharp

Imagesharp is an image-processing scheme for the Netcore platform extension, with the latest NuGet downloads up to 4,034 times, and the author team has just updated the package in the last one months; Yes, it's the latest because her predecessor and previous versions are very popular. Download volume is also high ; her git project address: Https://github.com/SixLabors/ImageSharp. If your project is the same as I was in version 2.0 (2.0 skipped), you can download the corresponding package directly from the VS NuGet console, and note that the following two packages are downloaded separately:

install-package sixlabors.imagesharp-version 1.0.0-beta0001

install-package sixlabors.imagesharp.drawing-version 1.0.0-beta0001

Imagesharp usage has been written by friends before, but mainly for the previous version, this chapter is mainly used in the latest, some of the wording may be different.

Try drawing two lines (solid lines and dashed lines)

Here will use her to draw two straight lines and save as a picture, mainly play a role in the introduction, first to see the actual line of the following code:

var path = @ "D:\F\ learning \vs2017\netcore\study.aspnetcore\webapp02-1\wwwroot\images";            Default solid line            using (image<rgba32> image = New image<rgba32> (.))   //Canvas size            {                Image. Mutate (x = x).                        BackgroundColor (Rgba32.whitesmoke).   Canvas background                            drawlines (                            rgba32.hotpink,//Font Color                            5,   //font size                            new sixlabors.primitives.pointf[]{                                    new Vector2 (Ten),                                    new Vector2 (Max, Max),                                    new Vector2 (+)                            }//2.1-wire coordinates)                    ;                Image. Save ($ "{path}/1.png"); Save            }

Always to step I have notes on the text, here mainly through 2.1 lines to draw graphics,Vector2 object is worth noting is C # two-dimensional coordinates (x, Y) object, in fact, in addition to Vector2 there are Vector3(three-dimensional coordinates), etc., This is not unfamiliar to the friends who do u3d, honestly this is also when I contact u3d when I know there is this class. See below:

A corner constructed from two 2.1 lines, below to see the dashed line drawn:

Dashed            using (image<rgba32> Image = new image<rgba32>)   //Canvas size            {                Image. Mutate (x = x).                        BackgroundColor (Rgba32.whitesmoke).   Canvas background                            drawlines (                            pens.dash (Rgba32.hotpink, 5),   //font size                            new sixlabors.primitives.pointf[]{                                    New Vector2 (Ten),                                    new Vector2 (Max, Max),                                    new Vector2 (+)                            }//2.1-wire coordinates)                    ;                Image. Save ($ "{path}/2.png"); Save            }

The steps are similar, just call the extension method of DrawLines, other line examples do not say that you do their own experiments.

Generate thumbnails and stooped on a picture

For the image type of the site, the thumbnail is common, here with Imagesharp to generate thumbnails is very simple, this example uses 8.png sample to generate thumbnail image 8-1.png, directly see the example below is netstandard 1.3+ Example:

Thumbnail            using (image<rgba32> image = Image.load ($ "{path}/8.png"))            {                image. Mutate (x = x)                     . Resize (image. WIDTH/2, image. HEIGHT/2)                     );                Image. Save ($ "{path}/8-1.png");            }

In order to better compare the differences between thumbnails and the original image here, the properties of the two graphs are made for example:

Can be very good to see the thumbnail file size and pixels are halved , the actual thumbnail is not necessarily halved, this is all controlled by the parameters resize (width,height);

stooped: in the picture we want to draw the word, in fact, similar to a watermark of a requirement, the following is the stooped code on the image:

stooped             var install_family = new Fontcollection (). Install (                System.IO.Path.Combine (Directory.GetCurrentDirectory (), "Wwwroot/bak", "Stkaiti". TTF ")                //@" C:\Windows\Fonts\STKAITI. TTF "   //font file                );            var font = new Font (install_family, +);  Font            using (image<rgba32> image = Image.load ($ "{path}/8.png"))            {                image. Mutate (x = x)                     . DrawText (                        "Hello, I am God ox",   //text content                         font,                         rgba32.hotpink,                         new Vector2 ()                         , Textgraphicsoptions.default)                     );                Image. Save ($ "{path}/8-2.png");            }

Here with Imagesharp on the picture stooped need to note: font , because the Windows system comes with a font problem here in the case of Stkaiti.ttf font file, it is stored in C:\Windows\Fonts\STKAITI . TTF directory, of course, you can directly copy it to our project as follows I here the example of the same practice (this is only tested under Windows available, has not yet tested Linux directly using the font file is feasible);

Make a verification code picture

Below we will use her to draw a verification code type of picture, usually the verification code has a number of points and lines to interfere, there is already a picture line example, here show how to draw points:

Draw a point (the point of the rule, others write the algorithm yourself) var dianwith = 1;  Dot width var xx = 300;  Picture width var yy = 200;  Picture height var xx_space = 10;    The x-coordinate interval between points and points var yy_space = 5;            Y-coordinate interval var listpath = new list<ipath> ();                for (int i = 0, i < xx/xx_space; i++) {for (int j = 0; J < Yy/yy_space; J + +)                    {var position = new Vector2 (i * xx_space, J * yy_space);                    var linerline = new Linearlinesegment (position, position);                    var shapespath = new SixLabors.Shapes.Path (linerline);                Listpath.add (Shapespath);                }} using (image<rgba32> Image = new image<rgba32> (xx, yy))//canvas Size { Image.                        Mutate (x = x).   BackgroundColor (Rgba32.whitesmoke). Draw on canvas background (Pens.dot (Rgba32.hotpink, Dianwith),//Size new SixLabors.Shapes.PathCollection (Listpath)//coordinate set)                ); Image. Save ($ "{path}/9.png"); Save

The iimageprocessingcontext<tpixel> extension method draw is used here to draw a regular point:

More monotonous, perhaps you can do more beautiful; below to do the verification code picture, mainly by: draw dot + stooped = verification code Picture , here I encapsulated a method directly generated code image:

<summary>///Draw points + stooped = Captcha Pictures///</summary>//<param name= "Content" > Captcha </pa ram>//<param name= "Outimgpath" > Output picture path </param>//<param name= "Fontfilepath" > Font file &lt        ;/param>//<param name= "x" > Picture width </param>//<param name= "y" > Picture height </param> public void Getvalidcode (String content = "I am a god bull", string outimgpath = "d:/f/Learning/VS2 017/netcore/study.aspnetcore/webapp02-1/wwwroot/images/10.png ", String fontfilepath = @" D:\F\ Learn \vs2017\ Netcore\study.aspnetcore\webapp02-1\wwwroot\bak\stkaiti. TTF ", int xx = max, int yy = +) {var dianwith = 1;//dot width var xx_space =  10;    The x-coordinate interval between points and points var yy_space = 5; Y-coordinate interval var wenzilen = content.  Length; Literal length var MaxX = Xx/wenzilen; Maximum x width of each text var Prevwenzix = 0;            The x-coordinate of the preceding textvar size = 16;//font size//font var install_family = new Fontcollection (). Install (Fontfilepath//@ "C:\Windows\Fonts\STKAITI.            TTF "//windows system font file);  var font = new Font (install_family, size);            Font//point coordinate var listpath = new list<ipath> ();                for (int i = 0, i < xx/xx_space; i++) {for (int j = 0; J < Yy/yy_space; J + +)                    {var position = new Vector2 (i * xx_space, J * yy_space);                    var linerline = new Linearlinesegment (position, position);                    var shapespath = new SixLabors.Shapes.Path (linerline);                Listpath.add (Shapespath);            }}//Paint using (image<rgba32> Image = new image<rgba32> (xx, yy))//Canvas size {image. Mutate (x = {//Draw point Var IMGPROC = X.backgroundcolor (Rgba32.whitesmoke).                              Draw on canvas background (Pens.dot (Rgba32.hotpink, Dianwith),//Size                    New SixLabors.Shapes.PathCollection (Listpath)//coordinate set);                        stooped for (int i = 0; i < Wenzilen; i++) {//the current word to be output var Nowwenzi = content.                        Substring (i, 1);                        Text coordinate var wenxy = new Vector2 ();                        var maxxx = Prevwenzix + (maxx-size); wenxy.x = new Random ().                        Next (Prevwenzix, maxxx); WENXY.Y = new Random ().                        Next (0, yy-size);                        Prevwenzix = Convert.ToInt32 (Math.floor (wenxy.x)) + size;                       Stooped Imgproc.drawtext (Nowwenzi,//text content font,     I% 2 > 0?                    Rgba32.HotPink:Rgba32.Red, Wenxy, Textgraphicsoptions.default);                }                }); Save to picture image.            Save (Outimgpath); }        }

By simply calling Getvalidcode ("I am a god ox"), return Page (), get the result of the CAPTCHA image:

The text seems to be in front of the point, but it doesn't matter just need to put the painting point and stooped order to modify the line, here does not map;

Combine razorpage templates to show captcha images

The above section is generated a verification code picture, of course, we do not need to generate code physical images of the actual scene, only need to return a stream or base64 output to the Web interface on the line, we can look at the image<tpixel> save time extension method:

View Code

Well, a bit more, we just have to understand that she can turn base64,stream, save as a picture, etc. here we will use the Saveaspng (stream) method, and then get his byte[], the following code:

<summary>//Draw points + stooped = verification Code byte[]///</summary>//<param name= "Content" > Captcha </ param>//<param name= "Outimgpath" > Output picture path </param>//<param name= "Fontfilepath" > Font files &        lt;/param>//<param name= "x" > Picture width </param>//<param name= "y" > Picture height </param> Public byte[] Getvalidcodebyte (String content = "I am a god bull", string fontfilepath = @ " D:\F\ study \vs2017\netcore\study.aspnetcore\webapp02-1\wwwroot\bak\stkaiti.            TTF ", int xx = max, int yy = +) {var bb = default (byte[]);  try {var dianwith = 1;//dot width var xx_space = 10;    The x-coordinate interval between points and points var yy_space = 5; Y-coordinate interval var wenzilen = content.  Length; Literal length var MaxX = Xx/wenzilen; Maximum x width of each text var Prevwenzix = 0; The x-coordinate of the preceding text is var size = 16;Font size//font var install_family = new Fontcollection (). Install (Fontfilepath//@ "C:\Windows\Fonts\STKAITI.                TTF "//windows system font file);  var font = new Font (install_family, size);                Font//point coordinate var listpath = new list<ipath> ();                    for (int i = 0, i < xx/xx_space; i++) {for (int j = 0; J < Yy/yy_space; J + +)                        {var position = new Vector2 (i * xx_space, J * yy_space);                        var linerline = new Linearlinesegment (position, position);                        var shapespath = new SixLabors.Shapes.Path (linerline);                    Listpath.add (Shapespath);   }}//Paint using (image<rgba32> Image = new image<rgba32> (xx, yy)) Canvas size {image. Mutate (x= = {var imgproc = x; stooped for (int i = 0; i < Wenzilen; i++) {// The current word var Nowwenzi = content to output.                            Substring (i, 1);                            Text coordinate var wenxy = new Vector2 ();                            var maxxx = Prevwenzix + (maxx-size); wenxy.x = new Random ().                            Next (Prevwenzix, maxxx); WENXY.Y = new Random ().                            Next (0, yy-size);                            Prevwenzix = Convert.ToInt32 (Math.floor (wenxy.x)) + size;                                   Stooped Imgproc.drawtext (Nowwenzi,//text content Font, I% 2 > 0? Rgba32.HotPink:Rgba32.Red, Wenxy, TextGraphicsoptions.default);   }//Draw point Imgproc.backgroundcolor (Rgba32.whitesmoke).   Draw on canvas background (Pens.dot (Rgba32.hotpink, Dianwith),                                 Size new SixLabors.Shapes.PathCollection (Listpath)//coordinate set                    );                    }); using (MemoryStream stream = new MemoryStream ()) {image.                        Saveaspng (stream); BB = stream.                    GetBuffer ();        }}} catch (Exception ex) {} return bb; }

The method returns a byte[] array, and then requests the Razor interface through the HttpGet way, the front end can get to this captcha image byte[];

<summary>//        get Get Verification code picture byte[]///</summary>//        <returns></returns>        Public Fileresult Ongetvalidcode ()        {            var Codebb = Getvalidcodebyte (DateTime.Now.ToString ("mmssfff"));            Return File (Codebb, "image/png");        }

We get the verification code by GET request: Http://localhost:1120/login?handler=ValidCode, then get the effect:

This is the end of this article, if you have a good help, may wish to order a "like", together to promote the development of Netcore, thank you.

This article transferred from: http://www.cnblogs.com/wangrudong003/p/7656842.html

Imagesharp an open source project focused on Netcore platform image processing

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.