USB拍照功能


常用的USB拍照功能代码:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <linux/types.h>
#include <linux/videodev2.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include <sys/mman.h>
#include <errno.h>
#include <assert.h>
#include<QDebug>
#include<QUuid>
#include<QDir>
#include<QDateTime>
#include "uvcTest.h"
#define FILE_VIDEO  "/dev/video0"
#define JPG "./image%d.jpg"
BUFTYPE *usr_buf;
static unsigned int n_buffer = 0;
//set video capture ways(mmap)
int init_mmap(int fd)
{
    //to request frame cache, contain requested counts
    struct v4l2_requestbuffers reqbufs;
    //request V4L2 driver allocation video cache
    //this cache is locate in kernel and need mmap mapping
    memset(&reqbufs, 0, sizeof(reqbufs));
    reqbufs.count = 4;
    reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    reqbufs.memory = V4L2_MEMORY_MMAP;
    if(-1 == ioctl(fd,VIDIOC_REQBUFS,&reqbufs)){
        perror("Fail to ioctl ‘VIDIOC_REQBUFS‘");
        exit(EXIT_FAILURE);
    }
    n_buffer = reqbufs.count;
    printf("n_buffer = %d\n", n_buffer);
//    usr_buf = (BUFTYPE *)calloc(reqbufs.count, sizeof(usr_buf));
    usr_buf = new BUFTYPE[reqbufs.count*sizeof(BUFTYPE)];
    if(usr_buf == NULL){
        printf("Out of memory\n");
        exit(-1);
    }
    //map kernel cache to user process
    for(n_buffer = 0; n_buffer < reqbufs.count; ++n_buffer){
        //stand for a frame
        struct v4l2_buffer buf;
        memset(&buf, 0, sizeof(buf));
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = n_buffer;
        //check the information of the kernel cache requested
        if(-1 == ioctl(fd,VIDIOC_QUERYBUF,&buf))
        {
            perror("Fail to ioctl : VIDIOC_QUERYBUF");
            exit(EXIT_FAILURE);
        }
        usr_buf[n_buffer].length = buf.length;
        usr_buf[n_buffer].start =
            (char *)mmap(
                    NULL,
                    buf.length,
                    PROT_READ | PROT_WRITE,
                    MAP_PRIVATE,
                    fd,
                    buf.m.offset
                );
        if(MAP_FAILED == usr_buf[n_buffer].start)
        {
            perror("Fail to mmap");
            exit(EXIT_FAILURE);
        }
    }
    return 0;
}
//initial camera device
int init_camera_device(int fd)
{
    //decive fuction, such as video input
    struct v4l2_capability cap;
    //video standard,such as PAL,NTSC
    struct v4l2_standard std;
    //frame format
    struct v4l2_format tv_fmt;
    //check control
    struct v4l2_queryctrl query;
    //detail control value
    struct v4l2_fmtdesc fmt;
    int ret;
    //get the format of video supply
    memset(&fmt, 0, sizeof(fmt));
    fmt.index = 0;
    //supply to image capture
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    // show all format of supply
    printf("Support format:\n");
    while(ioctl(fd, VIDIOC_ENUM_FMT, &fmt) == 0){
        fmt.index++;
        printf("pixelformat = ‘‘%c%c%c%c‘‘\ndescription = ‘‘%s‘‘\n",fmt.pixelformat & 0xFF, (fmt.pixelformat >> 8) & 0xFF,(fmt.pixelformat >> 16) & 0xFF, (fmt.pixelformat >> 24) & 0xFF,fmt.description);
    }
    //check video decive driver capability
    ret = ioctl(fd, VIDIOC_QUERYCAP, &cap);
    if(ret < 0){
        perror("Fail to ioctl VIDEO_QUERYCAP");
        exit(EXIT_FAILURE);
    }
    //judge wherher or not to be a video-get device
    if(!(cap.capabilities & V4L2_BUF_TYPE_VIDEO_CAPTURE))
    {
        printf("The Current device is not a video capture device\n");
        exit(-1);
    }
    //judge whether or not to supply the form of video stream
    if(!(cap.capabilities & V4L2_CAP_STREAMING))
    {
        printf("The Current device does not support streaming i/o\n");
        exit(EXIT_FAILURE);
    }
    //set the form of camera capture data
    tv_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    tv_fmt.fmt.pix.width = 100;
    tv_fmt.fmt.pix.height = 100;
    tv_fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
    tv_fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
    if (ioctl(fd, VIDIOC_S_FMT, &tv_fmt)< 0) {
        printf("VIDIOC_S_FMT\n");
        exit(-1);
        close(fd);
    }
    //initial video capture way(mmap)
    init_mmap(fd);
    return 0;
}
int open_camera_device(const char *dev_name)
{
    int fd;
    QString devName =QString(QLatin1String(dev_name));
    QString strDevName = QString("sudo chmod 777 %1").arg(devName);
    qDebug()<<"strDevName"<<strDevName;
//    system(strDevName.toStdString().c_str());
    //open video device with block
    fd = open(FILE_VIDEO, O_RDONLY);
    if(fd < 0){
        perror(FILE_VIDEO);
        exit(EXIT_FAILURE);
    }
    return fd;
}
int start_capture(int fd)
{
    unsigned int i;
    enum v4l2_buf_type type;
    //place the kernel cache to a queue
    for(i = 0; i < n_buffer; i++){
        struct v4l2_buffer buf;
        memset(&buf, 0, sizeof(buf));
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        if(-1 == ioctl(fd, VIDIOC_QBUF, &buf)){
            perror("Fail to ioctl ‘VIDIOC_QBUF‘");
            exit(EXIT_FAILURE);
        }
    }
    //start capture data
    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if(-1 == ioctl(fd, VIDIOC_STREAMON, &type)){
        printf("i=%d.\n", i);
        perror("VIDIOC_STREAMON");
        close(fd);
        exit(EXIT_FAILURE);
    }
    return 0;
}
int process_image(void *addr, int length, int count, char *workOrder)
{
    FILE *fp;
    count = 0;
//    static int num = 0;
//    char image_name[20];
    char* image_name;
    QUuid id = QUuid::createUuid();
    QString strId = id.toString();
    strId.append(".jpeg");
//    QString timeName = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
    QString timeName = QString(QLatin1String(workOrder));
    QDir dir("./photo");
    if(!dir.exists())
        dir.mkdir((dir.currentPath()+"/photo"));
    timeName.append(".jpeg");
//    sprintf(image_name, JPG, count++);
//    strId.toLatin1();
    QByteArray ba = timeName.toLatin1();
    image_name=ba.data();
    if((fp = fopen(image_name, "wb")) == NULL){
        perror("Fail to fopen");
        exit(EXIT_FAILURE);
    }
    fwrite(addr, length, 1, fp);
    usleep(500);
    fclose(fp);
    return 0;
}
int read_frame(int fd,char *workOrder)
{
    struct v4l2_buffer buf;
    unsigned int i;
    memset(&buf, 0, sizeof(buf));
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    //put cache from queue
    if(-1 == ioctl(fd, VIDIOC_DQBUF,&buf)){
        perror("Fail to ioctl ‘VIDIOC_DQBUF‘");
        exit(EXIT_FAILURE);
    }
    assert(buf.index < n_buffer);
    //read process space‘s data to a file
    process_image(usr_buf[buf.index].start, usr_buf[buf.index].length,buf.index,workOrder);
//    qDebug()<<QString((char*)usr_buf[buf.index].start);
    if(-1 == ioctl(fd, VIDIOC_QBUF,&buf)){
        perror("Fail to ioctl ‘VIDIOC_QBUF‘");
        exit(EXIT_FAILURE);
    }
    return 1;
}
/**
 * @brief mainloop
 * @param fd        文件描述符
 * @param count     拍摄的图片张数
 * @return
 */
