Multimedia programming--ios camera image grab Tool class

Source: Internet
Author: User

The tool class provides a preview image screen, automatically handles rotation, and captures the image proactively (so that the frame rate can be infinitely large)

The interface of the system is the asynchronous receive image, like I this obsessive-compulsive disorder how to bear, must be passive receive the image of the way to the active crawl.


Header file


#import <Foundation/Foundation.h> #import <avfoundation/avfoundation.h>//These ratios are all 4:3 of the scale. typedef enum tkvideoframesize{    tkvideoframe480x360     = 480  << |    tkvideoframe720x540     = 720  << 16 | 540,//With this resolution, the efficiency will be much faster. }tkvideoframesize; @interface tkvideocapture:nsobject <avcapturevideodataoutputsamplebufferdelegate>-(BOOL) Create: (uiview*) Preview frame: (tkvideoframesize) type;-(BOOL) destory;-(BOOL) Start;-(bool) stop;//return byte order BGRA BGRA The image data. -(uint8_t*) Get_image_rgb32: (uint32_t*) length; @end




Implementation file: (the use of the lock can go to the previous article to find)


#import "TKVideoCapture.h" #import <UIKit/UIKit.h> #import <CoreGraphics/CoreGraphics.h> #import <    corevideo/corevideo.h> #import <CoreMedia/CoreMedia.h> #import "TKLock.h" @interface tkvideocapture () {    Tkvideoframesize _frametype;    uiview* _preview;    avcapturesession* _capturesession;    avcapturevideopreviewlayer* _capturepreview;    Avcapturevideodataoutput * _CAPTUREOUTPUT;    Avcapturedevice* _capturedevice;        avcapturedeviceinput* _captureinput; uint8_t* _buffer_temp; Each frame of data is stored in this cache uint8_t* _buffer_obox;    Copy from Tempbuf When you need to use it. CGRect _subimagerect;        The location of the child picture. Tklock* _buffer_lock;} @end @implementation tkvideocapture-(void) do_create{self->_capturedevice = [Avcapturedevice    Defaultdevicewithmediatype:avmediatypevideo]; Self->_captureinput = [AvcaptUredeviceinput Deviceinputwithdevice:self->_capturedevice Error:nil];        Self->_captureoutput = [[Avcapturevideodataoutput alloc] init];        if (self->_captureoutput) [Self->_captureoutput setalwaysdiscardslatevideoframes:true];    dispatch_queue_t queue = dispatch_queue_create ("Cameraqueue", NULL);        [Self->_captureoutput setsamplebufferdelegate:self Queue:queue];            Dispatch_release (queue);    nsstring* key = (nsstring*) Kcvpixelbufferpixelformattypekey;        nsnumber* value = [NSNumber Numberwithunsignedint:kcvpixelformattype_32bgra];        nsdictionary* videosettings = [nsdictionary dictionarywithobject:value Forkey:key];    [Self->_captureoutput setvideosettings:videosettings];        Self->_capturesession = [[Avcapturesession alloc] init];    uint16_t width = (uint16_t) (((uint32_t) _frametype) >> 16);        uint16_t height = (uint16_t) (((uint32_t) _frametype) & 0xFFFF); _buffer_temp = (uint8_t*) malloc (Width * height * 4);        _buffer_obox = (uint8_t*) malloc (Width * height * 4); 0.75 is the predetermined proportional switch (_frametype) {case tkvideoframe480x360: {_capturesession.sessionpreset =            avcapturesessionpreset640x480;            _subimagerect = CGRectMake ((640-360)/2, 0, 360, 480);        Break } case tkvideoframe720x540: {_capturesession.sessionpreset = avcapturesessionpresetiframe1280x72            0;            _subimagerect = CGRectMake ((1280-540)/2, 0, 540, 720);        Break    } Default:break;        } if (Self->_captureinput! = nil) [Self->_capturesession addinput:self->_captureinput];        [Self->_capturesession addoutput:self->_captureoutput];    Self->_capturepreview = [Avcapturevideopreviewlayer layerwithsession:self->_capturesession];    Self->_capturepreview.frame = self->_preview.bounds;//cgrectmake (100, 0, 100, 100); Self->_capturepreview.videogravity = AvlayervIdeogravityresizeaspectfill;        Self->_capturepreview.connection.videoorientation = [self getorientation];        [Self->_preview.layer addsublayer:self->_capturepreview];    _buffer_lock = [[Tklock alloc] init]; [_buffer_lock open];}    -(BOOL) Create: (uiview*) Preview frame: (tkvideoframesize) type{self->_frametype = type;        Self->_preview = preview;        [Self Performselectoronmainthread: @selector (do_create) withobject:self waituntildone:true]; return true;} -(avcapturevideoorientation) getorientation{uiinterfaceorientation orientation = [UIApplication sharedApplication].    Statusbarorientation;        Switch (orientation) {case Uiinterfaceorientationportrait:return avcapturevideoorientationportrait;        Case Uiinterfaceorientationportraitupsidedown:return Avcapturevideoorientationportraitupsidedown;        Case Uiinterfaceorientationlandscapeleft:return Avcapturevideoorientationlandscapeleft; Case UiinterfaceorientatIonlandscaperight:return Avcapturevideoorientationlandscaperight; } return avcapturevideoorientationlandscapeleft;}    -(void) do_destory{[_buffer_lock Close];    [_buffer_lock release];        _buffer_lock = nil;    Free (_buffer_temp);    Free (_buffer_obox);    _buffer_temp = NULL;        _buffer_obox = NULL;    [Self->_capturesession stoprunning];    [Self->_capturepreview Removefromsuperlayer];    [Self->_captureoutput release];    [Self->_capturesession release];    Self->_capturesession = nil;    Self->_capturepreview = nil;    Self->_captureoutput = nil;    Self->_capturedevice = nil;    Self->_captureinput = nil; Self->_preview = nil;}    -(BOOL) destory{[self performselectoronmainthread: @selector (do_destory) withobject:self waituntildone:true]; return true;} -(void) Captureoutput: (Avcaptureoutput *) captureoutput Didoutputsamplebuffer: (cmsamplebufferref) SampleBuffer Fromconnection: (avcaptureconnection *) connection{cvimagebufferref imagebuffer = Cmsamplebuffergetimagebuffer (Samplebuffer);    Cvpixelbufferlockbaseaddress (imagebuffer,0);        uint8_t* baseaddress = (uint8_t *) cvpixelbuffergetbaseaddress (imagebuffer);    size_t width = cvpixelbuffergetwidth (imagebuffer);    size_t height = cvpixelbuffergetheight (imagebuffer);        size_t Bytesperrow = Cvpixelbuffergetbytesperrow (Imagebuffer);    Cgcolorspaceref colorspace = Cgcolorspacecreatedevicergb ();        Cgdataproviderref Provider = Cgdataprovidercreatewithdata (null, baseaddress, bytesperrow * height, null);                                        Cgimageref imageref = cgimagecreate (width, height, 8, Bytesperrow, ColorSpace, Kcgbitmapbyteorder32little|kcgimagealphapremultipliedfirst, provider, NULL, False,        Kcgrenderingintentdefault);        Cgimageref subimageref = Cgimagecreatewithimageinrect (Imageref, _subimagerect);    size_t subwidth = _subimagerect.size.height; size_t Subheight = _subimagerect.size.width; Cgcontextref context = Cgbitmapcontextcreate (NULL, Subwidth, Subheight, Cgimagegetbitsper                                  Component (Subimageref), 0, Cgimagegetcolorspace (subimageref),        Cgimagegetbitmapinfo (Subimageref));    CGCONTEXTTRANSLATECTM (context, 0, subheight);    CGCONTEXTROTATECTM (context,-M_PI/2);    Cgcontextdrawimage (context, CGRectMake (0, 0, Subheight, subwidth), subimageref);        uint8_t* data = (uint8_t*) cgbitmapcontextgetdata (context);    [_buffer_lock Lock];    memcpy (_buffer_temp, data, Subwidth * subheight * 4);        [_buffer_lock unlock];    Cgcontextrelease (context);    Cgimagerelease (IMAGEREF);    Cgimagerelease (SUBIMAGEREF);    Cgdataproviderrelease (provider);    Cgcolorspacerelease (ColorSpace); Cvpixelbufferunlockbaseaddress (imagebuffer,0);} -(void) do_start{[self->_capturesession startrunning];} -(void) do_stop{[Self->_captureseSsion stoprunning];}    -(BOOL) start{[self performselectoronmainthread: @selector (Do_start) withobject:self waituntildone:true]; return true;}    -(BOOL) stop{[self performselectoronmainthread: @selector (do_stop) withobject:self waituntildone:true]; return true;}    -(uint8_t*) Get_image_rgb32: (uint32_t*) length{uint16_t width = (uint16_t) (((uint32_t) _frametype) >> 16);        uint16_t height = (uint16_t) (((uint32_t) _frametype) & 0xFFFF);    Output data acquisition from the camera [_buffer_lock lock];    memcpy (_buffer_obox, _buffer_temp, Width * height * 4);        [_buffer_lock unlock];        if (length) *length = width * Height * 4; return _buffer_obox;} @end



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.