opcncv 转JPEG对JPEG格式进行自定义消息

  • JPEG格式大纲

二话不说,上代码

//图片缓存区设置
#define MAX_PHOTO 4*1024*1024
//不再全局了,不然多线程的话要加锁了
//unsigned char photoTemp[MAX_PHOTO];
//unsigned char photo[MAX_PHOTO + 128];
int copyFile(char *fileRead, char *fileWrite, Point sit)
{
    FILE *fpRead;  // 指向要复制的文件
    FILE *fpWrite;  // 指向复制后的文件
    int readCount;  // 实际读取的字节数
    if ((fpRead = fopen(fileRead, "rb")) == NULL || (fpWrite = fopen(fileWrite, "wb")) == NULL) {
        printf("Cannot open file, press any key to exit!\n");
        return -1;
    }
    unsigned char* photoTemp = (unsigned char*)malloc(MAX_PHOTO);
    unsigned char* photo = (unsigned char*)malloc(MAX_PHOTO + 128);
    memset(photoTemp, 0, MAX_PHOTO);
    memset(photo, 0, MAX_PHOTO + 128);

    //JPEG 开始
    photo[0] = 0XFF;
    photo[1] = 0XD8;
    //JPEG 备份信息
    photo[2] = 0XFF;
    photo[3] = 0XFE;
    //JPEG 备份信息位数
    photo[4] = 0X00;
    photo[5] = 0X80;
    /*******************
    photoTemp[6] = ;
    ~               //备份数据的存储区
    photoTemp[130] =;
    ********************/
    //已经不用这个方法写入值了
    //photo[6] = sit.x >> 24;
    //photo[7] = sit.x >> 16;
    //photo[8] = sit.x >> 8;
    //photo[9] = sit.x & 0xff;

    //photo[10] = sit.y >> 24;
    //photo[11] = sit.y >> 16;
    //photo[12] = sit.y >> 8;
    //photo[13] = sit.y & 0xff;
    //新的赋值方式
    void* temPoint = (void*)(photo + 6);
    Point* point = (Point*)temPoint;
    point->x = sit.x;
    point->y = sit.y;
    // 不断从fileRead读取内容,放在缓冲区,再将缓冲区的内容写入fileWrite
    int infohead = 1;
    while ((readCount = fread(photoTemp, 1, MAX_PHOTO, fpRead)) > 0) {
        if (infohead)
        {
            photoTemp[0] = 0x00;
            photoTemp[1] = 0x00;
            memcpy(photo + 130, photoTemp, MAX_PHOTO);
            infohead = 0;
            fwrite(photo, readCount + 130, 1, fpWrite);
        }
        else
        {
            fwrite(photoTemp, readCount, 1, fpWrite);
        }
    }
    fclose(fpRead);
    fclose(fpWrite);
    //注意释放和置空
    free(photoTemp);
    photoTemp = NULL;
    free(photo);
    photo = NULL;
    return 1;
}

int addJpegInfo(Mat input, char* output, Point sit)
{
    char *deletePath = "temp.jpg";
    imwrite("temp.jpg", input);

    if (1 != copyFile(deletePath, output, sit))
    {
        return -1;
    }
    
    if (remove(deletePath) != 0)
    {
        printf("delete temp file failed!\n");
        return -1;
    }
    return 0;
}
int main()
{
    /*************************************************************************
    * 图片JPEG格式,添加二进制里面添加备注信息
    *************************************************************************/
    char* path = "../../bin/data/豫AY2528四合一截图.jpg";
    char* outPath = "../../bin/data/4.jpg";

    Mat input;
    Point A(400, 500);
    input = imread(path);
    addJpegInfo(input, outPath, A);


    return 0;
}

借鉴作者: https://www.cnblogs.com/jackytang/p/9011127.html

你可能感兴趣的:(opcncv 转JPEG对JPEG格式进行自定义消息)