int mainloop(int fd, int count, char *workOrder)
{
//    int count = 10;
    while(count-- > 0)
    {
        for(;;)
        {
            fd_set fds;
            struct timeval tv;
            int r;
            FD_ZERO(&fds);
            FD_SET(fd,&fds);
            /*Timeout*/
            tv.tv_sec = 2;
            tv.tv_usec = 0;
            r = select(fd + 1,&fds,NULL,NULL,&tv);
            if(-1 == r)
            {
                if(EINTR == errno)
                    continue;
                perror("Fail to select");
                exit(EXIT_FAILURE);
            }
            if(0 == r)
            {
                fprintf(stderr,"select Timeout\n");
                exit(-1);
            }
            if(read_frame(fd,workOrder))
                break;
        }
    }
    return 0;
}
void stop_capture(int fd)
{
    enum v4l2_buf_type type;
    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if(-1 == ioctl(fd,VIDIOC_STREAMOFF,&type))
    {
        qDebug()<<"stop"<<fd;
        perror("Fail to ioctl ‘VIDIOC_STREAMOFF‘");
        exit(EXIT_FAILURE);
    }
    return;
}
void close_camera_device(int fd)
{
    unsigned int i;
    for(i = 0;i < n_buffer; i++)
    {
        if(-1 == munmap(usr_buf[i].start,usr_buf[i].length)){
            exit(-1);
        }
    }
    delete[] usr_buf;
//    qDebug()<<"closedf"<<fd;
    if(-1 == close(fd))
    {
        qDebug()<<"close"<<fd;
        perror("Fail to close fd");
        exit(EXIT_FAILURE);
    }
    return;
}
时间: 2024-08-08 04:23:49

USB拍照功能的相关文章

Android 4.4 Kitkat 使能 USB adb 功能

