I recently read the article about JavaScript Image Processing in justany_whitesnow. I wrote very well, so I practiced it,Some encapsulation is made.:
( Function (){ Function Imagetogray (icanvas, URL ){ This . Canvas = Icanvas; This . Ictx = This . Canvas. getcontext ("2D" ); This . Url =URL;} imagetogray. Prototype = {Imread: Function (_ Image ){ VaR Width = _ Image. width, height = _ Image. height; This . Iresize (width, height ); This . Ictx. drawimage (_ image, 0, 0 ); VaR Imagedata =This . Ictx. getimagedata (0, 0 , Width, height), tempmat = New MAT (height, width, imagedata. data); imagedata = Null ; This . Ictx. clearrect (0, 0 , Width, height ); Return Tempmat;}, iresize: Function (_ Width, _ height ){ This . Canvas. width = _ Width; This . Canvas. Height = _ Height;}, rgba2imagedata: Function (_ Imgmat ){ VaR Width = _ Imgmat. Col, height = _ Imgmat. Row, imagedata = This . Ictx. createimagedata (width, height); imagedata. Data. Set (_ imgmat. data ); Return Imagedata;}, render: Function (){ VaR IMG = New Image (); VaR _ This = This ; IMG. onload = Function (){ VaR Mymat = _ This. imread (IMG ); VaR Newimage = Cvtcolor (mymat ); VaR Newiamgedata = _ This. rgba2imagedata (newimage); _ this. ictx. putimagedata (newiamgedata, 0, 0 ) ;}; IMG. SRC = This . Url ;}}; Function MAT (_ row, _ Col, _ data, _ buffer ){ This . Row = _ row | 0 ; This . Col = _ Col | 0 ; This . Channel = 4 ; This . Buffer = _ buffer | New Arraybuffer (_ row * _ Col * 4 ); This . Data = New Uint8clampedarray ( This . Buffer); _ DATA && This . Data. Set (_ data ); This . Bytes = 1 ; This . Type = "cv_rgba" ;} Function Cvtcolor (_ SRC ){ If (_ SRC. Type & _ SRC. type = "cv_rgba" ){ VaR Row = _ SRC. Row, Col = _ SRC. Col; VaR DST = New MAT (row, col); Data = DST. Data, data2 = _ SRC. Data; VaR Pix1, pix2, pix = _ SRC. row * _ SRC. Col * 4 ; While (Pix) {data [pix -= 4] = data [pix1 = pix + 1] = data [pix2 = pix + 2] = (data2 [pix] * 299 + data2 [pix1] * 587 + data2 [pix2] * 114) /1000 ; Data [pix + 3] = data2 [pix + 3 ] ;}} Else { Return SRC ;} Return DST;} window. imagetogray = Imagetogray ;})();
The call method is as follows:
VaRIcanvas = Document. getelementbyid ("grayimage ");//Canvas ElementVaRImgtogray =NewImagetogray (icanvas, "images/1.jpg"); Imgtogray. Render ();
Here is a complete example :)
I wanted to give an online operation address, but because the garden image has another domain name, getimagedata has a cross-domain security problem, so I 'd like to give it (to run it on a local web service, or directly run it in VS): Click here to download
Finally, let's get the benefits. Haha!