背景 在 Linux-3.8 以后,Android 的内核分支,便去掉了 f_adb,改使用 USB function FS,在用户空间实现 USB adb 功能.这篇文章根据原作者的 Google+ 文章,在 Atmel sama5 开发板上做了测试,将步骤记录如下,供需要使用的读者参考,你也可以查看作者原文:https://plus.google.com/111524780435806926688/posts/AaEccFjKNHE 在 Linux-3.10 上使能 USB ADB 编译内核

UWP开发之Template10实践二:拍照功能你合理使用了吗?(TempState临时目录问题)

最近在忙Asp.Net MVC开发一直没空更新UWP这块,不过有时间的话还是需要将自己的经验和大家分享下,以求共同进步. 在上章[UWP开发之Template10实践:本地文件与照相机文件操作的MVVM实例(图文付原代码)]已经谈到了使用FileOpenPicker进行文件选择,以及CameraCaptureUI进行拍照. 对于文件选择一般进行如下设置就能实现: // 选择多个文件 FileOpenPicker openPicker = new FileOpenPicker(); openPic

相册、图库、拍照功能的访问以及图像角度设置

在我们需要访问UIImagePickerController的时候,一般为选择图片,此时我们可能需要做如下操作: 一.访问相册.图库.拍照功能: 二.图片设置: 1.需要将选择的图片缩小 (等比例): 2.设置图片的形状 (比如:希望选择的图片为圆形): 3.将图片翻转一定的角度 (比如翻转90度.180度等) 以下是我自己的总结的一些方法: 一.访问功能 - (IBAction)changeIconAction:(UITapGestureRecognizer *)sender { // UIA

如何打开USB OTG功能:

一.检查HW原理图,确认是否支持OTG功能(vbus是否供上电,IDDIG pin连接是否正确)二.若HW确认支持OTG功能,则按照以下方法分别打开USB OTG功能及实现挂载: 如何打开USB OTG功能:1).在alps/mediatek/config/[project]/autoconfig/kconfig/project中打开CONFIG_USB_MTK_OTG和CONFIG_USB_MTK_HDRC_HCDCONFIG_USB_MTK_OTG =yCONFIG_USB_MTK_HDRC

WPF中实现拍照功能(利用“WPFMediaKit.dll”)

开始先展示下效果图: -------------------------------下面记录步骤:------------------------------------------------------ 下载“WPFMediaKit.dll”程序开发包,用在项目中添加引用: 在WPF窗口引入并命名: xmlns:wpfMedia="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit" 在界面用到一个V

Android使得手机拍照功能的发展(源共享)

Android系统调用手机拍照功能有两种方法来直接调用手机自带摄像头还有一个就是要当心自己的节拍. 例Camera360 强大的一个在每个操作系统都有一个手机摄影软件:您可以捕捉不同风格,不同特效的照片,同一时候具有云服务和互联网分享功能,全球用户已经超过2.5亿.如今专门的开发一款手机摄影软件肯定没多大意义,已经比只是这些前辈了.我们仅仅需学会怎样调用手机自带的摄像机完毕拍照并把照片获取过来,为用户提供上传头像,发表图文微博,传送图片的功能就可以. 完毕上述的功能十分的简单,甚至不须要在清单文

HTML5+Canvas+jQuery调用手机拍照功能实现图片上传(二)

上一篇只讲到前台操作,这篇专门涉及到Java后台处理,前台通过Ajax提交将Base64编码过的图片数据信息传到Java后台,然后Java这边进行接收处理,通过对图片数据信息进行Base64解码,之后使用流将图片数据信息上传至服务器进行保存,并且将图片的路径地址存进数据库.ok,废话不多说了,直接贴代码吧. 1.前台js代码: $.ajax({ async:false,//是否异步 cache:false,//是否使用缓存 type: "POST", data:{fileData:fi

玩转Android Camera开发(一):Surfaceview预览Camera,基础拍照功能完整demo

杂家前文是在2012年的除夕之夜仓促完成,后来很多人指出了一些问题,琐事缠身一直没有进行升级.后来随着我自己的使用,越来越发现不出个升级版的demo是不行了.有时候就连我自己用这个demo测一些性能.功能点,用着都不顺手.当初代码是在linux下写的,弄到windows里下全是乱码.还要自己改几分钟才能改好.另外,很多人说不能正常预览,原因是我在布局里把Surfaceview的尺寸写死了.再有就是initCamera()的时候设参数失败,直接黑屏退出,原因也是我把预览尺寸和照片尺寸写死了.再有就

Android--启动拍照功能并返回结果

因为没有深入学习拍照这块功能,所以只是简单的调用了一下系统的拍照功能,下面代码: //拍照的方法 private void openTakePhoto(){ /** * 在启动拍照之前最好先判断一下sdcard是否可用 */ String state = Environment.getExternalStorageState(); //拿到sdcard是否可用的状态码 if (state.equals(Environment.MEDIA_MOUNTED)){ //如果可用 Intent inte